context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftLeftLogicalInt1616()
{
var test = new ImmUnaryOpTest__ShiftLeftLogicalInt1616();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local 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 ImmUnaryOpTest__ShiftLeftLogicalInt1616
{
private struct TestStruct
{
public Vector128<Int16> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalInt1616 testClass)
{
var result = Sse2.ShiftLeftLogical(_fld, 16);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data = new Int16[Op1ElementCount];
private static Vector128<Int16> _clsVar;
private Vector128<Int16> _fld;
private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable;
static ImmUnaryOpTest__ShiftLeftLogicalInt1616()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public ImmUnaryOpTest__ShiftLeftLogicalInt1616()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ShiftLeftLogical(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ShiftLeftLogical(
Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ShiftLeftLogical(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ShiftLeftLogical(
_clsVar,
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftLeftLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftLeftLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftLeftLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftLeftLogicalInt1616();
var result = Sse2.ShiftLeftLogical(test._fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ShiftLeftLogical(_fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ShiftLeftLogical(test._fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _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(Vector128<Int16> firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (0 != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0 != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical)}<Int16>(Vector128<Int16><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using PayStuffWeb.Areas.HelpPage.ModelDescriptions;
using PayStuffWeb.Areas.HelpPage.Models;
namespace PayStuffWeb.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using Lucene.Net.Linq;
using Moq;
using NuGet.Lucene.IO;
using NUnit.Framework;
using Remotion.Linq.Clauses.ResultOperators;
namespace NuGet.Lucene.Tests
{
[TestFixture]
public class LucenePackageRepositoryTests : TestBase
{
private Mock<IPackageIndexer> indexer;
private TestableLucenePackageRepository repository;
[SetUp]
public void SetUp()
{
indexer = new Mock<IPackageIndexer>();
repository = new TestableLucenePackageRepository(packagePathResolver.Object, fileSystem.Object)
{
Indexer = indexer.Object,
LucenePackages = datasource,
LuceneDataProvider = provider,
HashProvider = new CryptoHashProvider()
};
}
public class InitializeTests : LucenePackageRepositoryTests
{
[Test]
public void UpdatesTotalPackages()
{
var p = MakeSamplePackage("a", "1.0");
repository.LucenePackages = new EnumerableQuery<LucenePackage>(Enumerable.Repeat(p, 1234));
repository.Initialize();
Assert.That(repository.PackageCount, Is.EqualTo(repository.LucenePackages.Count()));
}
}
public class IncrementDownloadCountTests : LucenePackageRepositoryTests
{
[Test]
public async Task IncrementDownloadCount()
{
var pkg = MakeSamplePackage("sample", "2.1");
indexer.Setup(i => i.IncrementDownloadCountAsync(pkg, CancellationToken.None)).Returns(Task.FromResult(true)).Verifiable();
await repository.IncrementDownloadCountAsync(pkg, CancellationToken.None);
indexer.Verify();
}
}
public class FindPackageTests : LucenePackageRepositoryTests
{
[Test]
public void FindPackage()
{
InsertPackage("a", "1.0");
InsertPackage("a", "2.0");
InsertPackage("b", "2.0");
var result = repository.FindPackage("a", new SemanticVersion("2.0"));
Assert.That(result.Id, Is.EqualTo("a"));
Assert.That(result.Version.ToString(), Is.EqualTo("2.0"));
}
[Test]
public void FindPackage_ExactMatch()
{
InsertPackage("a", "1.0");
InsertPackage("a", "1.0.0.0");
var result = repository.FindPackage("a", new SemanticVersion("1.0.0.0"));
Assert.That(result.Id, Is.EqualTo("a"));
Assert.That(result.Version.ToString(), Is.EqualTo("1.0.0.0"));
}
}
public class ConvertPackageTests : LucenePackageRepositoryTests
{
[Test]
public void TrimsAuthors()
{
var package = SetUpConvertPackage();
package.SetupGet(p => p.Authors).Returns(new[] {"a", " b"});
package.SetupGet(p => p.Owners).Returns(new[] { "c", " d" });
var result = repository.Convert(package.Object);
Assert.That(result.Authors.ToArray(), Is.EqualTo(new[] {"a", "b"}));
Assert.That(result.Owners.ToArray(), Is.EqualTo(new[] {"c", "d"}));
}
[Test]
public void SupportedFrameworks()
{
var package = SetUpConvertPackage();
package.Setup(p => p.GetSupportedFrameworks()).Returns(new[] { VersionUtility.ParseFrameworkName("net40") });
var result = repository.Convert(package.Object);
Assert.That(result.SupportedFrameworks, Is.Not.Null, "SupportedFrameworks");
Assert.That(result.SupportedFrameworks.ToArray(), Is.EquivalentTo(new[] {"net40"}));
}
[Test]
[TestCase("magicsauce", "magicsauce", "0.0", "")]
[TestCase("magicsauce-lite", "magicsauce", "0.0", "lite")]
[TestCase("magicsauce12", "magicsauce", "1.2", "")]
[TestCase("magicsauce123-lite", "magicsauce", "1.2.3", "lite")]
public void SupportedFrameworks_Custom(string expected, string identifier, string version, string profile)
{
var package = SetUpConvertPackage();
package.Setup(p => p.GetSupportedFrameworks()).Returns(new[] { new FrameworkName(identifier, new Version(version), profile) });
var result = repository.Convert(package.Object);
Assert.That(result.SupportedFrameworks, Is.Not.Null, "SupportedFrameworks");
Assert.That(result.SupportedFrameworks.ToArray(), Is.EquivalentTo(new[] { expected }));
}
[Test]
public void DetectsInvalidModifiedTime()
{
var package = SetUpConvertPackage();
Assert.That(package.Object.Version, Is.Not.Null);
fileSystem.Setup(fs => fs.GetLastModified(It.IsAny<string>()))
.Returns(new DateTime(1601, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
Assert.That(package.Object.Version, Is.Not.Null);
var result = repository.Convert(package.Object);
Assert.That(result.Published, Is.EqualTo(result.Created));
}
[Test]
public void Files()
{
var file1 = new Mock<IPackageFile>();
file1.SetupGet(f => f.Path).Returns("path1");
var package = new PackageWithFiles
{
Id = "Sample",
Version = new SemanticVersion("1.0"),
Files = new[] {file1.Object}
};
fileSystem.Setup(fs => fs.OpenFile(It.IsAny<string>())).Returns(new MemoryStream());
var result = repository.Convert(package);
Assert.That(result.Files, Is.Not.Null, "Files");
Assert.That(result.Files.ToArray(), Is.EquivalentTo(new[] {"path1"}));
}
[Test]
public void FilesSkippedWhenDisabled()
{
var file1 = new Mock<IPackageFile>();
file1.SetupGet(f => f.Path).Returns("path1");
var package = new PackageWithFiles
{
Id = "Sample",
Version = new SemanticVersion("1.0"),
Files = new[] { file1.Object }
};
fileSystem.Setup(fs => fs.OpenFile(It.IsAny<string>())).Returns(new MemoryStream());
repository.IgnorePackageFiles = true;
var result = repository.Convert(package);
Assert.That(result.Files, Is.Not.Null, "Files");
Assert.That(result.Files.ToArray(), Is.Empty);
}
[Test]
public void RemovesPlaceholderUrls()
{
var package = SetUpConvertPackage();
package.SetupGet(p => p.IconUrl).Returns(new Uri("http://ICON_URL_HERE_OR_DELETE_THIS_LINE"));
package.SetupGet(p => p.LicenseUrl).Returns(new Uri("http://LICENSE_URL_HERE_OR_DELETE_THIS_LINE"));
package.SetupGet(p => p.ProjectUrl).Returns(new Uri("http://PROJECT_URL_HERE_OR_DELETE_THIS_LINE"));
var result = repository.Convert(package.Object);
Assert.That(result.IconUrl, Is.Null, "IconUrl");
Assert.That(result.LicenseUrl, Is.Null, "LicenseUrl");
Assert.That(result.ProjectUrl, Is.Null, "ProjectUrl");
}
[Test]
public void SetsPath()
{
var package = SetUpConvertPackage();
var result = repository.Convert(package.Object);
Assert.That(result.Path, Is.EqualTo(Path.Combine("package-dir", "Sample.1.0")));
}
}
public class GetUpdatesTests : LucenePackageRepositoryTests
{
[Test]
public void GetUpdates()
{
var a1 = MakeSamplePackage("a", "1.0");
var a2 = MakeSamplePackage("a", "2.0");
var a3 = MakeSamplePackage("a", "3.0");
a3.IsLatestVersion = true;
InsertPackage(a1);
InsertPackage(a2);
InsertPackage(a3);
var result = repository.GetUpdates(new[] {a1}, false, false, new FrameworkName[0]);
Assert.That(result.Single().Version.ToString(), Is.EqualTo(a3.Version.ToString()));
}
[Test]
public void FilterByVersionConstraint()
{
var a1 = MakeSamplePackage("a", "1.0");
var a2 = MakeSamplePackage("a", "2.0");
var a3 = MakeSamplePackage("a", "3.0");
a3.IsLatestVersion = true;
InsertPackage(a1);
InsertPackage(a2);
InsertPackage(a3);
var constraints = new[] { VersionUtility.ParseVersionSpec("[1.0,2.0]") };
var result = repository.GetUpdates(new[] { a1 }, false, false, new FrameworkName[0], constraints);
Assert.That(result.Single().Version.ToString(), Is.EqualTo(a2.Version.ToString()));
}
[Test]
public void FilterByVersionConstraint_ExcludesCurrentVersion()
{
var a1 = MakeSamplePackage("a", "1.0");
var a2 = MakeSamplePackage("a", "2.0");
var a3 = MakeSamplePackage("a", "3.0");
a3.IsLatestVersion = true;
InsertPackage(a1);
InsertPackage(a2);
InsertPackage(a3);
var constraints = new[] { VersionUtility.ParseVersionSpec("[1.0,2.0]") };
var result = repository.GetUpdates(new[] { a2 }, false, false, new FrameworkName[0], constraints);
Assert.That(result.ToList(), Is.Empty);
}
[Test]
public void FilterByTargetFrameworkVersion()
{
var b1 = MakeSamplePackage("b", "1.0");
var a1 = MakeSamplePackage("a", "1.0");
var a2 = MakeSamplePackage("a", "2.0");
var a3 = MakeSamplePackage("a", "3.0");
a2.SupportedFrameworks = new[] {"net20"};
a3.SupportedFrameworks = new[] {"net451"};
a3.IsLatestVersion = true;
InsertPackage(b1);
InsertPackage(a1);
InsertPackage(a2);
InsertPackage(a3);
var result = repository.GetUpdates(new[] {b1, a1}, false, false, a2.GetSupportedFrameworks());
Assert.That(result.Single().Version.ToString(), Is.EqualTo(a2.Version.ToString()));
}
[Test]
public void IncludeAll()
{
var a1 = MakeSamplePackage("a", "1.0");
var a2 = MakeSamplePackage("a", "2.0-pre");
var a3 = MakeSamplePackage("a", "3.0");
a3.IsLatestVersion = true;
InsertPackage(a1);
InsertPackage(a2);
InsertPackage(a3);
var result = repository.GetUpdates(new[] {a1}, true, true, new FrameworkName[0]);
Assert.That(result.Select(p => p.Version.ToString()).ToArray(),
Is.EqualTo(new[] {a2.Version.ToString(), a3.Version.ToString()}));
}
}
public class SearchTests : LucenePackageRepositoryTests
{
[Test]
public void Id()
{
InsertPackage("Foo.Bar", "1.0");
var result = repository.Search(new SearchCriteria("Foo.Bar"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EqualTo(new[] {"Foo.Bar"}));
}
[Test]
public void AllVersions_OrderById_ImplicitlyThenByVersion()
{
InsertPackage("Foo.Bar", "1.0");
InsertPackage("Foo.Bar", "1.1");
InsertPackage("Foo.Bar", "1.2");
var result = repository.Search(new SearchCriteria("Foo.Bar") { SortField = SearchSortField.Id });
Assert.That(result.Select(r => r.Id + ' ' + r.Version).ToArray(), Is.EqualTo(new[] { "Foo.Bar 1.2", "Foo.Bar 1.1", "Foo.Bar 1.0" }));
}
[Test]
public void TokenizeId()
{
InsertPackage("Foo.Bar", "1.0");
InsertPackage("Foo.Baz", "1.0");
var result = repository.Search(new SearchCriteria("Bar"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EqualTo(new[] { "Foo.Bar" }));
}
[Test]
public void TokenizeIdPrefix()
{
InsertPackage("Foo.BarBell.ThingUpdater", "1.0");
InsertPackage("Foo.BarBell.OtherThing", "1.0");
var result = repository.Search(new SearchCriteria("Foo.BarBell"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EquivalentTo(new[] { "Foo.BarBell.ThingUpdater", "Foo.BarBell.OtherThing" }));
}
[Test]
public void TokenizeIdPrefix_LowerCase()
{
InsertPackage("Foo.BarBell.ThingUpdater", "1.0");
InsertPackage("Foo.BarBell.OtherThing", "1.0");
var result = repository.Search(new SearchCriteria("foo.barbell"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EquivalentTo(new[] { "Foo.BarBell.ThingUpdater", "Foo.BarBell.OtherThing" }));
}
[Test]
public void TokenizeIdPrefix_LowerCase_Full()
{
InsertPackage("Microsoft.AspNet.Razor", "1.0");
var result = repository.Search(new SearchCriteria("id:microsoft.aspnet.razor"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EquivalentTo(new[] { "Microsoft.AspNet.Razor" }));
}
[Test]
public void FilterOnTargetFramework_ExactMatch()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new[] {"net40"};
var pkg2 = MakeSamplePackage("Foo.Bar", "2.0");
pkg2.SupportedFrameworks = new[] { "net45" };
InsertPackage(pkg1);
InsertPackage(pkg2);
repository.Initialize();
var result = repository.Search(new SearchCriteria("id:Foo.Bar") { TargetFrameworks = new[] {"net40"} });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FilterOnTargetFramework_CaseInsensitive()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new[] { "net40-Client" };
InsertPackage(pkg1);
repository.Initialize();
var result = repository.Search(new SearchCriteria("id:Foo.Bar") { TargetFrameworks = new[] { "net40" } });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FilterOnTargetFramework_ExactMatch_NonStandardFramework()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new[] { "mono38" };
var pkg2 = MakeSamplePackage("Foo.Bar", "2.0");
pkg2.SupportedFrameworks = new[] { "net45" };
InsertPackage(pkg1);
InsertPackage(pkg2);
repository.Initialize();
var result = repository.Search(new SearchCriteria("id:Foo.Bar") { TargetFrameworks = new[] { "mono38" } });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FilterOnTargetFramework_CompatibleMatch()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new[] { "net20" };
var pkg2 = MakeSamplePackage("Foo.Bar", "2.0");
pkg2.SupportedFrameworks = new[] { "net45" };
InsertPackage(pkg1);
InsertPackage(pkg2);
repository.Initialize();
var result = repository.Search(new SearchCriteria("id:Foo.Bar") { TargetFrameworks = new[] { "net35" } });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FilterOnTargetFramework_CompatibleMatch_WithProfile()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new[] { "net40-cf" };
var pkg2 = MakeSamplePackage("Foo.Bar", "2.0");
pkg2.SupportedFrameworks = new[] { "net45" };
InsertPackage(pkg1);
InsertPackage(pkg2);
repository.Initialize();
var result = repository.Search(new SearchCriteria("id:Foo.Bar") { TargetFrameworks = new[] { "net40-cf" } });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FilterOnTargetFramework_Portable_ExactMatch()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new[] { "portable-net40+sl50+wp80+win80" };
var pkg2 = MakeSamplePackage("Foo.Bar", "2.0");
pkg2.SupportedFrameworks = new[] { "net45" };
InsertPackage(pkg1);
InsertPackage(pkg2);
repository.Initialize();
var result = repository.Search(new SearchCriteria("id:Foo.Bar") { TargetFrameworks = new[] { "portable-net40+sl50+wp80+win80" } });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FilterOnTargetFramework_CompatibleProfile()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new[] { "net40-client" };
var pkg2 = MakeSamplePackage("Foo.Bar", "2.0");
pkg2.SupportedFrameworks = new[] { "net45" };
InsertPackage(pkg1);
InsertPackage(pkg2);
repository.Initialize();
var result = repository.Search(new SearchCriteria("") { TargetFrameworks = new[] { "net40" } });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FilterOnTargetFramework_AllowsPackagesWithNoSupportedFrameworks()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new string[0];
var pkg2 = MakeSamplePackage("Yaz.Jazz", "2.0");
pkg2.SupportedFrameworks = new[] { "net45" };
InsertPackage(pkg1);
InsertPackage(pkg2);
repository.Initialize();
var result = repository.Search(new SearchCriteria("") { TargetFrameworks = new[] { "net40" } });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FileName()
{
var pkg = MakeSamplePackage("Foo.Bar", "1.0");
pkg.Files = new[] {"/lib/net45/baz.dll"};
InsertPackage(pkg);
var result = repository.Search(new SearchCriteria("baz.dll"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EqualTo(new[] { "Foo.Bar" }));
}
[Test]
public void FileNameCaseInsensitive()
{
var pkg = MakeSamplePackage("Foo.Bar", "1.0");
pkg.Files = new[] { "/lib/net45/Baz.DLL" };
InsertPackage(pkg);
var result = repository.Search(new SearchCriteria("baz.dll"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EqualTo(new[] { "Foo.Bar" }));
}
[Test]
public void FileNameFullPath()
{
var pkg = MakeSamplePackage("Foo.Bar", "1.0");
pkg.Files = new[] { "/lib/net45/baz.dll" };
InsertPackage(pkg);
var result = repository.Search(new SearchCriteria("/lib/net45/baz.dll"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EqualTo(new[] { "Foo.Bar" }));
}
[Test]
public void FileNameNoExtension()
{
var pkg = MakeSamplePackage("Foo.Bar", "1.0");
pkg.Files = new[] { "/lib/net45/Biz.Baz.DLL" };
InsertPackage(pkg);
var result = repository.Search(new SearchCriteria("Biz.Baz"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EqualTo(new[] { "Foo.Bar" }));
}
[Test]
public void FileNamePartialMatch()
{
var pkg = MakeSamplePackage("Foo.Bar", "1.0");
pkg.Files = new[] { "/lib/net45/Biz.Baz.DLL" };
InsertPackage(pkg);
var result = repository.Search(new SearchCriteria("Baz"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EqualTo(new[] { "Foo.Bar" }));
}
[Test]
public void UsesAdvancedWhenColonPresent()
{
var query = repository.Search("Tags:remoting", Enumerable.Empty<string>(), allowPrereleaseVersions: true);
AssertComputedQueryEquals(query, "Tags:remot");
}
[Test]
public void AdvancedQueryCaseInsensitiveField()
{
var query = repository.Search("tags:remoting", Enumerable.Empty<string>(), allowPrereleaseVersions: true);
AssertComputedQueryEquals(query, "Tags:remot");
}
[Test]
public void AdvancedSearchUsesFallbackField()
{
var query = repository.Search("NoSuchField:foo", Enumerable.Empty<string>(), allowPrereleaseVersions: true);
AssertComputedQueryEquals(query, "SearchId:foo");
}
[Test]
public void AdvancedSearchMalformedQueryThrows()
{
TestDelegate call = () => repository.Search("(Tags:foo", Enumerable.Empty<string>(), allowPrereleaseVersions: true);
Assert.That(call, Throws.InstanceOf<InvalidSearchCriteriaException>());
}
[Test]
[Description("See http://docs.nuget.org/docs/reference/search-syntax")]
public void AdvancedSearch_PackageId_ExactMatch()
{
var query = repository.Search("PackageId:Foo.Bar", Enumerable.Empty<string>(), allowPrereleaseVersions: true);
AssertComputedQueryEquals(query, "Id:foo.bar");
}
[Test]
[Description("See http://docs.nuget.org/docs/reference/search-syntax")]
public void AdvancedSearch_Id_FuzzyMatch()
{
var query = repository.Search("Id:Foo", Enumerable.Empty<string>(), allowPrereleaseVersions: true);
AssertComputedQueryEquals(query, "SearchId:foo");
}
private static void AssertComputedQueryEquals(IQueryable<IPackage> query, string expectedQuery)
{
LuceneQueryStatistics stats = null;
var result = query.CaptureStatistics(s => { stats = s; }).ToArray();
Assert.That(stats.Query.ToString(), Is.EqualTo(expectedQuery));
}
}
public class LoadFromFileSystemTests : LucenePackageRepositoryTests
{
readonly DateTime lastModified = new DateTime(2001, 5, 27, 0, 0, 0, DateTimeKind.Utc);
readonly string expectedPath = Path.Combine("a", "non", "standard", "package", "location.nupkg");
[Test]
public void LoadFromFileSystem()
{
SetupFileSystem();
repository.LoadFromFileSystem(expectedPath);
fileSystem.Verify();
}
[Test]
public void SetsPublishedDateToLastModified()
{
SetupFileSystem();
fileSystem.Setup(fs => fs.GetLastModified(It.IsAny<string>())).Returns(lastModified);
var result = repository.LoadFromFileSystem(expectedPath);
Assert.That(result.Published.GetValueOrDefault().DateTime, Is.EqualTo(lastModified));
}
[Test]
public void SetsPath()
{
SetupFileSystem();
var result = repository.LoadFromFileSystem(expectedPath);
Assert.That(result.Path, Is.EqualTo(expectedPath));
}
[Test]
public void MakesPathRelative()
{
SetupFileSystem();
var result = repository.LoadFromFileSystem(Path.Combine(Environment.CurrentDirectory, expectedPath));
Assert.That(result.Path, Is.EqualTo(expectedPath));
}
private void SetupFileSystem()
{
var root = Environment.CurrentDirectory;
fileSystem.Setup(fs => fs.Root).Returns(Environment.CurrentDirectory);
fileSystem.Setup(fs => fs.GetFullPath(It.IsAny<string>()))
.Returns<string>(p => Path.Combine(root, p));
fileSystem.Setup(fs => fs.OpenFile(It.IsAny<string>())).Returns(new MemoryStream());
}
}
public class AddDataServicePackageTests : LucenePackageRepositoryTests
{
[SetUp]
public void SetHashAlgorithm()
{
repository.HashAlgorithmName = "SHA256";
}
[Test]
public async Task DownloadAndIndex()
{
var package = new FakeDataServicePackage(new Uri("http://example.com/packages/Foo/1.0"));
fileSystem.Setup(fs => fs.GetFullPath(It.IsAny<string>())).Returns<string>(n => Path.Combine(Environment.CurrentDirectory, n));
await repository.AddPackageAsync(package, CancellationToken.None);
indexer.Verify(i => i.AddPackageAsync(It.IsAny<LucenePackage>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task DownloadAndIndex_DeletesTempFile()
{
var package = new FakeDataServicePackage(new Uri("http://example.com/packages/Foo/1.0"));
fileSystem.Setup(fs => fs.GetFullPath(It.IsAny<string>())).Returns<string>(n => Path.Combine(Environment.CurrentDirectory, n));
await repository.AddPackageAsync(package, CancellationToken.None);
fileSystem.Verify(fs => fs.DeleteFile(It.IsRegex(@"\.tmp[\\/].+\.nupkg.tmp")));
}
[Test]
public async Task DenyPackageOverwrite()
{
var p = MakeSamplePackage("Foo", "1.0");
repository.LucenePackages = (new[] {p}).AsQueryable();
repository.PackageOverwriteMode = PackageOverwriteMode.Deny;
try
{
await repository.AddPackageAsync(p, CancellationToken.None);
Assert.Fail("Expected PackageOverwriteDeniedException");
}
catch (PackageOverwriteDeniedException)
{
}
indexer.Verify(i => i.AddPackageAsync(It.IsAny<LucenePackage>(), It.IsAny<CancellationToken>()), Times.Never);
}
[Test]
public async Task CancelDuringGetDownloadStream()
{
var package = new FakeDataServicePackage(new Uri("http://example.com/packages/Foo/1.0"));
packagePathResolver.Setup(r => r.GetInstallPath(package)).Returns("Foo");
packagePathResolver.Setup(r => r.GetPackageFileName(package)).Returns("Foo.1.0.nupkg");
var insideHandlerSignal = new ManualResetEventSlim(initialState: false);
var proceedFromHandlerSignal = new ManualResetEventSlim(initialState: false);
var exception = new TaskCanceledException("Fake");
repository.MessageHandler = new FakeHttpMessageHandler((req, token) =>
{
insideHandlerSignal.Set();
Assert.True(proceedFromHandlerSignal.Wait(TimeSpan.FromMilliseconds(500)), "Timeout waiting for proceedFromHandlerSignal");
if (token.IsCancellationRequested)
{
throw exception;
}
});
var cts = new CancellationTokenSource();
var cancelTask = Task.Run(() =>
{
Assert.True(insideHandlerSignal.Wait(TimeSpan.FromMilliseconds(500)), "Timeout waiting for MessageHandler.SendAsync");
cts.Cancel();
proceedFromHandlerSignal.Set();
});
try
{
await repository.AddPackageAsync(package, cts.Token);
await cancelTask;
Assert.Fail("Expected TaskCanceledException");
}
catch (TaskCanceledException ex)
{
Assert.That(ex, Is.SameAs(exception), "Expected spcific instance of TaskCanceledException");
}
}
}
private Mock<IPackage> SetUpConvertPackage()
{
var package = new Mock<IPackage>().SetupAllProperties();
package.SetupGet(p => p.Id).Returns("Sample");
package.SetupGet(p => p.Version).Returns(new SemanticVersion("1.0"));
package.SetupGet(p => p.DependencySets).Returns(new List<PackageDependencySet>());
fileSystem.Setup(fs => fs.OpenFile(It.IsAny<string>())).Returns(new MemoryStream());
package.Setup(p => p.GetStream()).Returns(new MemoryStream());
Assert.That(package.Object.Version, Is.Not.Null);
return package;
}
public class PackageWithFiles : LocalPackage
{
public IEnumerable<IPackageFile> Files { get; set; }
public PackageWithFiles()
{
DependencySets = Enumerable.Empty<PackageDependencySet>();
}
public override void ExtractContents(IFileSystem fileSystem, string extractPath)
{
}
protected sealed override IEnumerable<IPackageFile> GetFilesBase()
{
return Files ?? new IPackageFile[0];
}
public override Stream GetStream()
{
return new MemoryStream();
}
protected override IEnumerable<IPackageAssemblyReference> GetAssemblyReferencesCore()
{
return Enumerable.Empty<IPackageAssemblyReference>();
}
public override IEnumerable<FrameworkName> GetSupportedFrameworks()
{
return Enumerable.Empty<FrameworkName>();
}
}
class FakeDataServicePackage : DataServicePackage
{
public FakeDataServicePackage(Uri packageStreamUri)
{
Id = "Sample";
Version = "1.0";
var context = new Mock<IDataServiceContext>();
context.Setup(c => c.GetReadStreamUri(It.IsAny<object>())).Returns(packageStreamUri);
var prop = typeof(DataServicePackage).GetProperty("Context", BindingFlags.NonPublic | BindingFlags.Instance);
prop.SetValue(this, context.Object);
}
}
public class TestableLucenePackageRepository : LucenePackageRepository
{
public HttpMessageHandler MessageHandler { get; set; }
public TestableLucenePackageRepository(IPackagePathResolver packageResolver, IFileSystem fileSystem)
: base(packageResolver, fileSystem)
{
MessageHandler = new FakeHttpMessageHandler((req, cancel) => {});
}
protected override IPackage OpenPackage(string path)
{
return new TestPackage(Path.GetFileNameWithoutExtension(path));
}
public override IFastZipPackage LoadStagedPackage(HashingWriteStream packageStream)
{
packageStream.Close();
return new FastZipPackage
{
Id = "Sample",
Version = new SemanticVersion("1.0"),
FileLocation = packageStream.FileLocation,
Hash = packageStream.Hash
};
}
protected override Stream OpenFileWriteStream(string path)
{
return new MemoryStream();
}
protected override void MoveFileWithOverwrite(string src, string dest)
{
}
protected override System.Net.Http.HttpClient CreateHttpClient()
{
return new System.Net.Http.HttpClient(MessageHandler);
}
}
public class FakeHttpMessageHandler : HttpMessageHandler
{
private readonly Action<HttpRequestMessage, CancellationToken> onSendAsync;
public FakeHttpMessageHandler(Action<HttpRequestMessage, CancellationToken> onSendAsync)
{
this.onSendAsync = onSendAsync;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
onSendAsync(request, cancellationToken);
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("the package contents")});
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using Valle.SqlGestion;
using Valle.SqlUtilidades;
using Valle.Utilidades;
namespace Valle.ToolsTpv
{
public class TablaEnString{
public static string VistaRondasServidas(IGesSql gesL, string consIntervaloTicket, string consIDTpv, string intervaloHoras, string tarifa, string nomCarareo){
/* if( gesL.EjecutarSqlSelect("","SELECT ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES "+
" WHERE (ROUTINE_NAME = 'CalculoPrecioUnidad') AND (ROUTINE_SCHEMA = 'dbo') AND (ROUTINE_TYPE = 'FUNCTION') ").Rows.Count<=0){
gesL.EjConsultaNoSelect("","CREATE FUNCTION dbo.CalculoPrecioUnidad( "+
"@numero integer, @nombre VARCHAR(50)) "+
" RETURNS Decimal(5,2) "+
" AS BEGIN "+
" DECLARE @PrecioUnidad Decimal(5,2) "+
" DECLARE CDatos CURSOR FOR "+
" Select Top 1 TotalLinea/Cantidad "+
" From LineasTicket "+
" Where numTicket = @numero AND nomArticulo = @nombre "+
" open CDatos Fetch CDatos Into @PrecioUnidad "+
" RETURN @PrecioUnidad END ");
}*/
consIntervaloTicket = consIntervaloTicket.Length>0 ? " AND ("+consIntervaloTicket.Replace("numTicket","Ticket.NumTicket")+")":"";
intervaloHoras = intervaloHoras.Length>0 ? " AND ("+intervaloHoras.Replace("Fecha","Rondas.FechaServido + ' ' + Rondas.HoraServido")+")":"";
tarifa = tarifa.Length>0 ? " AND ("+tarifa.Replace("Tarifa","LineasRonda.Tarifa")+")":"";
consIDTpv = consIDTpv.Length>0? "("+consIDTpv.Replace("IDTpv","Ticket.IDTpv")+")":"";
nomCarareo = nomCarareo.Length>0 ? " AND ("+nomCarareo.Replace("nomCamarero","Rondas.CamareroServido")+")":"";
string consultaCompleta = "(SELECT (FechaServido+' '+HoraServido) as Fecha, TotalLinea "+
" FROM LineasRonda INNER JOIN "+
" Rondas ON Rondas.IDVinculacion = LineasRonda.IDRonda INNER JOIN "+
" Ticket ON Ticket.NumTicket = LineasRonda.numTicket "+
" WHERE @IDTpv @Tarifa @NomCamarero @Intervalo_horas @Intervalo_ticket) AS VistaRondasSl";
consultaCompleta = consultaCompleta.Replace("@Intervalo_ticket",consIntervaloTicket);
consultaCompleta = consultaCompleta.Replace("@IDTpv",consIDTpv);
consultaCompleta = consultaCompleta.Replace("@Intervalo_horas",intervaloHoras);
consultaCompleta = consultaCompleta.Replace("@Tarifa",tarifa);
consultaCompleta = consultaCompleta.Replace("@NomCamarero",nomCarareo);
return consultaCompleta;
}
}
public class DesgloseCierre{
public string[] lienasArticulos;
public decimal totalCierre =0;
public string fechaCierre ="";
public string HoraCierre = "";
public int numTicket=0;
}
public class VentaCamarero
{
public decimal totalCobrado = 0;
public decimal totalServido = 0;
public string nomCamarero = "";
public int numticketCobrados = 0;
public int numRodasServidas = 0;
public decimal VentaComision = 0;
public decimal Comision = 0;
public decimal MediaVentas
{
get { return totalCobrado / numticketCobrados; }
}
public decimal MediaServido
{
get { return totalServido / numRodasServidas;
}
}
public VentaCamarero(IGesSql gesL, string nomCam, string nomCamaSim, int IDCierre)
{
this.nomCamarero = nomCam;
DataTable tbCierre = gesL.EjecutarSqlSelect("UnCierre", "SELECT * FROM CierreDeCaja WHERE IDCierre = " + IDCierre);
object CalculoTotal = gesL.EjEscalar("SELECT SUM(LineasTicket.TotalLinea) AS TotalLinea " +
"FROM Ticket INNER JOIN LineasTicket ON Ticket.NumTicket = LineasTicket.numTicket " +
"WHERE (Ticket.NumTicket >= " + tbCierre.Rows[0]["desdeTicket"].ToString() + ")"+
" AND (Ticket.NumTicket <= " + tbCierre.Rows[0]["hastaTicket"].ToString() + ") AND (Ticket.Camarero = '" + nomCam + "') AND "+
"(Ticket.IDTpv ="+tbCierre.Rows[0]["IDTpv"].ToString()+")");
object CalculoNumTicket = gesL.EjEscalar("SELECT COUNT(*) " +
"FROM Ticket WHERE (Ticket.NumTicket >= " + tbCierre.Rows[0]["desdeTicket"].ToString() + ")"+
" AND (Ticket.NumTicket <= " + tbCierre.Rows[0]["hastaTicket"].ToString() + ")"+
" AND (Ticket.Camarero = '" + nomCam + "')"+
" AND (Ticket.IDTpv ="+tbCierre.Rows[0]["IDTpv"].ToString()+")");
if ((!CalculoTotal.GetType().Name.Equals("DBNull")) && ((decimal)CalculoTotal > 0))
{
totalCobrado = (decimal)CalculoTotal;
numticketCobrados = Convert.ToInt32(CalculoNumTicket);
}
object CalculoNumRondas = gesL.EjEscalar("SELECT COUNT(DISTINCT LineasRonda.IDRonda) AS Cuenta "+
"FROM Rondas INNER JOIN "+
"LineasRonda ON Rondas.IDVinculacion = LineasRonda.IDRonda INNER JOIN "+
"Ticket ON LineasRonda.numTicket = Ticket.NumTicket "+
" WHERE (LineasRonda.numTicket >= " + tbCierre.Rows[0]["desdeTicket"].ToString() + ")"+
" AND (LineasRonda.numTicket <= " + tbCierre.Rows[0]["hastaTicket"].ToString() + ") AND (IDTpv = "+tbCierre.Rows[0]["IDTpv"].ToString()+")"+
" AND (CamareroServido = '"+nomCam+ "')");
object CalculoTotalServido = gesL.EjEscalar("SELECT SUM(TotalLinea) AS suma FROM "+ TablaEnString.VistaRondasServidas(gesL,
"(numTicket >= " + tbCierre.Rows[0]["desdeTicket"].ToString() + ") AND (numTicket <= " + tbCierre.Rows[0]["hastaTicket"].ToString() + ")",
"(IDTpv = "+tbCierre.Rows[0]["IDTpv"].ToString()+")","","", "(nomCamarero = '"+nomCam+ "') "));
if ((!CalculoTotalServido.GetType().Name.Equals("DBNull")) && ((decimal)CalculoTotalServido > 0))
{
totalServido = (decimal)CalculoTotalServido;
numRodasServidas = Convert.ToInt32(CalculoNumRondas);
this.calculoComision(gesL,nomCam,nomCamaSim,tbCierre.Rows[0]);
}
}
void calculoComision(IGesSql gesL, string nomCam,string nomCamPila , DataRow Cierre)
{
DataRow Camarero = gesL.EjecutarSqlSelect("Camareros","SELECT * FROM Camareros WHERE Nombre ='"+nomCamPila+"'").Rows[0];
DataTable InstCom = gesL.EjecutarSqlSelect("Inst","SELECT * FROM InstComision WHERE IDCamarero ="+ Camarero["IDCamarero"].ToString());
if(InstCom.Rows.Count>0){
string HCierre = Cierre["HoraCierre"].ToString();
DataRow FechaTicketPrimero = gesL.EjecutarSqlSelect("TicketPrimero","Select * FROM Ticket WHERE NumTicket = "+
Cierre["desdeTicket"].ToString()).Rows[0];
DataRow FechaTicketUltimo = gesL.EjecutarSqlSelect("TicketPrimero","Select * FROM Ticket WHERE NumTicket = "+
Cierre["hastaTicket"].ToString()).Rows[0];
// DataTable ResComision = gesL.ExtraerTabla ("ResComision","IDVinculacion");
foreach(DataRow r in InstCom.Rows){
string consultaTarifa = !(r["Tarifa"].GetType().Name.Equals("DBNull")) ? "(Tarifa = "+r["Tarifa"].ToString() +")": "";
string HFinal = !r["HoraFin"].GetType().Name.Equals("DBNull") ? FechaTicketUltimo["FechaCobrado"].ToString()+" "+r["HoraFin"].ToString() :
FechaTicketUltimo["FechaCobrado"].ToString()+" "+HCierre;
string intervaloH = CadenasParaSql.CrearConsultaIntervaloHora("Fecha", FechaTicketPrimero["FechaCobrado"].ToString()+" "+ r["HoraInicio"].ToString(), HFinal);
object totalComision = gesL.EjEscalar("SELECT SUM(TotalLinea) AS suma FROM "+ TablaEnString.VistaRondasServidas(gesL,
"(numTicket >= " + Cierre["desdeTicket"].ToString() + ") AND (numTicket <= " + Cierre["hastaTicket"].ToString() + ")",
"(IDTpv = "+Cierre["IDTpv"].ToString()+")",intervaloH,
consultaTarifa,"(nomCamarero = '"+nomCam+ "')"));
if ((!totalComision.GetType().Name.Equals("DBNull")) && ((decimal)totalComision > 0))
{
this.VentaComision += (decimal)totalComision;
this.Comision += this.VentaComision* (decimal)r["PorcientoCom"];
}
}
}
}
}
public class VentaHoras
{
public decimal totalVenta = 0;
public string HInicio = "";
public string HFin = "";
public int numTicket = 0;
public decimal Media
{
get { return totalVenta / numTicket; }
}
public VentaHoras(IGesSql gesL, string hIni, string hFin, int IDCierre)
{
DataTable tbCierre = gesL.EjecutarSqlSelect("UnCierre", "SELECT * FROM CierreDeCaja WHERE IDCierre = " + IDCierre);
object CalculoTotal = gesL.EjEscalar("SELECT SUM(LineasTicket.TotalLinea) "+
"FROM Ticket INNER JOIN LineasTicket ON Ticket.NumTicket = LineasTicket.numTicket "+
"WHERE "+ CadenasParaSql.CrearConsultaIntervaloHora("Ticket.HoraCobrado",hIni,hFin) +
" AND (Ticket.NumTicket >= " + tbCierre.Rows[0]["desdeTicket"].ToString() + ") AND (Ticket.NumTicket <= " + tbCierre.Rows[0]["hastaTicket"].ToString() + ")"+
" AND Ticket.IDTpv = "+tbCierre.Rows[0]["IDTpv"].ToString());
object CalculoNumTicket = gesL.EjEscalar("SELECT COUNT(*) " +
"FROM Ticket WHERE " + CadenasParaSql.CrearConsultaIntervaloHora("Ticket.HoraCobrado", hIni, hFin) +
" AND (Ticket.NumTicket >= " + tbCierre.Rows[0]["desdeTicket"].ToString() + ") AND (Ticket.NumTicket <= " + tbCierre.Rows[0]["hastaTicket"].ToString() + ")"+
" AND Ticket.IDTpv = "+tbCierre.Rows[0]["IDTpv"].ToString());
HInicio = hIni;
HFin = hFin;
if ((!CalculoTotal.GetType().Name.Equals("DBNull")) && ((decimal)CalculoTotal > 0))
{
totalVenta = (decimal)CalculoTotal;
numTicket = Convert.ToInt32(CalculoNumTicket);
}
}
}
public class GesVentas
{
public DesgloseCierre CalcularCierre(IGesSql ges, int idTpv, int ticketCom, int ticketFin)
{
DesgloseCierre desglose = new DesgloseCierre();
DataTable tbSumaCierre ;
DataTable tbResumen;
DataTable tbNumTicket;
int numComienzo = ticketCom;
tbSumaCierre = ges.EjecutarSqlSelect("SumaCierre","SELECT SUM(TotalLinea) AS total FROM "+
"(SELECT LineasTicket.numTicket, LineasTicket.TotalLinea FROM "+
"LineasTicket INNER JOIN Ticket ON LineasTicket.numTicket = Ticket.NumTicket "+
"WHERE (Ticket.IDTpv = "+ idTpv+ ")) AS LineasTpv WHERE numTicket >= "+numComienzo
+" AND numTicket <= "+ ticketFin);
tbNumTicket = ges.EjecutarSqlSelect("NumTicket", ("SELECT MIN(numTicket) AS minimo, MAX(numTicket) AS maximo FROM " +
"(SELECT LineasTicket.numTicket FROM " +
"LineasTicket INNER JOIN Ticket ON LineasTicket.numTicket = Ticket.NumTicket " +
"WHERE (Ticket.IDTpv = " + idTpv + ")) AS LineasTpv WHERE numTicket >= "+numComienzo
+" AND numTicket <= "+ ticketFin));
tbResumen = ges.EjecutarSqlSelect("TbResumen","SELECT nomArticulo, SUM(Cantidad) AS Cantidad " +
"FROM (SELECT LineasTicket.numTicket, LineasTicket.nomArticulo, LineasTicket.Cantidad FROM "+
"LineasTicket INNER JOIN Ticket ON LineasTicket.numTicket = Ticket.NumTicket "+
"WHERE (Ticket.IDTpv = "+ idTpv+ ")) AS LineasTpv WHERE (numTicket >= "+numComienzo
+" AND numTicket <= "+ ticketFin+") " +
"GROUP BY nomArticulo");
if (tbResumen.Rows.Count > 0)
{
int logArray = tbResumen.Rows.Count;
desglose.lienasArticulos = new String[logArray];
desglose.totalCierre = (decimal)tbSumaCierre.Rows[0][0];
desglose.numTicket = (int)tbNumTicket.Rows[0]["maximo"] - (int)tbNumTicket.Rows[0]["minimo"]+1;
int punt = 0;
foreach (DataRow dr in tbResumen.Rows)
{
String cantidad = String.Format("{0:#0.###}", dr["Cantidad"]);
if(cantidad.Contains(",")){
string[] cantidades = cantidad.Split(',');
cantidad = cantidades[0].PadLeft(4)+','+cantidades[1];
}else{
cantidad = cantidad.PadLeft(4);
}
desglose.lienasArticulos[punt] = dr["nomArticulo"].ToString().PadRight(22) + cantidad;
punt++;
}
return desglose;
}
return null;
}
public List<string> CalcularVentaHoras(IGesSql ges, int IDCierre){
string[] Intervalos = new string[] { "07:00-09:00", "09:01-11:00", "11:01-13:00", "13:01-15:00", "15:01-17:00","17:01-19:00",
"19:01-21:00","21:01-23:00","23:01-00:00",
"00:01-02:00","02:01-03:00","03:01-05:00",
"05:01-06:59"};
List<string> Listado = new List<string>();
VentaHoras infVentaHoras;
Listado.Add("Estadistica de ventas por hora");
Listado.Add("");
foreach (string intervalo in Intervalos)
{
string[] sepInt = intervalo.Split('-');
infVentaHoras = new VentaHoras(ges, sepInt[0], sepInt[1], IDCierre);
if(infVentaHoras.totalVenta>0){
Listado.Add("En el intervalo de "+ intervalo);
Listado.Add(String.Format("Total vendido = {0:c}",infVentaHoras.totalVenta));
Listado.Add("Num de ticket "+ infVentaHoras.numTicket);
Listado.Add(String.Format("Media por ticket = {0:c}",infVentaHoras.Media));
Listado.Add("");
}
}
return Listado;
}
public List<string> CalcularVentaCamareros(IGesSql ges, int IDCierre, IBarrProgres miBarra)
{
List<string> Listado = new List<string>();
Listado.Add("Estadistica de camareros");
Listado.Add("");
VentaCamarero infVentaCamarero;
DataTable tbCamareros = ges.ExtraerTabla("Camareros",null);
miBarra.MaxProgreso = tbCamareros.Rows.Count;
foreach (DataRow rC in tbCamareros.Rows)
{
miBarra.Progreso ++;
infVentaCamarero = new VentaCamarero(ges,rC["Nombre"].ToString()+" "+rC["Apellidos"].ToString(),rC["Nombre"].ToString(), IDCierre);
if(infVentaCamarero.totalCobrado + infVentaCamarero.totalServido + infVentaCamarero.VentaComision >0)
Listado.Add("Camarero = "+rC["Nombre"].ToString()+" "+rC["Apellidos"].ToString());
if(infVentaCamarero.totalCobrado>0){
Listado.Add(String.Format("Total cobrado = {0:c}", infVentaCamarero.totalCobrado));
Listado.Add("Num ticket cobrados = "+ infVentaCamarero.numticketCobrados);
Listado.Add(String.Format("Media de ticket cobrados = {0:c}",infVentaCamarero.MediaVentas));
Listado.Add("");
}
if(infVentaCamarero.totalServido>0){
Listado.Add(String.Format("Total servido = {0:c}",infVentaCamarero.totalServido));
Listado.Add("Num rondas servidas = "+ infVentaCamarero.numRodasServidas);
Listado.Add(String.Format("Media servido = {0:c}", infVentaCamarero.MediaServido));
Listado.Add("");
}
if(infVentaCamarero.VentaComision>0){
Listado.Add(String.Format("Total venta comision = {0:c}", infVentaCamarero.VentaComision));
Listado.Add(String.Format("Comision dia = {0:c}",infVentaCamarero.Comision));
Listado.Add("");
}
}
return Listado;
}
public string[] CalcularCierre(IGesSql ges, int idTpv)
{
DataTable tbCierreCaja = ges.ExtraerTabla("CierreDeCaja", "IDCierre");
DataTable tbSumaCierre ;
DataTable tbResumen;
DataTable tbNumTicket;
DataView dwCierre = new DataView(tbCierreCaja, "IDTpv =" + idTpv, "hastaTicket", DataViewRowState.CurrentRows);
int numComienzo = dwCierre.Count > 0 ?
(int)dwCierre[dwCierre.Count - 1]["hastaTicket"] : 0;
tbSumaCierre = ges.EjecutarSqlSelect("SumaCierre","SELECT SUM(TotalLinea) AS total FROM "+
"(SELECT LineasTicket.numTicket, LineasTicket.TotalLinea FROM "+
"LineasTicket INNER JOIN Ticket ON LineasTicket.numTicket = Ticket.NumTicket "+
"WHERE (Ticket.IDTpv = "+ idTpv+ ")) AS LineasTpv WHERE numTicket > "+numComienzo);
tbNumTicket = ges.EjecutarSqlSelect("NumTicket", ("SELECT MIN(numTicket) AS minimo, MAX(numTicket) AS maximo FROM " +
"(SELECT LineasTicket.numTicket FROM " +
"LineasTicket INNER JOIN Ticket ON LineasTicket.numTicket = Ticket.NumTicket " +
"WHERE (Ticket.IDTpv = " + idTpv + ")) AS LineasTpv WHERE numTicket > " + numComienzo));
tbResumen = ges.EjecutarSqlSelect("TbResumen","SELECT nomArticulo, SUM(Cantidad) AS Cantidad " +
"FROM (SELECT LineasTicket.numTicket, LineasTicket.nomArticulo, LineasTicket.Cantidad FROM "+
"LineasTicket INNER JOIN Ticket ON LineasTicket.numTicket = Ticket.NumTicket "+
"WHERE (Ticket.IDTpv = "+ idTpv+ ")) AS LineasTpv WHERE (numTicket > "+numComienzo+") " +
"GROUP BY nomArticulo");
if (tbResumen.Rows.Count > 0)
{
int logArray = 4 + tbResumen.Rows.Count;
String[] linea = new String[logArray];
decimal totalDia = (decimal)tbSumaCierre.Rows[0][0];
linea[0] = String.Format("Total del dia: {0:#0.00}", totalDia);
int numTicket = (int)tbNumTicket.Rows[0]["maximo"] - (int)tbNumTicket.Rows[0]["minimo"]+1;
linea[1] = String.Format("Numero de ticket: {0}", numTicket);
linea[2] = String.Format("Media por ticket: {0:#0.00}", totalDia / numTicket);
linea[3] = "";
int punt = 4;
foreach (DataRow dr in tbResumen.Rows)
{
String cantidad = String.Format("{0:#0.###}", dr["Cantidad"]);
if(cantidad.Contains(",")){
string[] cantidades = cantidad.Split(',');
cantidad = cantidades[0].PadLeft(4)+','+cantidades[1];
}else{
cantidad = cantidad.PadLeft(4);
}
linea[punt] = dr["nomArticulo"].ToString().PadRight(30) + cantidad;
punt++;
}
DataRow drCierre = tbCierreCaja.NewRow();
drCierre["desdeTicket"] = (int)tbNumTicket.Rows[0]["minimo"];
drCierre["hastaTicket"] = (int)tbNumTicket.Rows[0]["maximo"];
drCierre["fechaCierre"] = Utilidades.CadenasTexto.RotarFecha(DateTime.Now.ToShortDateString());
drCierre["HoraCierre"] = DateTime.Now.ToShortTimeString().PadLeft(5,'0');
drCierre["IDTpv"] = idTpv;
tbCierreCaja.Rows.Add(drCierre);
ges.EjConsultaNoSelect("CierreDeCaja",Valle.SqlUtilidades.UtilidadesReg.ExConsultaNoSelet(drCierre,AccionesConReg.Agregar,
"").Replace(@"\",@"\\"));
return linea;
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using XCLCMS.WebAPI.Areas.HelpPage.ModelDescriptions;
using XCLCMS.WebAPI.Areas.HelpPage.Models;
namespace XCLCMS.WebAPI.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
// TODO: !! Make types internal?
namespace SFML
{
namespace Graphics
{
////////////////////////////////////////////////////////////
/// <summary>
/// IntRect is an utility class for manipulating 2D rectangles
/// with integer coordinates
/// </summary>
////////////////////////////////////////////////////////////
[StructLayout(LayoutKind.Sequential)]
public struct IntRect
{
////////////////////////////////////////////////////////////
/// <summary>
/// Construct the rectangle from its coordinates
/// </summary>
/// <param name="left">Left coordinate of the rectangle</param>
/// <param name="top">Top coordinate of the rectangle</param>
/// <param name="width">Width of the rectangle</param>
/// <param name="height">Height of the rectangle</param>
////////////////////////////////////////////////////////////
public IntRect(int left, int top, int width, int height)
{
Left = left;
Top = top;
Width = width;
Height = height;
}
////////////////////////////////////////////////////////////
/// <summary>
/// Check if a point is inside the rectangle's area
/// </summary>
/// <param name="x">X coordinate of the point to test</param>
/// <param name="y">Y coordinate of the point to test</param>
/// <returns>True if the point is inside</returns>
////////////////////////////////////////////////////////////
public bool Contains(int x, int y)
{
return (x >= Left) && (x < Left + Width) && (y >= Top) && (y < Top + Height);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Check intersection between two rectangles
/// </summary>
/// <param name="rect"> Rectangle to test</param>
/// <returns>True if rectangles overlap</returns>
////////////////////////////////////////////////////////////
public bool Intersects(IntRect rect)
{
// Compute the intersection boundaries
int left = Math.Max(Left, rect.Left);
int top = Math.Max(Top, rect.Top);
int right = Math.Min(Left + Width, rect.Left + rect.Width);
int bottom = Math.Min(Top + Height, rect.Top + rect.Height);
return (left < right) && (top < bottom);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Check intersection between two rectangles
/// </summary>
/// <param name="rect"> Rectangle to test</param>
/// <param name="overlap">Rectangle to be filled with overlapping rect</param>
/// <returns>True if rectangles overlap</returns>
////////////////////////////////////////////////////////////
public bool Intersects(IntRect rect, out IntRect overlap)
{
// Compute the intersection boundaries
int left = Math.Max(Left, rect.Left);
int top = Math.Max(Top, rect.Top);
int right = Math.Min(Left + Width, rect.Left + rect.Width);
int bottom = Math.Min(Top + Height, rect.Top + rect.Height);
// If the intersection is valid (positive non zero area), then there is an intersection
if ((left < right) && (top < bottom))
{
overlap.Left = left;
overlap.Top = top;
overlap.Width = right - left;
overlap.Height = bottom - top;
return true;
}
else
{
overlap.Left = 0;
overlap.Top = 0;
overlap.Width = 0;
overlap.Height = 0;
return false;
}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Provide a string describing the object
/// </summary>
/// <returns>String description of the object</returns>
////////////////////////////////////////////////////////////
public override string ToString()
{
return "[IntRect]" +
" Left(" + Left + ")" +
" Top(" + Top + ")" +
" Width(" + Width + ")" +
" Height(" + Height + ")";
}
/// <summary>Left coordinate of the rectangle</summary>
public int Left;
/// <summary>Top coordinate of the rectangle</summary>
public int Top;
/// <summary>Width of the rectangle</summary>
public int Width;
/// <summary>Height of the rectangle</summary>
public int Height;
}
////////////////////////////////////////////////////////////
/// <summary>
/// IntRect is an utility class for manipulating 2D rectangles
/// with float coordinates
/// </summary>
////////////////////////////////////////////////////////////
[StructLayout(LayoutKind.Sequential)]
public struct FloatRect
{
////////////////////////////////////////////////////////////
/// <summary>
/// Construct the rectangle from its coordinates
/// </summary>
/// <param name="left">Left coordinate of the rectangle</param>
/// <param name="top">Top coordinate of the rectangle</param>
/// <param name="width">Width of the rectangle</param>
/// <param name="height">Height of the rectangle</param>
////////////////////////////////////////////////////////////
public FloatRect(float left, float top, float width, float height)
{
Left = left;
Top = top;
Width = width;
Height = height;
}
////////////////////////////////////////////////////////////
/// <summary>
/// Check if a point is inside the rectangle's area
/// </summary>
/// <param name="x">X coordinate of the point to test</param>
/// <param name="y">Y coordinate of the point to test</param>
/// <returns>True if the point is inside</returns>
////////////////////////////////////////////////////////////
public bool Contains(float x, float y)
{
return (x >= Left) && (x < Left + Width) && (y >= Top) && (y < Top + Height);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Check intersection between two rectangles
/// </summary>
/// <param name="rect"> Rectangle to test</param>
/// <returns>True if rectangles overlap</returns>
////////////////////////////////////////////////////////////
public bool Intersects(FloatRect rect)
{
// Compute the intersection boundaries
float left = Math.Max(Left, rect.Left);
float top = Math.Max(Top, rect.Top);
float right = Math.Min(Left + Width, rect.Left + rect.Width);
float bottom = Math.Min(Top + Height, rect.Top + rect.Height);
return (left < right) && (top < bottom);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Check intersection between two rectangles
/// </summary>
/// <param name="rect"> Rectangle to test</param>
/// <param name="overlap">Rectangle to be filled with overlapping rect</param>
/// <returns>True if rectangles overlap</returns>
////////////////////////////////////////////////////////////
public bool Intersects(FloatRect rect, out FloatRect overlap)
{
// Compute the intersection boundaries
float left = Math.Max(Left, rect.Left);
float top = Math.Max(Top, rect.Top);
float right = Math.Min(Left + Width, rect.Left + rect.Width);
float bottom = Math.Min(Top + Height, rect.Top + rect.Height);
// If the intersection is valid (positive non zero area), then there is an intersection
if ((left < right) && (top < bottom))
{
overlap.Left = left;
overlap.Top = top;
overlap.Width = right - left;
overlap.Height = bottom - top;
return true;
}
else
{
overlap.Left = 0;
overlap.Top = 0;
overlap.Width = 0;
overlap.Height = 0;
return false;
}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Provide a string describing the object
/// </summary>
/// <returns>String description of the object</returns>
////////////////////////////////////////////////////////////
public override string ToString()
{
return "[FloatRect]" +
" Left(" + Left + ")" +
" Top(" + Top + ")" +
" Width(" + Width + ")" +
" Height(" + Height + ")";
}
/// <summary>Left coordinate of the rectangle</summary>
public float Left;
/// <summary>Top coordinate of the rectangle</summary>
public float Top;
/// <summary>Width of the rectangle</summary>
public float Width;
/// <summary>Height of the rectangle</summary>
public float Height;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipelines;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.Extensions.Logging;
using Orleans.Connections.Security.Internal;
namespace Orleans.Connections.Security
{
internal class TlsServerConnectionMiddleware
{
private readonly ConnectionDelegate _next;
private readonly TlsOptions _options;
private readonly ILogger _logger;
private readonly X509Certificate2 _certificate;
private readonly Func<ConnectionContext, string, X509Certificate2> _certificateSelector;
public TlsServerConnectionMiddleware(ConnectionDelegate next, TlsOptions options, ILoggerFactory loggerFactory)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
_next = next;
// capture the certificate now so it can't be switched after validation
_certificate = options.LocalCertificate;
_certificateSelector = options.LocalServerCertificateSelector;
if (_certificate == null && _certificateSelector == null)
{
throw new ArgumentException("Server certificate is required", nameof(options));
}
// If a selector is provided then ignore the cert, it may be a default cert.
if (_certificateSelector != null)
{
// SslStream doesn't allow both.
_certificate = null;
}
else
{
EnsureCertificateIsAllowedForServerAuth(_certificate);
}
_options = options;
_logger = loggerFactory?.CreateLogger<TlsServerConnectionMiddleware>();
}
public Task OnConnectionAsync(ConnectionContext context)
{
return Task.Run(() => InnerOnConnectionAsync(context));
}
private async Task InnerOnConnectionAsync(ConnectionContext context)
{
bool certificateRequired;
var feature = new TlsConnectionFeature();
context.Features.Set<ITlsConnectionFeature>(feature);
context.Features.Set<ITlsHandshakeFeature>(feature);
var memoryPool = context.Features.Get<IMemoryPoolFeature>()?.MemoryPool;
var inputPipeOptions = new StreamPipeReaderOptions
(
pool: memoryPool,
bufferSize: memoryPool.GetMinimumSegmentSize(),
minimumReadSize: memoryPool.GetMinimumAllocSize(),
leaveOpen: true
);
var outputPipeOptions = new StreamPipeWriterOptions
(
pool: memoryPool,
leaveOpen: true
);
TlsDuplexPipe tlsDuplexPipe = null;
if (_options.RemoteCertificateMode == RemoteCertificateMode.NoCertificate)
{
tlsDuplexPipe = new TlsDuplexPipe(context.Transport, inputPipeOptions, outputPipeOptions);
certificateRequired = false;
}
else
{
tlsDuplexPipe = new TlsDuplexPipe(context.Transport, inputPipeOptions, outputPipeOptions, s => new SslStream(
s,
leaveInnerStreamOpen: false,
userCertificateValidationCallback: (sender, certificate, chain, sslPolicyErrors) =>
{
if (certificate == null)
{
return _options.RemoteCertificateMode != RemoteCertificateMode.RequireCertificate;
}
if (_options.RemoteCertificateValidation == null)
{
if (sslPolicyErrors != SslPolicyErrors.None)
{
return false;
}
}
var certificate2 = ConvertToX509Certificate2(certificate);
if (certificate2 == null)
{
return false;
}
if (_options.RemoteCertificateValidation != null)
{
if (!_options.RemoteCertificateValidation(certificate2, chain, sslPolicyErrors))
{
return false;
}
}
return true;
}));
certificateRequired = true;
}
var sslStream = tlsDuplexPipe.Stream;
using (var cancellationTokeSource = new CancellationTokenSource(_options.HandshakeTimeout))
using (cancellationTokeSource.Token.UnsafeRegisterCancellation(state => ((ConnectionContext)state).Abort(), context))
{
try
{
// Adapt to the SslStream signature
ServerCertificateSelectionCallback selector = null;
if (_certificateSelector != null)
{
selector = (sender, name) =>
{
context.Features.Set(sslStream);
var cert = _certificateSelector(context, name);
if (cert != null)
{
EnsureCertificateIsAllowedForServerAuth(cert);
}
return cert;
};
}
var sslOptions = new TlsServerAuthenticationOptions
{
ServerCertificate = _certificate,
ServerCertificateSelectionCallback = selector,
ClientCertificateRequired = certificateRequired,
EnabledSslProtocols = _options.SslProtocols,
CertificateRevocationCheckMode = _options.CheckCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
};
_options.OnAuthenticateAsServer?.Invoke(context, sslOptions);
#if NETCOREAPP
await sslStream.AuthenticateAsServerAsync(sslOptions.Value, cancellationTokeSource.Token);
#else
await sslStream.AuthenticateAsServerAsync(
sslOptions.ServerCertificate,
sslOptions.ClientCertificateRequired,
sslOptions.EnabledSslProtocols,
sslOptions.CertificateRevocationCheckMode == X509RevocationMode.Online);
#endif
}
catch (OperationCanceledException ex)
{
_logger?.LogWarning(2, ex, "Authentication timed out");
#if NETCOREAPP
await sslStream.DisposeAsync();
#else
sslStream.Dispose();
#endif
return;
}
catch (Exception ex)
{
_logger?.LogWarning(1, ex, "Authentication failed");
#if NETCOREAPP
await sslStream.DisposeAsync();
#else
sslStream.Dispose();
#endif
return;
}
}
#if NETCOREAPP
feature.ApplicationProtocol = sslStream.NegotiatedApplicationProtocol.Protocol;
#endif
context.Features.Set<ITlsApplicationProtocolFeature>(feature);
feature.LocalCertificate = ConvertToX509Certificate2(sslStream.LocalCertificate);
feature.RemoteCertificate = ConvertToX509Certificate2(sslStream.RemoteCertificate);
feature.CipherAlgorithm = sslStream.CipherAlgorithm;
feature.CipherStrength = sslStream.CipherStrength;
feature.HashAlgorithm = sslStream.HashAlgorithm;
feature.HashStrength = sslStream.HashStrength;
feature.KeyExchangeAlgorithm = sslStream.KeyExchangeAlgorithm;
feature.KeyExchangeStrength = sslStream.KeyExchangeStrength;
feature.Protocol = sslStream.SslProtocol;
var originalTransport = context.Transport;
try
{
context.Transport = tlsDuplexPipe;
// Disposing the stream will dispose the TlsDuplexPipe
#if NETCOREAPP
await using (sslStream)
await using (tlsDuplexPipe)
#else
using (sslStream)
using (tlsDuplexPipe)
#endif
{
await _next(context);
// Dispose the inner stream (TlsDuplexPipe) before disposing the SslStream
// as the duplex pipe can hit an ODE as it still may be writing.
}
}
finally
{
// Restore the original so that it gets closed appropriately
context.Transport = originalTransport;
}
}
protected static void EnsureCertificateIsAllowedForServerAuth(X509Certificate2 certificate)
{
if (!CertificateLoader.IsCertificateAllowedForServerAuth(certificate))
{
throw new InvalidOperationException($"Invalid server certificate for server authentication: {certificate.Thumbprint}");
}
}
private static X509Certificate2 ConvertToX509Certificate2(X509Certificate certificate)
{
if (certificate is null)
{
return null;
}
return certificate as X509Certificate2 ?? new X509Certificate2(certificate);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Net.Primitives.Functional.Tests
{
public class IPAddressParsing
{
#region IPv4
[Theory]
[InlineData("192.168.0.1", "192.168.0.1")]
[InlineData("0.0.0.0", "0.0.0.0")]
[InlineData("0", "0.0.0.0")]
[InlineData("255.255.255.255", "255.255.255.255")]
[InlineData("4294967294", "255.255.255.254")]
[InlineData("4294967295", "255.255.255.255")]
[InlineData("157.3873051", "157.59.25.27")]
[InlineData("157.6427", "157.0.25.27")]
[InlineData("2637895963", "157.59.25.27")]
public void ParseIPv4_Decimal_Success(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[InlineData("0xFF.0xFF.0xFF.0xFF", "255.255.255.255")]
[InlineData("0x0", "0.0.0.0")]
[InlineData("0xFFFFFFFE", "255.255.255.254")]
[InlineData("0xFFFFFFFF", "255.255.255.255")]
[InlineData("0x9D3B191B", "157.59.25.27")]
[InlineData("0X9D.0x3B.0X19.0x1B", "157.59.25.27")]
[InlineData("0x89.0xab.0xcd.0xef", "137.171.205.239")]
public void ParseIPv4_Hex_Success(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[InlineData("0377.0377.0377.0377", "255.255.255.255")]
[InlineData("037777777776", "255.255.255.254")]
[InlineData("037777777777", "255.255.255.255")]
[InlineData("023516614433", "157.59.25.27")]
[InlineData("00000023516614433", "157.59.25.27")]
[InlineData("000235.000073.0000031.00000033", "157.59.25.27")]
[InlineData("0235.073.031.033", "157.59.25.27")]
[InlineData("157.59.25.033", "157.59.25.27")] // Partial octal
public void ParseIPv4_Octal_Success(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[InlineData("157.59.25.0x1B", "157.59.25.27")]
[InlineData("157.59.0x001B", "157.59.0.27")]
[InlineData("157.0x00001B", "157.0.0.27")]
[InlineData("157.59.0x25.033", "157.59.37.27")]
public void ParseIPv4_MixedBase_Success(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Fact]
public void ParseIPv4_WithSubnet_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("192.168.0.0/16"); });
}
[Fact]
public void ParseIPv4_WithPort_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("192.168.0.1:80"); });
}
[Fact]
public void ParseIPv4_Empty_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(""); });
}
[Theory]
[InlineData(" ")]
[InlineData(" 127.0.0.1")]
public void ParseIPv4_Whitespace_Failure(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
[Theory]
[InlineData("157.3B191B")] // Hex without 0x
[InlineData("1.1.1.0x")] // Empty trailing hex segment
[InlineData("0000X9D.0x3B.0X19.0x1B")] // Leading zeros on hex
public void ParseIPv4_InvalidHex_Failure(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
[Theory]
[PlatformSpecific(~TestPlatforms.OSX)] // There doesn't appear to be an OSX API that will fail for these
[InlineData("0x.1.1.1")] // Empty leading hex segment
public void ParseIPv4_InvalidHex_Failure_NonOSX(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
[Theory]
[InlineData("0.0.0.089")] // Octal (leading zero) but with 8 or 9
public void ParseIPv4_InvalidOctal_Failure(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
[Theory]
[InlineData("260.156")] // Left dotted segments can't be more than 255
[InlineData("255.260.156")] // Left dotted segments can't be more than 255
[InlineData("0xFF.0xFFFFFF.0xFF")] // Middle segment too large
[InlineData("0xFFFFFF.0xFF.0xFFFFFF")] // Leading segment too large
public void ParseIPv4_InvalidValue_Failure(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
[Theory]
[PlatformSpecific(~TestPlatforms.OSX)] // There does't appear to be an OSX API that will fail for these
[InlineData("4294967296")] // Decimal overflow by 1
[InlineData("040000000000")] // Octal overflow by 1
[InlineData("01011101001110110001100100011011")] // Binary? Read as octal, overflows
[InlineData("10011101001110110001100100011011")] // Binary? Read as decimal, overflows
[InlineData("0x100000000")] // Hex overflow by 1
public void ParseIPv4_InvalidValue_Failure_NonOSX(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
[Theory]
[InlineData("1.1\u67081.1.1")] // Unicode, Crashes .NET 4.0 IPAddress.TryParse
public void ParseIPv4_InvalidChar_Failure(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
[Theory]
[InlineData("...")] // Empty sections
[InlineData("1.1.1.")] // Empty trailing section
[InlineData("1..1.1")] // Empty internal section
[InlineData(".1.1.1")] // Empty leading section
[InlineData("..11.1")] // Empty sections
public void ParseIPv4_EmptySection_Failure(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
#endregion
#region IPv6
[Theory]
[InlineData("Fe08::1", "fe08::1")]
[InlineData("0000:0000:0000:0000:0000:0000:0000:0000", "::")]
[InlineData("FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")]
[InlineData("0:0:0:0:0:0:0:0", "::")]
[InlineData("1:0:0:0:0:0:0:0", "1::")]
[InlineData("0:1:0:0:0:0:0:0", "0:1::")]
[InlineData("0:0:1:0:0:0:0:0", "0:0:1::")]
[InlineData("0:0:0:1:0:0:0:0", "0:0:0:1::")]
[InlineData("0:0:0:0:1:0:0:0", "::1:0:0:0")]
[InlineData("0:0:0:0:0:1:0:0", "::1:0:0")]
[InlineData("0:0:0:0:0:0:1:0", "::0.1.0.0")]
[InlineData("0:0:0:0:0:0:0:1", "::1")]
[InlineData("1:0:0:0:0:0:0:1", "1::1")]
[InlineData("1:1:0:0:0:0:0:1", "1:1::1")]
[InlineData("1:0:1:0:0:0:0:1", "1:0:1::1")]
[InlineData("1:0:0:1:0:0:0:1", "1:0:0:1::1")]
[InlineData("1:0:0:0:1:0:0:1", "1::1:0:0:1")]
[InlineData("1:0:0:0:0:1:0:1", "1::1:0:1")]
[InlineData("1:0:0:0:0:0:1:1", "1::1:1")]
[InlineData("1:1:0:0:1:0:0:1", "1:1::1:0:0:1")]
[InlineData("1:0:1:0:0:1:0:1", "1:0:1::1:0:1")]
[InlineData("1:0:0:1:0:0:1:1", "1::1:0:0:1:1")]
[InlineData("1:1:0:0:0:1:0:1", "1:1::1:0:1")]
[InlineData("1:0:0:0:1:0:1:1", "1::1:0:1:1")]
[InlineData("::", "::")]
public void ParseIPv6_NoBrackets_Success(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Fact]
public void ParseIPv6_Brackets_SuccessBracketsDropped()
{
Assert.Equal("fe08::1", IPAddress.Parse("[Fe08::1]").ToString());
}
[Fact]
public void ParseIPv6_LeadingBracket_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("[Fe08::1"); });
}
[Fact]
public void ParseIPv6_TrailingBracket_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("Fe08::1]"); });
}
[Fact]
public void ParseIPv6_BracketsAndPort_SuccessBracketsAndPortDropped()
{
Assert.Equal("fe08::1", IPAddress.Parse("[Fe08::1]:80").ToString());
}
[Fact]
public void ParseIPv6_BracketsAndInvalidPort_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("[Fe08::1]:80Z"); });
}
[Fact]
public void ParseIPv6_BracketsAndHexPort_SuccessBracketsAndPortDropped()
{
Assert.Equal("fe08::1", IPAddress.Parse("[Fe08::1]:0xFA").ToString());
}
[Fact]
public void ParseIPv6_WithSubnet_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("Fe08::/64"); });
}
[Theory]
[InlineData("Fe08::1%13542", "fe08::1%13542")]
[InlineData("1::%1", "1::%1")]
[InlineData("::1%12", "::1%12")]
[InlineData("::%123", "::%123")]
public void ParseIPv6_ScopeID_Success(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[InlineData("FE08::192.168.0.1", "fe08::c0a8:1")] // Output is not IPv4 mapped
[InlineData("::192.168.0.1", "::192.168.0.1")]
[InlineData("::FFFF:192.168.0.1", "::ffff:192.168.0.1")] // SIIT
public void ParseIPv6_v4_Success(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[PlatformSpecific(~TestPlatforms.AnyUnix)] // Linux/OSX don't do the IPv6->IPv4 formatting for these addresses
[InlineData("::FFFF:0:192.168.0.1", "::ffff:0:192.168.0.1")] // SIIT
[InlineData("::5EFE:192.168.0.1", "::5efe:192.168.0.1")] // ISATAP
[InlineData("1::5EFE:192.168.0.1", "1::5efe:192.168.0.1")] // ISATAP
public void ParseIPv6_v4_Success_NonUnix(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Linux/OSX don't do the IPv6->IPv4 formatting for these addresses
[InlineData("::FFFF:0:192.168.0.1", "::ffff:0:c0a8:1")] // SIIT
[InlineData("::5EFE:192.168.0.1", "::5efe:c0a8:1")] // ISATAP
[InlineData("1::5EFE:192.168.0.1", "1::5efe:c0a8:1")] // ISATAP
public void ParseIPv6_v4_Success_Unix(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[PlatformSpecific(~TestPlatforms.Linux)] // Linux does not appear to recognize this as a valid address
[InlineData("::192.168.0.010", "::192.168.0.10")] // Embedded IPv4 octal, read as decimal
public void ParseIPv6_v4_Success_NonLinux(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Fact]
public void ParseIPv6_Incomplete_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("[1]"); });
}
[Fact]
public void ParseIPv6_LeadingSingleColon_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(":1"); });
}
[Fact]
public void ParseIPv6_TrailingSingleColon_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("1:"); });
}
[Fact]
public void ParseIPv6_LeadingWhitespace_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(" ::1"); });
}
[Fact]
public void ParseIPv6_TrailingWhitespace_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("::1 "); });
}
[Fact]
public void ParseIPv6_Ambiguous_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("1::1::1"); });
}
[Fact]
public void ParseIPv6_InvalidChar_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("1:1\u67081:1:1"); });
}
[Fact]
public void ParseIPv6_v4_OutOfRange_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("FE08::260.168.0.1"); });
}
[Fact]
public void ParseIPv6_v4_Hex_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("::192.168.0.0x0"); });
}
[Fact]
public void ParseIPv6_Rawv4_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("[192.168.0.1]"); });
}
[Fact]
public void ParseIPv6_InvalidHex_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("G::"); });
}
[Fact]
public void ParseIPv6_InvalidValue_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("FFFFF::"); });
}
[Fact]
public void ParseIPv6_ColonScope_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(":%12"); });
}
[Fact]
public void ParseIPv6_JustScope_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("%12"); });
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // There does't appear to be an OSX API that will fail for this
public void ParseIPv6_AlphaNumericScope_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("::%1a"); });
}
#endregion
[Fact]
public void Parse_Null_Throws()
{
Assert.Throws<ArgumentNullException>(() => { IPAddress.Parse(null); });
}
[Fact]
public void TryParse_Null_False()
{
IPAddress ipAddress;
Assert.False(IPAddress.TryParse(null, out ipAddress));
}
[Fact]
public void Parse_Empty_Throws()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(String.Empty); });
}
[Fact]
public void TryParse_Empty_False()
{
IPAddress ipAddress;
Assert.False(IPAddress.TryParse(String.Empty, out ipAddress));
}
}
}
| |
// 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 MonoTouch;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using System.Drawing;
using MonoTouch.ObjCRuntime;
namespace ClanceysLib
{
public class UIComboBox : UITextField
{
PickerView pickerView;
TapableView closeView;
UIButton closeBtn;
public UIView ViewForPicker;
public event EventHandler ValueChanged;
public event EventHandler PickerClosed;
public event EventHandler PickerShown;
public event EventHandler PickerFadeInDidFinish;
public UIComboBox(RectangleF rect) : base (rect)
{
this.BorderStyle = UITextBorderStyle.RoundedRect;
pickerView = new PickerView();
this.TouchDown += delegate {
ShowPicker();
};
this.ShouldChangeCharacters += delegate {
return false;
};
pickerView.IndexChanged += delegate {
var oldValue = this.Text;
this.Text = pickerView.StringValue;
if(ValueChanged!= null && oldValue != Text)
ValueChanged(this,null);
};
closeBtn = new UIButton(new RectangleF(0,0,31,32));
closeBtn.SetImage(UIImage.FromFile("Images/closebox.png"),UIControlState.Normal);
closeBtn.TouchDown += delegate {
HidePicker();
};
pickerView.AddSubview(closeBtn);
}
public override bool CanBecomeFirstResponder {
get {
return false;
}
}
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
var parentView = ViewForPicker?? this.Superview;
var parentH = parentView.Frame.Height;
pickerView.Frame = new RectangleF(0,parentH - pickerView.Frame.Height,parentView.Frame.Size.Width,pickerView.Frame.Height);
closeBtn.Frame = closeBtn.Frame.SetLocation(new PointF(pickerView.Bounds.Width - 32,pickerView.Bounds.Y));
pickerView.BringSubviewToFront(closeBtn);
}
/// <summary>
/// Can be a collection of anyting. If you don't set the ValueMember or DisplayMember, it will use ToString() for the value and Title.
/// </summary>
public object [] Items {
get{return pickerView.Items;}
set{pickerView.Items = value;}
}
public string DisplayMember {
get{return pickerView.DisplayMember;}
set {pickerView.DisplayMember = value;}
}
public string ValueMember {
get{return pickerView.ValueMember;}
set {pickerView.ValueMember = value;}
}
public float Width {
get{return pickerView.Width;}
set {pickerView.Width = value;}
}
bool pickerVisible;
public void ShowPicker()
{
if(PickerShown != null)
PickerShown(this,null);
LayoutSubviews ();
pickerView.BringSubviewToFront(closeBtn);
pickerVisible = true;
var parentView = ViewForPicker ?? this.Superview;
var parentFrame = parentView.Frame;
//closeView = new TapableView(parentView.Bounds);
//closeView.Tapped += delegate{
// HidePicker();
//};
pickerView.Frame = pickerView.Frame.SetLocation(new PointF(0,parentFrame.Height));
UIView.BeginAnimations("slidePickerIn");
UIView.SetAnimationDuration(0.3);
UIView.SetAnimationDelegate(this);
UIView.SetAnimationDidStopSelector (new Selector ("fadeInDidFinish"));
//parentView.AddSubview(closeView);
parentView.AddSubview(pickerView);
var tb = new UITextField(new RectangleF(0,-100,15,25));
//closeView.AddSubview(tb);
tb.BecomeFirstResponder();
tb.ResignFirstResponder();
tb.RemoveFromSuperview();
pickerView.Frame = pickerView.Frame.SetLocation(new PointF(0,parentFrame.Height - pickerView.Frame.Height));
UIView.CommitAnimations();
}
public bool IsHiding;
public void HidePicker(bool Animated = true)
{
var parentView = ViewForPicker ?? Superview;
if(PickerClosed!=null)
PickerClosed(this,null);
if(IsHiding || parentView == null)
return;
IsHiding = true;
var parentH = parentView.Frame.Height;
if (Animated) {
UIView.BeginAnimations("slidePickerOut");
UIView.SetAnimationDuration(0.3);
UIView.SetAnimationDelegate(this);
UIView.SetAnimationDidStopSelector (new Selector ("fadeOutDidFinish"));
pickerView.Frame = pickerView.Frame.SetLocation(new PointF(0,parentH));
UIView.CommitAnimations();
}
else {
parentView.SendSubviewToBack(pickerView);
IsHiding = false;
}
}
public void SetSelectedIndex(int index) {
pickerView.Select(index, 0, true);
pickerView.SelectedIndex = index;
}
public void SetSelectedValue(string Value) {
var xx = 0;
foreach(var item in pickerView.Items) {
if (item.ToString() == Value) {
pickerView.Select(xx, 0, true);
pickerView.SelectedIndex = xx;
}
xx += 1;
}
}
public object SelectedItem {
get {return pickerView.SelectedItem;}
}
[Export("fadeOutDidFinish")]
public void FadeOutDidFinish ()
{
pickerView.RemoveFromSuperview();
//closeView.RemoveFromSuperview();
pickerVisible = false;
IsHiding = false;
}
[Export("fadeInDidFinish")]
public void FadeInDidFinish ()
{
pickerView.BecomeFirstResponder();
pickerView.BringSubviewToFront(closeBtn);
if (PickerFadeInDidFinish != null) {
PickerFadeInDidFinish(this, null);
}
}
}
public class PickerView : UIPickerView
{
public PickerView () : base ()
{
this.ShowSelectionIndicator = true;
this.Width = 300f;
}
object[] items;
public object[] Items
{
get{return items;}
set{
items = value;
this.Model = new PickerData(this);
if(IndexChanged != null)
IndexChanged(this,null);
}
}
public string DisplayMember {get;set;}
public string ValueMember {get;set;}
public float Width {get;set;}
int selectedIndex;
public int SelectedIndex{
get {return selectedIndex;}
set{
if(selectedIndex == value)
return;
selectedIndex = value;
if(IndexChanged != null)
IndexChanged(this,null);
}
}
public object SelectedItem {get{return items[SelectedIndex];}}
public string StringValue {
get{
if(string.IsNullOrEmpty(ValueMember))
return SelectedItem.ToString();
return Util.GetPropertyValue(SelectedItem,ValueMember);
}
}
public event EventHandler IndexChanged;
}
public class PickerData : UIPickerViewModel
{
PickerView Picker;
public PickerData (PickerView picker)
{
Picker = picker;
}
public override int GetComponentCount (UIPickerView uipv)
{
return (1);
}
public override int GetRowsInComponent (UIPickerView uipv, int comp)
{
//each component has its own count.
int rows = Picker.Items.Length;
return (rows);
}
public override string GetTitle (UIPickerView uipv, int row, int comp)
{
//each component would get its own title.
var theObject = Picker.Items[row];
if(string.IsNullOrEmpty(Picker.DisplayMember))
return theObject.ToString();
return Util.GetPropertyValue(theObject,Picker.DisplayMember);
}
public override void Selected (UIPickerView uipv, int row, int comp)
{
Picker.SelectedIndex = row;
//Picker.Select(row,comp,false);
}
public override float GetComponentWidth (UIPickerView uipv, int comp)
{
return Picker.Width;
}
public override float GetRowHeight (UIPickerView uipv, int comp)
{
return (40f);
}
//CDEUTSCH: there are issues with this losing the contents of rows when there are multiple pickers on a page.
//public override UIView GetView (UIPickerView pickerView, int row, int component, UIView view) {
// ((UIView)Picker.Items[row]).ReloadInputViews();
// return (UIView)Picker.Items[row];
//}
}
}
| |
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Database;
using Android.OS;
using Android.Provider;
using Environment = Android.OS.Environment;
using Path = System.IO.Path;
using Uri = Android.Net.Uri;
using Drecogrizer.Controls.Media;
namespace Drecogrizer.Droid.Media
{
[Activity]
[Android.Runtime.Preserve(AllMembers = true)]
public class MediaPickerActivity : Activity
{
internal const string ExtraPath = "path";
internal const string ExtraLocation = "location";
internal const string ExtraType = "type";
internal const string ExtraId = "id";
internal const string ExtraAction = "action";
internal const string ExtraTasked = "tasked";
private const string JpgExtension = ".jpg";
internal static event EventHandler<MediaPickedEventArgs> MediaPicked;
private int id;
private string title;
private string description;
private string type;
private Uri path;
private string action;
private int seconds;
private bool tasked;
protected override void OnSaveInstanceState(Bundle outState)
{
outState.PutBoolean("ran", true);
outState.PutString(MediaStore.MediaColumns.Title, title);
outState.PutString(MediaStore.Images.ImageColumns.Description, description);
outState.PutInt(ExtraId, id);
outState.PutString(ExtraType, type);
outState.PutString(ExtraAction, action);
outState.PutInt(MediaStore.ExtraDurationLimit, seconds);
outState.PutBoolean(ExtraTasked, tasked);
if (path != null)
{
outState.PutString(ExtraPath, path.Path);
}
base.OnSaveInstanceState(outState);
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
var b = (savedInstanceState ?? Intent.Extras);
bool ran = b.GetBoolean("ran", defaultValue: false);
title = b.GetString(MediaStore.MediaColumns.Title);
description = b.GetString(MediaStore.Images.ImageColumns.Description);
tasked = b.GetBoolean(ExtraTasked);
id = b.GetInt(ExtraId, 0);
type = b.GetString(ExtraType);
action = b.GetString(ExtraAction);
Intent pickIntent = null;
try
{
pickIntent = new Intent(action);
if (action == Intent.ActionPick)
pickIntent.SetType(type);
else
{
if (!ran)
{
path = GetOutputMediaFile(this, b.GetString(ExtraPath), title);
Touch();
pickIntent.PutExtra(MediaStore.ExtraOutput, path);
}
else
{
path = Uri.Parse(b.GetString(ExtraPath));
}
}
if (!ran)
{
StartActivityForResult(pickIntent, id);
}
}
catch (Exception ex)
{
OnMediaPicked(new MediaPickedEventArgs(id, ex));
}
finally
{
pickIntent?.Dispose();
}
}
private void Touch()
{
if (path.Scheme != "file")
{
return;
}
File.Create(GetLocalPath(path)).Close();
}
internal static Task<MediaPickedEventArgs> GetMediaFileAsync(Context context, int requestCode, string action,
ref Uri path, Uri data)
{
Task<Tuple<string, bool>> pathFuture;
string originalPath = null;
if (action != Intent.ActionPick)
{
originalPath = path.Path;
// Not all camera apps respect EXTRA_OUTPUT, some will instead
// return a content or file uri from data.
if (data != null && data.Path != originalPath)
{
originalPath = data.ToString();
string currentPath = path.Path;
pathFuture =
TryMoveFileAsync(context, data, path)
.ContinueWith(t => new Tuple<string, bool>(t.Result ? currentPath : null, false));
}
else
{
pathFuture = TaskFromResult(new Tuple<string, bool>(path.Path, false));
}
}
else if (data != null)
{
originalPath = data.ToString();
path = data;
pathFuture = GetFileForUriAsync(context, path);
}
else
{
pathFuture = TaskFromResult<Tuple<string, bool>>(null);
}
return pathFuture.ContinueWith(t =>
{
string resultPath = t.Result.Item1;
if (resultPath != null && File.Exists(t.Result.Item1))
{
var mf = new MediaFile(resultPath, () => File.OpenRead(resultPath),
deletePathOnDispose: t.Result.Item2, dispose: (dis) =>
{
if (t.Result.Item2)
{
try
{
File.Delete(t.Result.Item1);
// We don't really care if this explodes for a normal IO reason.
}
catch (UnauthorizedAccessException)
{
}
catch (DirectoryNotFoundException)
{
}
catch (IOException)
{
}
}
});
return new MediaPickedEventArgs(requestCode, false, mf);
}
return new MediaPickedEventArgs(requestCode, new MediaFileNotFoundException(originalPath));
});
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (tasked)
{
var future = resultCode == Result.Canceled
? TaskFromResult(new MediaPickedEventArgs(requestCode, isCanceled: true))
: GetMediaFileAsync(this, requestCode, this.action, ref this.path, data?.Data);
Finish();
future.ContinueWith(t => OnMediaPicked(t.Result));
}
else
{
if (resultCode == Result.Canceled)
{
SetResult(Result.Canceled);
}
else
{
var resultData = new Intent();
resultData.PutExtra("MediaFile", data?.Data);
resultData.PutExtra("path", this.path);
resultData.PutExtra("action", this.action);
SetResult(Result.Ok, resultData);
}
Finish();
}
}
private static Task<bool> TryMoveFileAsync(Context context, Uri url, Uri path)
{
string moveTo = GetLocalPath(path);
return GetFileForUriAsync(context, url).ContinueWith(t =>
{
if (t.Result.Item1 == null)
return false;
File.Delete(moveTo);
File.Move(t.Result.Item1, moveTo);
if (url.Scheme == "content")
context.ContentResolver.Delete(url, null, null);
return true;
}, TaskScheduler.Default);
}
private static string GetUniquePath(string folder, string name)
{
string ext = Path.GetExtension(name);
if (ext == String.Empty)
ext = JpgExtension;
name = Path.GetFileNameWithoutExtension(name);
string fullName = name + ext;
int i = 1;
while (File.Exists(Path.Combine(folder, fullName)))
fullName = $"{name}_{(i++)}{ext}";
return Path.Combine(folder, fullName);
}
private static Uri GetOutputMediaFile(Context context, string subdir, string name)
{
subdir = subdir ?? String.Empty;
if (String.IsNullOrWhiteSpace(name))
{
string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
name = $"IMG_{timestamp}{JpgExtension}";
}
string mediaType = Environment.DirectoryPictures;
using (var mediaStorageDir = new Java.IO.File(context.GetExternalFilesDir(mediaType), subdir))
{
if (!mediaStorageDir.Exists())
{
if (!mediaStorageDir.Mkdirs())
{
throw new IOException(
"Couldn't create directory, have you added the WRITE_EXTERNAL_STORAGE permission?");
}
// Ensure this media doesn't show up in gallery apps
using (Java.IO.File nomedia = new Java.IO.File(mediaStorageDir, ".nomedia"))
{
nomedia.CreateNewFile();
}
}
return Uri.FromFile(new Java.IO.File(GetUniquePath(mediaStorageDir.Path, name)));
}
}
internal static Task<Tuple<string, bool>> GetFileForUriAsync(Context context, Uri uri)
{
var tcs = new TaskCompletionSource<Tuple<string, bool>>();
if (uri.Scheme == "file")
{
tcs.SetResult(new Tuple<string, bool>(new System.Uri(uri.ToString()).LocalPath, false));
}
else if (uri.Scheme == "content")
{
Task.Factory.StartNew(() =>
{
ICursor cursor = null;
try
{
cursor = context.ContentResolver.Query(uri, null, null, null, null);
if (cursor == null || !cursor.MoveToNext())
{
tcs.SetResult(new Tuple<string, bool>(null, false));
}
else
{
int column = cursor.GetColumnIndex(MediaStore.MediaColumns.Data);
string contentPath = null;
if (column != -1)
{
contentPath = cursor.GetString(column);
}
bool copied = false;
// If they don't follow the "rules", try to copy the file locally
if (contentPath == null || !contentPath.StartsWith("file"))
{
copied = true;
var outputPath = GetOutputMediaFile(context, "temp", null);
try
{
using (var input = context.ContentResolver.OpenInputStream(uri))
{
using (var output = File.Create(outputPath.Path))
{
input.CopyTo(output);
}
}
contentPath = outputPath.Path;
}
catch (Java.IO.FileNotFoundException)
{
// If there's no data associated with the uri, we don't know
// how to open this. contentPath will be null which will trigger
// MediaFileNotFoundException.
}
}
tcs.SetResult(new Tuple<string, bool>(contentPath, copied));
}
}
finally
{
if (cursor != null)
{
cursor.Close();
cursor.Dispose();
}
}
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
}
else
{
tcs.SetResult(new Tuple<string, bool>(null, false));
}
return tcs.Task;
}
private static string GetLocalPath(Uri uri)
{
return new System.Uri(uri.ToString()).LocalPath;
}
private static Task<T> TaskFromResult<T>(T result)
{
var tcs = new TaskCompletionSource<T>();
tcs.SetResult(result);
return tcs.Task;
}
private static void OnMediaPicked(MediaPickedEventArgs e)
{
var picked = MediaPicked;
picked?.Invoke(null, e);
}
}
internal class MediaPickedEventArgs : EventArgs
{
public MediaPickedEventArgs(int id, Exception error)
{
if (error == null)
{
throw new ArgumentNullException(nameof(error));
}
RequestId = id;
Error = error;
}
public MediaPickedEventArgs(int id, bool isCanceled, MediaFile media = null)
{
RequestId = id;
IsCanceled = isCanceled;
if (!IsCanceled && media == null)
{
throw new ArgumentNullException(nameof(media));
}
Media = media;
}
public int RequestId { get; private set; }
public bool IsCanceled { get; private set; }
public Exception Error { get; private set; }
public MediaFile Media { get; private set; }
public Task<MediaFile> ToTask()
{
var tcs = new TaskCompletionSource<MediaFile>();
if (IsCanceled)
{
tcs.SetResult(null);
}
else if (Error != null)
{
tcs.SetResult(null);
}
else
{
tcs.SetResult(Media);
}
return tcs.Task;
}
}
}
| |
using System;
using System.Collections;
using Inform;
using Xenosynth.Data;
using Xenosynth.Web.UI;
namespace Xenosynth.Web {
/// <summary>
/// Registers a content block for a template.
/// </summary>
public class CmsRegisteredContent {
[MemberMapping(PrimaryKey=true, ColumnName="ID")]
private Guid registeredContentID;
[MemberMapping(ColumnName="TemplateID")]
private Guid templateID;
[MemberMapping(ColumnName="ControlID", Length=250)]
private string controlID;
[MemberMapping(ColumnName="ContentTypeName", Length=500)]
private string contentTypeName;
public CmsRegisteredContent() {
}
/// <summary>
/// The unique identifier of the registered content.
/// </summary>
public Guid ID {
get { return registeredContentID; }
}
/// <summary>
/// The Cmstemplate's unique identifier.
/// </summary>
public Guid TemplateID {
get { return templateID; }
set { templateID = value; }
}
/// <summary>
/// The name of the content block.
/// </summary>
public string ControlID {
get { return controlID; }
set { controlID = value; }
}
/// <summary>
/// The class that implements the IContentPersister for this content block.
/// </summary>
public string ContentTypeName {
get { return contentTypeName; }
set { contentTypeName = value; }
}
internal IContentPersister GetContentTypePersister(){
Type t = Type.GetType(ContentTypeName, true);
return (IContentPersister)t.GetConstructor(Type.EmptyTypes).Invoke(null);
}
/// <summary>
/// Registers the content for the pages that use the template.
/// </summary>
public void Register(){
registeredContentID = Guid.NewGuid();
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
try{
ds.BeginTransaction();
ds.Insert(this);
//for each page using template, add default content
IList pages = CmsPage.FindByTemplateID(this.TemplateID);
IContentPersister cp = GetContentTypePersister();
foreach(CmsPage p in pages){
cp.CreateInitialContent(this.ControlID, p.ID);
}
ds.CommitTransaction();
} catch (Exception e) {
ds.RollbackTransaction();
throw e;
}
}
/// <summary>
/// Creates the intial content for the page.
/// </summary>
/// <param name="pageID">
/// A <see cref="Guid"/>
/// </param>
public void CreateInitialContent(Guid pageID){
IContentPersister cp = GetContentTypePersister();
cp.CreateInitialContent(this.ControlID, pageID);
}
/// <summary>
/// Copies the content to another page/
/// </summary>
/// <param name="sourcePageID">
/// A <see cref="Guid"/>
/// </param>
/// <param name="destinationPageID">
/// A <see cref="Guid"/>
/// </param>
public void CopyContent(Guid sourcePageID, Guid destinationPageID){
IContentPersister cp = GetContentTypePersister();
cp.CopyContent(this.ControlID, sourcePageID, destinationPageID);
}
/// <summary>
/// Deletes the content for a page.
/// </summary>
/// <param name="pageID">
/// A <see cref="Guid"/>
/// </param>
public void DeleteContent(Guid pageID){
//TODO: Call more directly?
IContentPersister cp = GetContentTypePersister();
cp.DeleteContent(this.ControlID, pageID);
}
/// <summary>
/// Deletes the content for a page.
/// </summary>
/// <param name="pageID">
/// A <see cref="Guid"/>
/// </param>
public void Delete(Guid pageID){
//TODO: Call more directly?
IContentPersister cp = GetContentTypePersister();
cp.DeleteContent(this.ControlID, pageID);
}
/// <summary>
/// Finds the CmsRegisteredContent by ID.
/// </summary>
/// <param name="id">
/// A <see cref="Guid"/>
/// </param>
/// <returns>
/// A <see cref="CmsRegisteredContent"/>
/// </returns>
public static CmsRegisteredContent FindByID(Guid id){
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
return (CmsRegisteredContent)ds.FindByPrimaryKey(typeof(CmsRegisteredContent),id);
}
/// <summary>
/// Finds all CmsRegisteredContent for a template.
/// </summary>
/// <param name="templateID">
/// A <see cref="Guid"/>
/// </param>
/// <returns>
/// A <see cref="IList"/>
/// </returns>
public static IList FindByTemplateID(Guid templateID){
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IFindCollectionCommand cmd = ds.CreateFindCollectionCommand(typeof(CmsRegisteredContent),"WHERE TemplateID = @TemplateID");
cmd.CreateInputParameter("@TemplateID", templateID);
return cmd.Execute();
}
/// <summary>
/// Finds all CmsRegisteredContent for a template using a specified name.
/// </summary>
/// <param name="templateID">
/// A <see cref="Guid"/>
/// </param>
/// <param name="controlID">
/// A <see cref="System.String"/>
/// </param>
/// <returns>
/// A <see cref="CmsRegisteredContent"/>
/// </returns>
public static CmsRegisteredContent FindByTemplateID(Guid templateID, string controlID){
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IFindObjectCommand cmd = ds.CreateFindObjectCommand(typeof(CmsRegisteredContent),"WHERE TemplateID = @TemplateID");
cmd.CreateInputParameter("@TemplateID", templateID);
cmd.CreateInputParameter("@ControlID", controlID);
return (CmsRegisteredContent)cmd.Execute();
}
/// <summary>
/// Removes a content bloc from all pages using the template.
/// </summary>
public void Unregister(){
//for each page using template, delete content
IList pages = CmsPage.FindByTemplateID(this.TemplateID);
IContentPersister cp = GetContentTypePersister();
foreach(CmsPage p in pages){
cp.DeleteContent(this.ControlID, p.ID);
}
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
ds.Delete(this);
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RouteTablesOperations operations.
/// </summary>
public partial interface IRouteTablesOperations
{
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteTable>> GetWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteTable>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, RouteTable parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RouteTable>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RouteTable>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteTable>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, RouteTable parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RouteTable>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RouteTable>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Diagnostics;
using System.Drawing;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using DirectInput = Microsoft.DirectX.DirectInput;
namespace Simbiosis
{
// There is only one camera. However, it can be attached to any cell capable of carrying it. This may be
// a vehicle (e.g. the submarine), a static dolly or skycam, or a specialised "eye" cell on an organism.
// The camera is carried by a hotspot on a cell, and thus the whole of the Organism, Cell and Physiology
// functionality is available for moving the camera, collision detection, etc.
// It also makes camera platforms visible when seen from another camera (e.g. the sub can be seen from a dolly cam).
//
// ATTACHING THE CAMERA TO A CELL
// The camera is always carried on the hotspot of a cell, for example the submarine "organism"
// or a creatures-eye-view (on a specialised cell).
//
// To attach the camera to a cell, call Organism.AssignCamera(), which in turn calls Cell.AssignCamera()
// for each of its cells, and they call the Physiology.AssignCamera() appropriate for their cell type.
// If that cell type accepts the role of camera mount, Physiology.AssignCamera() returns a hotspot number,
// which Cell.AssignCamera() then stores in the camera using Camera.cameraMount and Camera.cemeraHotspot.
// The outer call to Organism.AssignCamera() then returns true to confirm that the camera has been accepted.
// Every tick thereafter, the camera calls the appropriate Cell.GetCameraMatrix() to fetch the
// location/orientation of the hotspot. The inverse of this matrix determines the camera location.
//
// Organism.AssignCamera()
/// <summary>
/// static Camera object
/// </summary>
public static class Camera
{
/// <summary> Scanner modes - controls how cells will be visualised </summary>
public enum ScannerModes
{
Normal, // Normal textured camera display
Cell, // Cell design mode - highlights the cell/creature being edited
Channel, // Channel-editing mode
Chemical, // ChemoScan: display a local/global chemical concentration
};
/// <summary> Current display mode </summary>
public static ScannerModes ScannerMode = ScannerModes.Normal;
public enum CameraMode
{
Dolly, // user-controlled or stationary location and orientation
Carried, // object's-eye view
Map, // in the sky pointing down (& following a target object if selected)
Chasing // hovers around a target object
}
// The above modes as strings, for HUD info
public static string[] modeName =
{
"SteerableCam", // dolly
"EyeCam", // carried
"SkyCam", // map
"ChaseCam" // chasing
};
private const float MaxZoom = (float)Math.PI/10.0f; // min & max field-of-view for zooming
private const float MinZoom = (float)Math.PI/3.0f;
private const float NormalZoom = (float)Math.PI/3.0f; // normal FOV
/// <summary> Current projection & view matrices for computing frustrum clip planes </summary>
private static Matrix viewMatrix = new Matrix();
public static Matrix ViewMatrix { get { return viewMatrix; } }
private static Matrix projMatrix = new Matrix();
public static Matrix ProjMatrix { get { return projMatrix; } }
/// <summary> Frustrum as a series of planes for clipping </summary>
private static Plane[] frustrum = new Plane[6];
/// <summary> Frustrum as a box (better for some kinds of clipping)</summary>
private static Vector3[] corner = new Vector3[8];
/// <summary>
/// Location of camera if Fixed or Tracking.
/// </summary>
public static Vector3 position = new Vector3(1.0f,1.0f,1.0f);
/// <summary> Yaw direction of camera (used to orient billboard sprites) </summary>
public static float bearing = 0;
/// <summary> Field-of-view (PI/4=45 degrees = normal)</summary>
private static float fov = NormalZoom;
/// <summary>
/// The viewport to be used when rendering the 3D portion of the display. This can be smaller than the panel to clip unnecessary drawing.
/// Its extent is computed by calling the GetSceneViewport() method of the current cameraship.
/// </summary>
public static Viewport SceneViewport = new Viewport();
/// <summary>
/// The viewport to be used when rendering the whole display, including panel. This may be smaller than the window,
/// to ensure the display maintains the same aspect ratio as a 1024x768 screen.
/// </summary>
public static Viewport PanelViewport { get { return Camera.panelViewport; } }
private static Viewport panelViewport = new Viewport();
/// <summary>
/// constr
/// </summary>
static Camera()
{
}
/// <summary>
/// Once the first D3D device has been created, set up those things that couldn't be done before
/// </summary>
public static void OnDeviceCreated()
{
Debug.WriteLine("Camera.OnDeviceCreated()");
// Recalculate view data on resets of device
//Engine.Device.DeviceReset += new System.EventHandler(OnReset);
OnReset();
}
/// <summary>
/// Called immediately after the D3D device has been destroyed,
/// which generally happens as a result of application termination or
/// windowed/full screen toggles. Resources created in OnSubsequentDevices()
/// should be released here, which generally includes all Pool.Managed resources.
/// </summary>
public static void OnDeviceLost()
{
Debug.WriteLine("Camera.OnDeviceLost()");
Debug.WriteLine("(does nothing)");
}
// Device has been reset - reinitialise renderstate variables that
// normally don't get modified each frame
public static void OnReset()
{
Debug.WriteLine("Camera.OnReset()");
SetViewports();
}
/// <summary>
/// Compute & set projection matrix for frustrum, following a reset or zoom
/// </summary>
public static void SetProjection()
{
// Size of viewport
float width = (float)SceneViewport.Width;
float height = (float)SceneViewport.Height;
projMatrix = // keep the result in a static field for frustrum calcs
Matrix.PerspectiveFovLH(fov, // field of view
width / height, // aspect ratio
1f, // near clipping plane (metres)
Scene.Horizon); // far clipping plane (metres)
///Engine.Device.SetTransform(TransformType.Projection, projMatrix); // set the device projection matrix
Debug.Assert(projMatrix.M34 == 1.0f, "WARNING: Projection matrix is not W-friendly - fog won't be rendered properly. See DX documentation");
SetFrustrum(); // recompute the clip planes
}
/// <summary>
/// Set the two viewports for the new window size:
/// Camera.sceneViewport defines the screen area into which the 3D scene will be rendered.
/// Camera.panelViewport defines the screen ares into which the cameraship panel will be rendered.
/// Both are set to the same aspect ratio as a 1024x768 screen. I.e. if the window is wider than this aspect ratio, the display will be centred in it,
/// with dark bands to either side. This enables the game to run fullscreen on a widescreen monitor.
/// Call this function on a reset. Scene.Render() uses the two Viewport objects when rendering the scene and panel.
/// </summary>
private static void SetViewports()
{
const float BASEASPECT = 1024f / 768f; // The sprite graphics are drawn to this aspect ratio
Rectangle window = Rectangle.Empty;
// Compute the overall viewport - whole window, minus the borders needed to keep a 1024x768 aspect...
if (Engine.Framework.IsWindowed == true) // If we're windowed, ClientRectangle contains the size
window = Engine.Framework.ClientRectangle;
else // but for fullscreen, look at the screen mode
{ // (note: this fixes the fullscreen bug! ClientRectangle
window.Width = Engine.Device.DisplayMode.Width; // is zero when we go fullscreen)
window.Height = Engine.Device.DisplayMode.Height;
}
panelViewport.X = window.X; // initialise viewport to full window/screen
panelViewport.Y = window.Y;
panelViewport.Width = window.Width;
panelViewport.Height = window.Height;
panelViewport.MaxZ = 1.0f;
float currentAspect = (float)window.Width / (float)window.Height; // get the window aspect ratio
if (currentAspect > BASEASPECT) // if the window is too wide
{
panelViewport.Width = (int)(window.Width / currentAspect * BASEASPECT); // calculate a new width & store
panelViewport.X = (int)((window.Width - panelViewport.Width) / 2f); // then calculate an X-offset to centre the display
}
else // if it is too tall, centre display vertically instead
{
panelViewport.Height = (int)(window.Height / BASEASPECT * currentAspect);
panelViewport.Y = (int)((window.Height - panelViewport.Height) / 2f);
}
//Debug.WriteLine("Window: " + window.ToString());
//Debug.WriteLine("PanelViewport: x = " + panelViewport.X + " y = " + panelViewport.Y + " width = " + panelViewport.Width + " height = " + panelViewport.Height);
}
/// <summary>
/// Set up the view and projection matrices for the current camera position/angle
/// Call this every frame.
/// </summary>
/// <param name="elapsedtime">number of seconds elapsed since last frame</param>
/// <param name="simtime">time that has elapsed since simulation began</param>
public static void Render()
{
// The camera matrix is the inverse of the camera mount cell's hotspot frame
Matrix hotspot = CameraShip.CurrentShip.GetCameraMatrix();
viewMatrix = Matrix.Invert(hotspot);
// Update the frustrum clip planes
SetFrustrum();
// update Camera.position from the matrix, so that it is correct for LOD calculations etc.
position = new Vector3(hotspot.M41,hotspot.M42,hotspot.M43);
// Update camera bearing angle, so that it can be used by billboards, etc.
hotspot.M41 = hotspot.M42 = hotspot.M43 = 0; // remove the translation component
Vector3 normal = new Vector3(0,0,1); // vector representing the hotspot normal
normal = Vector3.TransformCoordinate(normal,hotspot); // rotate this into hotspot orientation
bearing = (float)( Math.PI/2 - Math.Atan2(normal.Z, normal.X)); // and compute its bearing (yaw)
// Send new camera data (position and shadow matrix) to the shaders
Fx.SetCameraData();
}
/// <summary>
/// Calculate the frustrum sides, ready for culling
/// </summary>
/// <remarks>
/// Works by creating a unit cube in front of the camera and then transforming
/// this by the view and projection matrices, to give a box the size and shape of the viewing
/// frustrum. This is then used as the framework for calculating the planes of its six sides,
/// which are used when culling
/// </remarks>
public static void SetFrustrum()
{
// set up the transformation
Matrix m = Matrix.Multiply(viewMatrix,projMatrix); // combined view & proj matrices
m.Invert(); // we need to do the opposite xform
// set up a box with unit corners, in front of the camera
corner[0] = new Vector3(-1.0f,-1.0f, 0.0f); // near b/l
corner[1] = new Vector3( 1.0f,-1.0f, 0.0f); // near b/r
corner[2] = new Vector3(-1.0f, 1.0f, 0.0f); // near t/l
corner[3] = new Vector3( 1.0f, 1.0f, 0.0f); // near t/r
corner[4] = new Vector3(-1.0f,-1.0f, 1.0f); // far b/l
corner[5] = new Vector3( 1.0f,-1.0f, 1.0f); // far b/r
corner[6] = new Vector3(-1.0f, 1.0f, 1.0f); // far t/l
corner[7] = new Vector3( 1.0f, 1.0f, 1.0f); // far t/r
// transform each corner into the view frustrum
for (int i=0; i<8; i++)
corner[i] = Vector3.TransformCoordinate(corner[i],m);
// use the transformed corners to build the six faces of the frustrum
frustrum[0] = Plane.FromPoints(corner[7],corner[3],corner[1]); // right face
frustrum[1] = Plane.FromPoints(corner[2],corner[6],corner[4]); // left face
frustrum[2] = Plane.FromPoints(corner[6],corner[7],corner[5]); // far face
frustrum[3] = Plane.FromPoints(corner[0],corner[1],corner[3]); // near face
// Top & bottom faces are at end so can be skipped during horizontal clip tests
frustrum[4] = Plane.FromPoints(corner[2],corner[3],corner[7]); // top face
frustrum[5] = Plane.FromPoints(corner[4],corner[5],corner[1]); // bottom face
}
/// <summary>
/// Check to see whether a bounding sphere/circle intersects the viewing frustrum
/// (e.g. for culling).
/// </summary>
/// <remarks>
/// Note: for 3D objects I need to check whether they're inside ALL walls of the frustrum (including top and
/// bottom). When checking for visible QUADS, however, I should only compare against the sides, since a quad
/// has a bounding sphere of finite height, but should be treated as if it extends upwards to infinity. To do
/// this, pass 4 instead of 6 in the "planes" parameter.
/// </remarks>
/// <param name="centre">xyz of centre of sphere</param>
/// <param name="radius">radius of sphere</param>
/// <param name="planes">Enter 6 to check if an object is within the entire frustrum (top/bottom as well
/// as sides), or 4 to check if a point on the MAP (e.g. a quad) is within the LATERAL extent
/// of the frustrum</param>
/// <returns>0=outside frustrum; 1=inside frustrum; -1=straddles frustrum</returns>
public static int CanSee(Vector3 centre, float radius, int planes)
{
float dist;
int behind = 0; // counts # faces point is behind
for (int i=0; i<planes; i++) // for each face
{
dist = frustrum[i].Dot(centre); // compute distance from the plane
if (dist < -radius) // if it's more than radius beyond plane
return 0; // object can't intersect frustrum at all
if (dist > radius) // if it's more than radius inside the plane
behind++; // it's fully enclosed by one more surface
}
if (behind==planes) // if fully enclosed by all 6 planes
return 1; // it's fully inside frustrum
return -1; // otherwise it must straddle it
}
/// <summary>
/// Overload of above to test whether a given 3D renderable object is within frustrum
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static int CanSee(Renderable obj)
{
return (CanSee(obj.AbsSphere.Centre,obj.AbsSphere.Radius, 6));
}
/// <summary>
/// Adjust camera zoom
/// </summary>
/// <param name="amount">positive values zoom OUT (wider angle)</param>
public static void ZoomBy(float amount)
{
ZoomTo(fov + amount);
}
/// <summary>
/// Set camera zoom
/// </summary>
/// <param name="amount">PI/4 is 45 degrees (normal perspective)</param>
public static void ZoomTo(float amount)
{
fov = amount;
if (fov < MaxZoom) fov = MaxZoom;
if (fov > MinZoom) fov = MinZoom;
SetProjection(); // recompute projection matrix
}
/// <summary>
/// Reset to default zoom
/// </summary>
public static void ZoomReset()
{
ZoomTo(NormalZoom);
}
#region properties
/// <summary> Return camera location in world (works in all modes) </summary>
public static Vector3 Position
{
get
{
return position;
}
}
/// <summary>
/// Names of the permissible camera modes (e.g. for filling panel controls)
/// </summary>
/// <param name="index">mode to fetch</param>
/// <returns>name of mode, or null if index is too large</returns>
public static string ModeName(int index)
{
if (index>=modeName.Length)
return null;
return modeName[index];
}
#endregion
/// <summary>
/// Given a mouse click, find the cell that has been clicked on
/// </summary>
/// <param name="screenX">the mouse cursor position when the click occurred</param>
/// <param name="screenY"></param>
/// <param name="socket">If a SOCKET on the cell was selected, its frame is returned here</param>
/// <returns>The picked cell, or null if no cell at that point</returns>
public static Cell MousePick(float screenX, float screenY, out JointFrame socket)
{
// Step 1: Convert the mouse position into an eyepoint in 3D
Vector3 v = new Vector3();
screenX -= Camera.SceneViewport.X; // remove offset of viewport
screenY -= Camera.SceneViewport.Y;
v.X = (((2.0f * screenX) / Camera.SceneViewport.Width) - 1) / projMatrix.M11;
v.Y = -(((2.0f * screenY) / Camera.SceneViewport.Height) - 1) / projMatrix.M22;
v.Z = 1.0f;
// Step 2: Create a ray emanating from the mouse cursor in the direction of the camera
Matrix m = viewMatrix;
m.Invert();
Vector3 rayDirection = new Vector3(
v.X * m.M11 + v.Y * m.M21 + v.Z * m.M31,
v.X * m.M12 + v.Y * m.M22 + v.Z * m.M32,
v.X * m.M13 + v.Y * m.M23 + v.Z * m.M33);
Vector3 rayPosition = new Vector3(m.M41, m.M42, m.M43);
// Step 3: Iterate through the orgs and cells to find the nearest one to the camera that our ray intersects
return Map.MousePick(rayPosition, rayDirection, out socket);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Autofac.Features.Metadata;
using Orchard.Environment.Extensions.Models;
namespace Orchard.UI.Resources {
public class ResourceManager : IResourceManager, IUnitOfWorkDependency {
private readonly Dictionary<Tuple<String, String>, RequireSettings> _required = new Dictionary<Tuple<String, String>, RequireSettings>();
private readonly List<LinkEntry> _links = new List<LinkEntry>();
private readonly Dictionary<string, MetaEntry> _metas = new Dictionary<string, MetaEntry> {
{ "generator", new MetaEntry { Content = "Orchard", Name = "generator" } }
};
private readonly Dictionary<string, IList<ResourceRequiredContext>> _builtResources = new Dictionary<string, IList<ResourceRequiredContext>>(StringComparer.OrdinalIgnoreCase);
private readonly IEnumerable<Meta<IResourceManifestProvider>> _providers;
private ResourceManifest _dynamicManifest;
private List<String> _headScripts;
private List<String> _footScripts;
private IEnumerable<IResourceManifest> _manifests;
private const string NotIE = "!IE";
private static string ToAppRelativePath(string resourcePath) {
if (!String.IsNullOrEmpty(resourcePath) && !Uri.IsWellFormedUriString(resourcePath, UriKind.Absolute)) {
resourcePath = VirtualPathUtility.ToAppRelative(resourcePath);
}
return resourcePath;
}
private static string FixPath(string resourcePath, string relativeFromPath) {
if (!String.IsNullOrEmpty(resourcePath) && !VirtualPathUtility.IsAbsolute(resourcePath) && !Uri.IsWellFormedUriString(resourcePath, UriKind.Absolute)) {
// appears to be a relative path (e.g. 'foo.js' or '../foo.js', not "/foo.js" or "http://..")
if (String.IsNullOrEmpty(relativeFromPath)) {
throw new InvalidOperationException("ResourcePath cannot be relative unless a base relative path is also provided.");
}
resourcePath = VirtualPathUtility.ToAbsolute(VirtualPathUtility.Combine(relativeFromPath, resourcePath));
}
return resourcePath;
}
private static TagBuilder GetTagBuilder(ResourceDefinition resource, string url) {
var tagBuilder = new TagBuilder(resource.TagName);
tagBuilder.MergeAttributes(resource.TagBuilder.Attributes);
if (!String.IsNullOrEmpty(resource.FilePathAttributeName)) {
if (!String.IsNullOrEmpty(url)) {
if (VirtualPathUtility.IsAppRelative(url)) {
url = VirtualPathUtility.ToAbsolute(url);
}
tagBuilder.MergeAttribute(resource.FilePathAttributeName, url, true);
}
}
return tagBuilder;
}
public static void WriteResource(TextWriter writer, ResourceDefinition resource, string url, string condition, Dictionary<string, string> attributes) {
if (!string.IsNullOrEmpty(condition)) {
if (condition == NotIE) {
writer.WriteLine("<!--[if " + condition + "]>-->");
}
else {
writer.WriteLine("<!--[if " + condition + "]>");
}
}
var tagBuilder = GetTagBuilder(resource, url);
if (attributes != null) {
// todo: try null value
tagBuilder.MergeAttributes(attributes, true);
}
writer.WriteLine(tagBuilder.ToString(resource.TagRenderMode));
if (!string.IsNullOrEmpty(condition)) {
if (condition == NotIE) {
writer.WriteLine("<!--<![endif]-->");
}
else {
writer.WriteLine("<![endif]-->");
}
}
}
public ResourceManager(IEnumerable<Meta<IResourceManifestProvider>> resourceProviders) {
_providers = resourceProviders;
}
public IEnumerable<IResourceManifest> ResourceProviders {
get {
if (_manifests == null) {
var builder = new ResourceManifestBuilder();
foreach (var provider in _providers) {
builder.Feature = provider.Metadata.ContainsKey("Feature") ?
(Feature)provider.Metadata["Feature"] :
null;
provider.Value.BuildManifests(builder);
}
_manifests = builder.ResourceManifests;
}
return _manifests;
}
}
public virtual ResourceManifest DynamicResources {
get {
return _dynamicManifest ?? (_dynamicManifest = new ResourceManifest());
}
}
public virtual RequireSettings Require(string resourceType, string resourceName) {
if (resourceType == null) {
throw new ArgumentNullException("resourceType");
}
if (resourceName == null) {
throw new ArgumentNullException("resourceName");
}
RequireSettings settings;
var key = new Tuple<string, string>(resourceType, resourceName);
if (!_required.TryGetValue(key, out settings)) {
settings = new RequireSettings { Type = resourceType, Name = resourceName };
_required[key] = settings;
}
_builtResources[resourceType] = null;
return settings;
}
public virtual RequireSettings Include(string resourceType, string resourcePath, string resourceDebugPath) {
return Include(resourceType, resourcePath, resourceDebugPath, null);
}
public virtual RequireSettings Include(string resourceType, string resourcePath, string resourceDebugPath, string relativeFromPath) {
if (resourceType == null) {
throw new ArgumentNullException("resourceType");
}
if (resourcePath == null) {
throw new ArgumentNullException("resourcePath");
}
// ~/ ==> convert to absolute path (e.g. /orchard/..)
if (VirtualPathUtility.IsAppRelative(resourcePath)) {
resourcePath = VirtualPathUtility.ToAbsolute(resourcePath);
}
if (resourceDebugPath != null && VirtualPathUtility.IsAppRelative(resourceDebugPath)) {
resourceDebugPath = VirtualPathUtility.ToAbsolute(resourceDebugPath);
}
resourcePath = FixPath(resourcePath, relativeFromPath);
resourceDebugPath = FixPath(resourceDebugPath, relativeFromPath);
return Require(resourceType, ToAppRelativePath(resourcePath)).Define(d => d.SetUrl(resourcePath, resourceDebugPath));
}
public virtual void RegisterHeadScript(string script) {
if (_headScripts == null) {
_headScripts = new List<string>();
}
_headScripts.Add(script);
}
public virtual void RegisterFootScript(string script) {
if (_footScripts == null) {
_footScripts = new List<string>();
}
_footScripts.Add(script);
}
public virtual void NotRequired(string resourceType, string resourceName) {
if (resourceType == null) {
throw new ArgumentNullException("resourceType");
}
if (resourceName == null) {
throw new ArgumentNullException("resourceName");
}
var key = new Tuple<string, string>(resourceType, resourceName);
_builtResources[resourceType] = null;
_required.Remove(key);
}
public virtual ResourceDefinition FindResource(RequireSettings settings) {
return FindResource(settings, true);
}
private ResourceDefinition FindResource(RequireSettings settings, bool resolveInlineDefinitions) {
// find the resource with the given type and name
// that has at least the given version number. If multiple,
// return the resource with the greatest version number.
// If not found and an inlineDefinition is given, define the resource on the fly
// using the action.
var name = settings.Name ?? "";
var type = settings.Type;
var resource = (from p in ResourceProviders
from r in p.GetResources(type)
where name.Equals(r.Key, StringComparison.OrdinalIgnoreCase)
let version = r.Value.Version != null ? new Version(r.Value.Version) : null
orderby version descending
select r.Value).FirstOrDefault();
if (resource == null && _dynamicManifest != null) {
resource = (from r in _dynamicManifest.GetResources(type)
where name.Equals(r.Key, StringComparison.OrdinalIgnoreCase)
let version = r.Value.Version != null ? new Version(r.Value.Version) : null
orderby version descending
select r.Value).FirstOrDefault();
}
if (resolveInlineDefinitions && resource == null) {
// Does not seem to exist, but it's possible it is being
// defined by a Define() from a RequireSettings somewhere.
if (ResolveInlineDefinitions(settings.Type)) {
// if any were defined, now try to find it
resource = FindResource(settings, false);
}
}
return resource;
}
private bool ResolveInlineDefinitions(string resourceType) {
bool anyWereDefined = false;
foreach (var settings in GetRequiredResources(resourceType).Where(settings => settings.InlineDefinition != null)) {
// defining it on the fly
var resource = FindResource(settings, false);
if (resource == null) {
// does not already exist, so define it
resource = DynamicResources.DefineResource(resourceType, settings.Name).SetBasePath(settings.BasePath);
anyWereDefined = true;
}
settings.InlineDefinition(resource);
settings.InlineDefinition = null;
}
return anyWereDefined;
}
public virtual IEnumerable<RequireSettings> GetRequiredResources(string type) {
return _required.Where(r => r.Key.Item1 == type).Select(r => r.Value);
}
public virtual IList<LinkEntry> GetRegisteredLinks() {
return _links.AsReadOnly();
}
public virtual IList<MetaEntry> GetRegisteredMetas() {
return _metas.Values.ToList().AsReadOnly();
}
public virtual IList<String> GetRegisteredHeadScripts() {
return _headScripts == null ? null : _headScripts.AsReadOnly();
}
public virtual IList<String> GetRegisteredFootScripts() {
return _footScripts == null ? null : _footScripts.AsReadOnly();
}
public virtual IList<ResourceRequiredContext> BuildRequiredResources(string resourceType) {
IList<ResourceRequiredContext> requiredResources;
if (_builtResources.TryGetValue(resourceType, out requiredResources) && requiredResources != null) {
return requiredResources;
}
var allResources = new OrderedDictionary();
foreach (var settings in GetRequiredResources(resourceType)) {
var resource = FindResource(settings);
if (resource == null) {
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "A '{1}' named '{0}' could not be found.", settings.Name, settings.Type));
}
ExpandDependencies(resource, settings, allResources);
}
requiredResources = (from DictionaryEntry entry in allResources
select new ResourceRequiredContext { Resource = (ResourceDefinition)entry.Key, Settings = (RequireSettings)entry.Value }).ToList();
_builtResources[resourceType] = requiredResources;
return requiredResources;
}
protected virtual void ExpandDependencies(ResourceDefinition resource, RequireSettings settings, OrderedDictionary allResources) {
if (resource == null) {
return;
}
// Settings is given so they can cascade down into dependencies. For example, if Foo depends on Bar, and Foo's required
// location is Head, so too should Bar's location.
// forge the effective require settings for this resource
// (1) If a require exists for the resource, combine with it. Last settings in gets preference for its specified values.
// (2) If no require already exists, form a new settings object based on the given one but with its own type/name.
settings = allResources.Contains(resource)
? ((RequireSettings)allResources[resource]).Combine(settings)
: new RequireSettings { Type = resource.Type, Name = resource.Name }.Combine(settings);
if (resource.Dependencies != null) {
var dependencies = from d in resource.Dependencies
select FindResource(new RequireSettings { Type = resource.Type, Name = d });
foreach (var dependency in dependencies) {
if (dependency == null) {
continue;
}
ExpandDependencies(dependency, settings, allResources);
}
}
allResources[resource] = settings;
}
public void RegisterLink(LinkEntry link) {
_links.Add(link);
}
public void SetMeta(MetaEntry meta) {
if (meta == null) {
return;
}
var index = meta.Name ?? meta.HttpEquiv ?? "charset";
_metas[index] = meta;
}
public void AppendMeta(MetaEntry meta, string contentSeparator) {
if (meta == null) {
return;
}
var index = meta.Name ?? meta.HttpEquiv;
if (String.IsNullOrEmpty(index)) {
return;
}
MetaEntry existingMeta;
if (_metas.TryGetValue(index, out existingMeta)) {
meta = MetaEntry.Combine(existingMeta, meta, contentSeparator);
}
_metas[index] = meta;
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// GameplayScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion
namespace GameStateManagement
{
/// <summary>
/// This screen implements the actual game logic. It is just a
/// placeholder to get the idea across: you'll probably want to
/// put some more interesting gameplay in here!
/// </summary>
class GameplayScreen : GameScreen
{
#region Fields
ContentManager content;
SpriteFont gameFont;
Vector2 playerPosition = new Vector2(100, 100);
Vector2 enemyPosition = new Vector2(100, 100);
Random random = new Random();
float pauseAlpha;
#endregion
#region Initialization
/// <summary>
/// Constructor.
/// </summary>
public GameplayScreen()
{
TransitionOnTime = TimeSpan.FromSeconds(1.5);
TransitionOffTime = TimeSpan.FromSeconds(0.5);
}
/// <summary>
/// Load graphics content for the game.
/// </summary>
public override void LoadContent()
{
if (content == null)
content = new ContentManager(ScreenManager.Game.Services, "Content");
gameFont = content.Load<SpriteFont>("gamefont");
// A real game would probably have more content than this sample, so
// it would take longer to load. We simulate that by delaying for a
// while, giving you a chance to admire the beautiful loading screen.
Thread.Sleep(1000);
// once the load has finished, we use ResetElapsedTime to tell the game's
// timing mechanism that we have just finished a very long frame, and that
// it should not try to catch up.
ScreenManager.Game.ResetElapsedTime();
}
/// <summary>
/// Unload graphics content used by the game.
/// </summary>
public override void UnloadContent()
{
content.Unload();
}
#endregion
#region Update and Draw
/// <summary>
/// Updates the state of the game. This method checks the GameScreen.IsActive
/// property, so the game will stop updating when the pause menu is active,
/// or if you tab away to a different application.
/// </summary>
public override void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
base.Update(gameTime, otherScreenHasFocus, false);
// Gradually fade in or out depending on whether we are covered by the pause screen.
if (coveredByOtherScreen)
pauseAlpha = Math.Min(pauseAlpha + 1f / 32, 1);
else
pauseAlpha = Math.Max(pauseAlpha - 1f / 32, 0);
if (IsActive)
{
// Apply some random jitter to make the enemy move around.
const float randomization = 10;
enemyPosition.X += (float)(random.NextDouble() - 0.5) * randomization;
enemyPosition.Y += (float)(random.NextDouble() - 0.5) * randomization;
// Apply a stabilizing force to stop the enemy moving off the screen.
Vector2 targetPosition = new Vector2(
ScreenManager.GraphicsDevice.Viewport.Width / 2 - gameFont.MeasureString("Insert Gameplay Here").X / 2,
200);
enemyPosition = Vector2.Lerp(enemyPosition, targetPosition, 0.05f);
// TODO: this game isn't very fun! You could probably improve
// it by inserting something more interesting in this space :-)
}
}
/// <summary>
/// Lets the game respond to player input. Unlike the Update method,
/// this will only be called when the gameplay screen is active.
/// </summary>
public override void HandleInput(InputState input)
{
if (input == null)
throw new ArgumentNullException("input");
// Look up inputs for the active player profile.
int playerIndex = (int)ControllingPlayer.Value;
KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex];
GamePadState gamePadState = input.CurrentGamePadStates[playerIndex];
// The game pauses either if the user presses the pause button, or if
// they unplug the active gamepad. This requires us to keep track of
// whether a gamepad was ever plugged in, because we don't want to pause
// on PC if they are playing with a keyboard and have no gamepad at all!
bool gamePadDisconnected = !gamePadState.IsConnected &&
input.GamePadWasConnected[playerIndex];
if (input.IsPauseGame(ControllingPlayer) || gamePadDisconnected)
{
ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer);
}
else
{
// Otherwise move the player position.
Vector2 movement = Vector2.Zero;
if (keyboardState.IsKeyDown(Keys.Left))
movement.X--;
if (keyboardState.IsKeyDown(Keys.Right))
movement.X++;
if (keyboardState.IsKeyDown(Keys.Up))
movement.Y--;
if (keyboardState.IsKeyDown(Keys.Down))
movement.Y++;
Vector2 thumbstick = gamePadState.ThumbSticks.Left;
movement.X += thumbstick.X;
movement.Y -= thumbstick.Y;
if (movement.Length() > 1)
movement.Normalize();
playerPosition += movement * 2;
}
}
/// <summary>
/// Draws the gameplay screen.
/// </summary>
public override void Draw(GameTime gameTime)
{
// This game has a blue background. Why? Because!
ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
Color.CornflowerBlue, 0, 0);
// Our player and enemy are both actually just text strings.
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
spriteBatch.Begin();
spriteBatch.DrawString(gameFont, "// TODO", playerPosition, Color.Green);
spriteBatch.DrawString(gameFont, "Insert Gameplay Here",
enemyPosition, Color.DarkRed);
spriteBatch.End();
// If the game is transitioning on or off, fade it out to black.
if (TransitionPosition > 0 || pauseAlpha > 0)
{
float alpha = MathHelper.Lerp(1f - TransitionAlpha, 1f, pauseAlpha / 2);
ScreenManager.FadeBackBufferToBlack(alpha);
}
}
#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.
*/
// $Id: DocumentBuilderFactory.java 884950 2009-11-27 18:46:18Z mrglavas $
using System;
using java = biz.ritter.javapi;
using javax = biz.ritter.javapix;
namespace biz.ritter.javapix.xml.parsers
{
/**
* Defines a factory API that enables applications to obtain a
* parser that produces DOM object trees from XML documents.
*
* @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version $Revision: 884950 $, $Date: 2009-11-27 13:46:18 -0500 (Fri, 27 Nov 2009) $
*/
public abstract class DocumentBuilderFactory
{
private bool validating = false;
private bool namespaceAware = false;
private bool whitespace = false;
private bool expandEntityRef = true;
private bool ignoreComments = false;
private bool coalescing = false;
protected DocumentBuilderFactory ()
{
}
/**
* Obtain a new instance of a
* <code>DocumentBuilderFactory</code>. This static method creates
* a new factory instance.
* This method uses the following ordered lookup procedure to determine
* the <code>DocumentBuilderFactory</code> implementation class to
* load:
* <ul>
* <li>
* Use the <code>javax.xml.parsers.DocumentBuilderFactory</code> system
* property.
* </li>
* <li>
* Use the properties file "lib/jaxp.properties" in the JRE directory.
* This configuration file is in standard <code>java.util.Properties
* </code> format and contains the fully qualified name of the
* implementation class with the key being the system property defined
* above.
*
* The jaxp.properties file is read only once by the JAXP implementation
* and it's values are then cached for future use. If the file does not exist
* when the first attempt is made to read from it, no further attempts are
* made to check for its existence. It is not possible to change the value
* of any property in jaxp.properties after it has been read for the first time.
* </li>
* <li>
* Use the Services API (as detailed in the JAR specification), if
* available, to determine the classname. The Services API will look
* for a classname in the file
* <code>META-INF/services/javax.xml.parsers.DocumentBuilderFactory</code>
* in jars available to the runtime.
* </li>
* <li>
* Platform default <code>DocumentBuilderFactory</code> instance.
* </li>
* </ul>
*
* Once an application has obtained a reference to a
* <code>DocumentBuilderFactory</code> it can use the factory to
* configure and obtain parser instances.
*
*
* <h2>Tip for Trouble-shooting</h2>
* <p>Setting the <code>jaxp.debug</code> system property will cause
* this method to print a lot of debug messages
* to <tt>System.err</tt> about what it is doing and where it is looking at.</p>
*
* <p> If you have problems loading {@link DocumentBuilder}s, try:</p>
* <pre>
* java -Djaxp.debug=1 YourProgram ....
* </pre>
*
* @return New instance of a <code>DocumentBuilderFactory</code>
*
* @exception FactoryConfigurationError if the implementation is not
* available or cannot be instantiated.
*/
public static DocumentBuilderFactory newInstance ()
{
try {
return (DocumentBuilderFactory)FactoryFinder.find (
/* The default property name according to the JAXP spec */
"javax.xml.parsers.DocumentBuilderFactory",
/* The fallback implementation class name */
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
} catch (FactoryFinder.ConfigurationError e) {
throw new FactoryConfigurationError (e.getException (), e.getMessage ());
}
}
/**
* @return New instance of a <code>DocumentBuilderFactory</code>
*
* @exception FactoryConfigurationError if the implementation is not
* available or cannot be instantiated.
*/
public static DocumentBuilderFactory newInstance (String factoryClassName,
java.lang.ClassLoader classLoader)
{
if (factoryClassName == null) {
throw new FactoryConfigurationError ("factoryClassName cannot be null.");
}
if (classLoader == null) {
classLoader = SecuritySupport.getContextClassLoader ();
}
try {
return (DocumentBuilderFactory)FactoryFinder.newInstance (factoryClassName, classLoader, false);
} catch (FactoryFinder.ConfigurationError e) {
throw new FactoryConfigurationError (e.getException (), e.getMessage ());
}
}
/**
* Creates a new instance of a {@link javax.xml.parsers.DocumentBuilder}
* using the currently configured parameters.
*
* @exception ParserConfigurationException if a DocumentBuilder
* cannot be created which satisfies the configuration requested.
* @return A new instance of a DocumentBuilder.
*/
public abstract DocumentBuilder newDocumentBuilder ();
//throws ParserConfigurationException;
/**
* Specifies that the parser produced by this code will
* provide support for XML namespaces. By default the value of this is set
* to <code>false</code>
*
* @param awareness true if the parser produced will provide support
* for XML namespaces; false otherwise.
*/
public void setNamespaceAware (bool awareness)
{
this.namespaceAware = awareness;
}
/**
* Specifies that the parser produced by this code will
* validate documents as they are parsed. By default the value of this
* is set to <code>false</code>.
*
* <p>
* Note that "the validation" here means
* <a href="http://www.w3.org/TR/REC-xml#proc-types">a validating
* parser</a> as defined in the XML recommendation.
* In other words, it essentially just controls the DTD validation.
* (except the legacy two properties defined in JAXP 1.2.
* See <a href="#validationCompatibility">here</a> for more details.)
* </p>
*
* <p>
* To use modern schema languages such as W3C XML Schema or
* RELAX NG instead of DTD, you can configure your parser to be
* a non-validating parser by leaving the {@link #setValidating(boolean)}
* method <tt>false</tt>, then use the {@link #setSchema(Schema)}
* method to associate a schema to a parser.
* </p>
*
* @param validating true if the parser produced will validate documents
* as they are parsed; false otherwise.
*/
public void setValidating (bool validating)
{
this.validating = validating;
}
/**
* Specifies that the parsers created by this factory must eliminate
* whitespace in element content (sometimes known loosely as
* 'ignorable whitespace') when parsing XML documents (see XML Rec
* 2.10). Note that only whitespace which is directly contained within
* element content that has an element only content model (see XML
* Rec 3.2.1) will be eliminated. Due to reliance on the content model
* this setting requires the parser to be in validating mode. By default
* the value of this is set to <code>false</code>.
*
* @param whitespace true if the parser created must eliminate whitespace
* in the element content when parsing XML documents;
* false otherwise.
*/
public void setIgnoringElementContentWhitespace (bool whitespace)
{
this.whitespace = whitespace;
}
/**
* Specifies that the parser produced by this code will
* expand entity reference nodes. By default the value of this is set to
* <code>true</code>
*
* @param expandEntityRef true if the parser produced will expand entity
* reference nodes; false otherwise.
*/
public void setExpandEntityReferences (bool expandEntityRef)
{
this.expandEntityRef = expandEntityRef;
}
/**
* <p>Specifies that the parser produced by this code will
* ignore comments. By default the value of this is set to <code>false
* </code>.</p>
*
* @param ignoreComments <code>boolean</code> value to ignore comments during processing
*/
public void setIgnoringComments (bool ignoreComments)
{
this.ignoreComments = ignoreComments;
}
/**
* Specifies that the parser produced by this code will
* convert CDATA nodes to Text nodes and append it to the
* adjacent (if any) text node. By default the value of this is set to
* <code>false</code>
*
* @param coalescing true if the parser produced will convert CDATA nodes
* to Text nodes and append it to the adjacent (if any)
* text node; false otherwise.
*/
public void setCoalescing (bool coalescing)
{
this.coalescing = coalescing;
}
/**
* Indicates whether or not the factory is configured to produce
* parsers which are namespace aware.
*
* @return true if the factory is configured to produce parsers which
* are namespace aware; false otherwise.
*/
public bool isNamespaceAware ()
{
return namespaceAware;
}
/**
* Indicates whether or not the factory is configured to produce
* parsers which validate the XML content during parse.
*
* @return true if the factory is configured to produce parsers
* which validate the XML content during parse; false otherwise.
*/
public bool isValidating ()
{
return validating;
}
/**
* Indicates whether or not the factory is configured to produce
* parsers which ignore ignorable whitespace in element content.
*
* @return true if the factory is configured to produce parsers
* which ignore ignorable whitespace in element content;
* false otherwise.
*/
public bool isIgnoringElementContentWhitespace ()
{
return whitespace;
}
/**
* Indicates whether or not the factory is configured to produce
* parsers which expand entity reference nodes.
*
* @return true if the factory is configured to produce parsers
* which expand entity reference nodes; false otherwise.
*/
public bool isExpandEntityReferences ()
{
return expandEntityRef;
}
/**
* Indicates whether or not the factory is configured to produce
* parsers which ignores comments.
*
* @return true if the factory is configured to produce parsers
* which ignores comments; false otherwise.
*/
public bool isIgnoringComments ()
{
return ignoreComments;
}
/**
* Indicates whether or not the factory is configured to produce
* parsers which converts CDATA nodes to Text nodes and appends it to
* the adjacent (if any) Text node.
*
* @return true if the factory is configured to produce parsers
* which converts CDATA nodes to Text nodes and appends it to
* the adjacent (if any) Text node; false otherwise.
*/
public bool isCoalescing ()
{
return coalescing;
}
/**
* Allows the user to set specific attributes on the underlying
* implementation.
* @param name The name of the attribute.
* @param value The value of the attribute.
* @exception IllegalArgumentException thrown if the underlying
* implementation doesn't recognize the attribute.
*/
public abstract void setAttribute (String name, Object value);
// throws IllegalArgumentException;
/**
* Allows the user to retrieve specific attributes on the underlying
* implementation.
* @param name The name of the attribute.
* @return value The value of the attribute.
* @exception IllegalArgumentException thrown if the underlying
* implementation doesn't recognize the attribute.
*/
public abstract Object getAttribute (String name);
//throws IllegalArgumentException;
/**
* <p>Set a feature for this <code>DocumentBuilderFactory</code> and <code>DocumentBuilder</code>s created by this factory.</p>
*
* <p>
* Feature names are fully qualified {@link java.net.URI}s.
* Implementations may define their own features.
* An {@link ParserConfigurationException} is thrown if this <code>DocumentBuilderFactory</code> or the
* <code>DocumentBuilder</code>s it creates cannot support the feature.
* It is possible for an <code>DocumentBuilderFactory</code> to expose a feature value but be unable to change its state.
* </p>
*
* <p>
* All implementations are required to support the {@link javax.xml.XMLConstants#FEATURE_SECURE_PROCESSING} feature.
* When the feature is:</p>
* <ul>
* <li>
* <code>true</code>: the implementation will limit XML processing to conform to implementation limits.
* Examples include entity expansion limits and XML Schema constructs that would consume large amounts of resources.
* If XML processing is limited for security reasons, it will be reported via a call to the registered
* {@link org.xml.sax.ErrorHandler#fatalError(SAXParseException exception)}.
* See {@link DocumentBuilder#setErrorHandler(org.xml.sax.ErrorHandler errorHandler)}.
* </li>
* <li>
* <code>false</code>: the implementation will processing XML according to the XML specifications without
* regard to possible implementation limits.
* </li>
* </ul>
*
* @param name Feature name.
* @param value Is feature state <code>true</code> or <code>false</code>.
*
* @throws ParserConfigurationException if this <code>DocumentBuilderFactory</code> or the <code>DocumentBuilder</code>s
* it creates cannot support this feature.
* @throws NullPointerException If the <code>name</code> parameter is null.
*/
public abstract void setFeature (String name, bool value);
//throws ParserConfigurationException;
/**
* <p>Get the state of the named feature.</p>
*
* <p>
* Feature names are fully qualified {@link java.net.URI}s.
* Implementations may define their own features.
* An {@link ParserConfigurationException} is thrown if this <code>DocumentBuilderFactory</code> or the
* <code>DocumentBuilder</code>s it creates cannot support the feature.
* It is possible for an <code>DocumentBuilderFactory</code> to expose a feature value but be unable to change its state.
* </p>
*
* @param name Feature name.
*
* @return State of the named feature.
*
* @throws ParserConfigurationException if this <code>DocumentBuilderFactory</code>
* or the <code>DocumentBuilder</code>s it creates cannot support this feature.
*/
public abstract bool getFeature (String name);
//throws ParserConfigurationException;
/**
* Gets the {@link Schema} object specified through
* the {@link #setSchema(Schema schema)} method.
*
*
* @throws UnsupportedOperationException
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @return
* the {@link Schema} object that was last set through
* the {@link #setSchema(Schema)} method, or null
* if the method was not invoked since a {@link DocumentBuilderFactory}
* is created.
*
* @since 1.5
*/
public javax.xml.validation.Schema getSchema ()
{
throw new java.lang.UnsupportedOperationException (
"This parser does not support specification \""
+ this.getClass ().getPackage ().getSpecificationTitle ()
+ "\" version \""
+ this.getClass ().getPackage ().getSpecificationVersion ()
+ "\""
);
}
/**
* <p/>Set the {@link Schema} to be used by parsers created
* from this factory.
*
* <p/>
* When a {@link Schema} is non-null, a parser will use a validator
* created from it to validate documents before it passes information
* down to the application.
*
* <p/>When errors are found by the validator, the parser is responsible
* to report them to the user-specified {@link org.xml.sax.ErrorHandler}
* (or if the error handler is not set, ignore them or throw them), just
* like any other errors found by the parser itself.
* In other words, if the user-specified {@link org.xml.sax.ErrorHandler}
* is set, it must receive those errors, and if not, they must be
* treated according to the implementation specific
* default error handling rules.
*
* <p/>
* A validator may modify the outcome of a parse (for example by
* adding default values that were missing in documents), and a parser
* is responsible to make sure that the application will receive
* modified DOM trees.
*
* <p/>
* Initially, null is set as the {@link Schema}.
*
* <p/>
* This processing will take effect even if
* the {@link #isValidating()} method returns <tt>false</tt>.
*
* <p>It is an error to use
* the <code>http://java.sun.com/xml/jaxp/properties/schemaSource</code>
* property and/or the <code>http://java.sun.com/xml/jaxp/properties/schemaLanguage</code>
* property in conjunction with a {@link Schema} object.
* Such configuration will cause a {@link ParserConfigurationException}
* exception when the {@link #newDocumentBuilder()} is invoked.</p>
*
*
* <h4>Note for implementors</h4>
* <p/>
* A parser must be able to work with any {@link Schema}
* implementation. However, parsers and schemas are allowed
* to use implementation-specific custom mechanisms
* as long as they yield the result described in the specification.
*
* @param schema <code>Schema</code> to use or <code>null</code> to remove a schema.
*
* @throws UnsupportedOperationException
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @since 1.5
*/
public void setSchema (javax.xml.validation.Schema schema)
{
throw new java.lang.UnsupportedOperationException (
"This parser does not support specification \""
+ this.getClass ().getPackage ().getSpecificationTitle ()
+ "\" version \""
+ this.getClass ().getPackage ().getSpecificationVersion ()
+ "\""
);
}
/**
* <p>Set state of XInclude processing.</p>
*
* <p>If XInclude markup is found in the document instance, should it be
* processed as specified in <a href="http://www.w3.org/TR/xinclude/">
* XML Inclusions (XInclude) Version 1.0</a>.</p>
*
* <p>XInclude processing defaults to <code>false</code>.</p>
*
* @param state Set XInclude processing to <code>true</code> or
* <code>false</code>
*
* @throws UnsupportedOperationException
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @since 1.5
*/
public void setXIncludeAware (bool state)
{
throw new java.lang.UnsupportedOperationException (
"This parser does not support specification \""
+ this.getClass ().getPackage ().getSpecificationTitle ()
+ "\" version \""
+ this.getClass ().getPackage ().getSpecificationVersion ()
+ "\""
);
}
/**
* <p>Get state of XInclude processing.</p>
*
* @return current state of XInclude processing
*
* @throws UnsupportedOperationException
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @since 1.5
*/
public bool isXIncludeAware ()
{
throw new java.lang.UnsupportedOperationException (
"This parser does not support specification \""
+ this.getClass ().getPackage ().getSpecificationTitle ()
+ "\" version \""
+ this.getClass ().getPackage ().getSpecificationVersion ()
+ "\""
);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Collections.Generic;
// TODO when we upgrade to C# V6 you can remove this.
// warning CS0420: 'P.x': a reference to a volatile field will not be treated as volatile
// This happens when you pass a _subcribers (a volatile field) to interlocked operations (which are byref).
// This was fixed in C# V6.
#pragma warning disable 0420
namespace System.Diagnostics
{
/// <summary>
/// A DiagnosticListener is something that forwards on events written with DiagnosticSource.
/// It is an IObservable (has Subscribe method), and it also has a Subscribe overloads that
/// lets you specify a 'IsEnabled' predicate that users of DiagnosticSource will use for
/// 'quick checks'.
///
/// The item in the stream is a KeyValuePair[string, object] where the string is the name
/// of the diagnostic item and the object is the payload (typically an anonymous type).
///
/// There may be many DiagnosticListeners in the system, but we encourage the use of
/// The DiagnosticSource.DefaultSource which goes to the DiagnosticListener.DefaultListener.
///
/// If you need to see 'everything' you can subscribe to the 'AllListeners' event that
/// will fire for every live DiagnosticListener in the appdomain (past or present).
///
/// Please See the DiagnosticSource Users Guide
/// https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/DiagnosticSourceUsersGuide.md
/// for instructions on its use.
/// </summary>
public class DiagnosticListener : DiagnosticSource, IObservable<KeyValuePair<string, object>>, IDisposable
{
/// <summary>
/// When you subscribe to this you get callbacks for all NotificationListeners in the appdomain
/// as well as those that occurred in the past, and all future Listeners created in the future.
/// </summary>
public static IObservable<DiagnosticListener> AllListeners
{
get
{
#if ENABLE_HTTP_HANDLER
GC.KeepAlive(HttpHandlerDiagnosticListener.s_instance);
#endif
if (s_allListenerObservable == null)
{
s_allListenerObservable = new AllListenerObservable();
}
return s_allListenerObservable;
}
}
// Subscription implementation
/// <summary>
/// Add a subscriber (Observer). If 'IsEnabled' == null (or not present), then the Source's IsEnabled
/// will always return true.
/// </summary>
public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer, Predicate<string> isEnabled)
{
IDisposable subscription;
if (isEnabled == null)
{
subscription = SubscribeInternal(observer, null, null);
}
else
{
Predicate<string> localIsEnabled = isEnabled;
subscription = SubscribeInternal(observer, isEnabled, (name, arg1, arg2) => localIsEnabled(name));
}
return subscription;
}
/// <summary>
/// Add a subscriber (Observer). If 'IsEnabled' == null (or not present), then the Source's IsEnabled
/// will always return true.
/// </summary>
/// <param name="observer">Subscriber (IObserver)</param>
/// <param name="isEnabled">Filters events based on their name (string) and context objects that could be null.
/// Note that producer may first call filter with event name only and null context arguments and filter should
/// return true if consumer is interested in any of such events. Producers that support
/// context-based filtering will invoke isEnabled again with context for more prcise filtering.
/// Use Subscribe overload with name-based filtering if producer does NOT support context-based filtering</param>
public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer, Func<string, object, object, bool> isEnabled)
{
return isEnabled == null ?
SubscribeInternal(observer, null, null) :
SubscribeInternal(observer, name => IsEnabled(name, null, null), isEnabled);
}
/// <summary>
/// Same as other Subscribe overload where the predicate is assumed to always return true.
/// </summary>
public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer)
{
return SubscribeInternal(observer, null, null);
}
/// <summary>
/// Make a new DiagnosticListener, it is a NotificationSource, which means the returned result can be used to
/// log notifications, but it also has a Subscribe method so notifications can be forwarded
/// arbitrarily. Thus its job is to forward things from the producer to all the listeners
/// (multi-casting). Generally you should not be making your own DiagnosticListener but use the
/// DiagnosticListener.Default, so that notifications are as 'public' as possible.
/// </summary>
public DiagnosticListener(string name)
{
Name = name;
// Insert myself into the list of all Listeners.
lock (s_lock)
{
// Issue the callback for this new diagnostic listener.
var allListenerObservable = s_allListenerObservable;
if (allListenerObservable != null)
allListenerObservable.OnNewDiagnosticListener(this);
// And add it to the list of all past listeners.
_next = s_allListeners;
s_allListeners = this;
}
// Touch DiagnosticSourceEventSource.Logger so we ensure that the
// DiagnosticSourceEventSource has been constructed (and thus is responsive to ETW requests to be enabled).
GC.KeepAlive(DiagnosticSourceEventSource.Logger);
}
/// <summary>
/// Clean up the NotificationListeners. Notification listeners do NOT DIE ON THEIR OWN
/// because they are in a global list (for discoverability). You must dispose them explicitly.
/// Note that we do not do the Dispose(bool) pattern because we frankly don't want to support
/// subclasses that have non-managed state.
/// </summary>
virtual public void Dispose()
{
// Remove myself from the list of all listeners.
lock (s_lock)
{
if (_disposed)
{
return;
}
_disposed = true;
if (s_allListeners == this)
s_allListeners = s_allListeners._next;
else
{
var cur = s_allListeners;
while (cur != null)
{
if (cur._next == this)
{
cur._next = _next;
break;
}
cur = cur._next;
}
}
_next = null;
}
// Indicate completion to all subscribers.
DiagnosticSubscription subscriber = null;
Interlocked.Exchange(ref subscriber, _subscriptions);
while (subscriber != null)
{
subscriber.Observer.OnCompleted();
subscriber = subscriber.Next;
}
// The code above also nulled out all subscriptions.
}
/// <summary>
/// When a DiagnosticListener is created it is given a name. Return this.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Return the name for the ToString() to aid in debugging.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Name;
}
#region private
// NotificationSource implementation
/// <summary>
/// Determines whether there are any registered subscribers
/// </summary>
/// <remarks> If there is an expensive setup for the notification,
/// you may call IsEnabled() as the first and most efficient check before doing this setup.
/// Producers may optionally use this check before IsEnabled(string) in the most performance-critical parts of the system
/// to ensure somebody listens to the DiagnosticListener at all.</remarks>
public bool IsEnabled()
{
return _subscriptions != null;
}
/// <summary>
/// Override abstract method
/// </summary>
public override bool IsEnabled(string name)
{
for (DiagnosticSubscription curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next)
{
if (curSubscription.IsEnabled1Arg == null || curSubscription.IsEnabled1Arg(name))
return true;
}
return false;
}
// NotificationSource implementation
/// <summary>
/// Override abstract method
/// </summary>
public override bool IsEnabled(string name, object arg1, object arg2 = null)
{
for (DiagnosticSubscription curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next)
{
if (curSubscription.IsEnabled3Arg == null || curSubscription.IsEnabled3Arg(name, arg1, arg2))
return true;
}
return false;
}
/// <summary>
/// Override abstract method
/// </summary>
public override void Write(string name, object value)
{
for (DiagnosticSubscription curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next)
curSubscription.Observer.OnNext(new KeyValuePair<string, object>(name, value));
}
// Note that Subscriptions are READ ONLY. This means you never update any fields (even on removal!)
private class DiagnosticSubscription : IDisposable
{
internal IObserver<KeyValuePair<string, object>> Observer;
// IsEnabled1Arg and IsEnabled3Arg represent IsEnabled callbacks.
// - IsEnabled1Arg invoked for DiagnosticSource.IsEnabled(string)
// - IsEnabled3Arg invoked for DiagnosticSource.IsEnabled(string, obj, obj)
// Subscriber MUST set both IsEnabled1Arg and IsEnabled3Arg or none of them:
// when Predicate<string> is provided in DiagosticListener.Subscribe,
// - IsEnabled1Arg is set to predicate
// - IsEnabled3Arg falls back to predicate ignoring extra arguments.
// similarly, when Func<string, obj, obj, bool> is provided,
// IsEnabled1Arg falls back to IsEnabled3Arg with null context
// Thus, dispatching is very efficient when producer and consumer agree on number of IsEnabled arguments
// Argument number mismatch between producer/consumer adds extra cost of adding or omitting context parameters
internal Predicate<string> IsEnabled1Arg;
internal Func<string, object, object, bool> IsEnabled3Arg;
internal DiagnosticListener Owner; // The DiagnosticListener this is a subscription for.
internal DiagnosticSubscription Next; // Linked list of subscribers
public void Dispose()
{
// TO keep this lock free and easy to analyze, the linked list is READ ONLY. Thus we copy
for (;;)
{
DiagnosticSubscription subscriptions = Owner._subscriptions;
DiagnosticSubscription newSubscriptions = Remove(subscriptions, this); // Make a new list, with myself removed.
// try to update, but if someone beat us to it, then retry.
if (Interlocked.CompareExchange(ref Owner._subscriptions, newSubscriptions, subscriptions) == subscriptions)
{
#if DEBUG
var cur = newSubscriptions;
while (cur != null)
{
Debug.Assert(!(cur.Observer == Observer && cur.IsEnabled1Arg == IsEnabled1Arg && cur.IsEnabled3Arg == IsEnabled3Arg), "Did not remove subscription!");
cur = cur.Next;
}
#endif
break;
}
}
}
// Create a new linked list where 'subscription has been removed from the linked list of 'subscriptions'.
private static DiagnosticSubscription Remove(DiagnosticSubscription subscriptions, DiagnosticSubscription subscription)
{
if (subscriptions == null)
{
// May happen if the IDisposable returned from Subscribe is Dispose'd again
return null;
}
if (subscriptions.Observer == subscription.Observer &&
subscriptions.IsEnabled1Arg == subscription.IsEnabled1Arg &&
subscriptions.IsEnabled3Arg == subscription.IsEnabled3Arg)
return subscriptions.Next;
#if DEBUG
// Delay a bit. This makes it more likely that races will happen.
for (int i = 0; i < 100; i++)
GC.KeepAlive("");
#endif
return new DiagnosticSubscription() { Observer = subscriptions.Observer, Owner = subscriptions.Owner, IsEnabled1Arg = subscriptions.IsEnabled1Arg, IsEnabled3Arg = subscriptions.IsEnabled3Arg, Next = Remove(subscriptions.Next, subscription) };
}
}
#region AllListenerObservable
/// <summary>
/// Logically AllListenerObservable has a very simple task. It has a linked list of subscribers that want
/// a callback when a new listener gets created. When a new DiagnosticListener gets created it should call
/// OnNewDiagnosticListener so that AllListenerObservable can forward it on to all the subscribers.
/// </summary>
private class AllListenerObservable : IObservable<DiagnosticListener>
{
public IDisposable Subscribe(IObserver<DiagnosticListener> observer)
{
lock (s_lock)
{
// Call back for each existing listener on the new callback (catch-up).
for (DiagnosticListener cur = s_allListeners; cur != null; cur = cur._next)
observer.OnNext(cur);
// Add the observer to the list of subscribers.
_subscriptions = new AllListenerSubscription(this, observer, _subscriptions);
return _subscriptions;
}
}
/// <summary>
/// Called when a new DiagnosticListener gets created to tell anyone who subscribed that this happened.
/// </summary>
/// <param name="diagnosticListener"></param>
internal void OnNewDiagnosticListener(DiagnosticListener diagnosticListener)
{
Debug.Assert(Monitor.IsEntered(s_lock)); // We should only be called when we hold this lock
// Simply send a callback to every subscriber that we have a new listener
for (var cur = _subscriptions; cur != null; cur = cur.Next)
cur.Subscriber.OnNext(diagnosticListener);
}
#region private
/// <summary>
/// Remove 'subscription from the list of subscriptions that the observable has. Called when
/// subscriptions are disposed. Returns true if the subscription was removed.
/// </summary>
private bool Remove(AllListenerSubscription subscription)
{
lock (s_lock)
{
if (_subscriptions == subscription)
{
_subscriptions = subscription.Next;
return true;
}
else if (_subscriptions != null)
{
for (var cur = _subscriptions; cur.Next != null; cur = cur.Next)
{
if (cur.Next == subscription)
{
cur.Next = cur.Next.Next;
return true;
}
}
}
// Subscriber likely disposed multiple times
return false;
}
}
/// <summary>
/// One node in the linked list of subscriptions that AllListenerObservable keeps. It is
/// IDisposable, and when that is called it removes itself from the list.
/// </summary>
internal class AllListenerSubscription : IDisposable
{
internal AllListenerSubscription(AllListenerObservable owner, IObserver<DiagnosticListener> subscriber, AllListenerSubscription next)
{
this._owner = owner;
this.Subscriber = subscriber;
this.Next = next;
}
public void Dispose()
{
if (_owner.Remove(this))
{
Subscriber.OnCompleted(); // Called outside of a lock
}
}
private readonly AllListenerObservable _owner; // the list this is a member of.
internal readonly IObserver<DiagnosticListener> Subscriber;
internal AllListenerSubscription Next;
}
private AllListenerSubscription _subscriptions;
#endregion
}
#endregion
private IDisposable SubscribeInternal(IObserver<KeyValuePair<string, object>> observer, Predicate<string> isEnabled1Arg, Func<string, object, object, bool> isEnabled3Arg)
{
// If we have been disposed, we silently ignore any subscriptions.
if (_disposed)
{
return new DiagnosticSubscription() { Owner = this };
}
DiagnosticSubscription newSubscription = new DiagnosticSubscription()
{
Observer = observer,
IsEnabled1Arg = isEnabled1Arg,
IsEnabled3Arg = isEnabled3Arg,
Owner = this,
Next = _subscriptions
};
while (Interlocked.CompareExchange(ref _subscriptions, newSubscription, newSubscription.Next) != newSubscription.Next)
newSubscription.Next = _subscriptions;
return newSubscription;
}
private volatile DiagnosticSubscription _subscriptions;
private DiagnosticListener _next; // We keep a linked list of all NotificationListeners (s_allListeners)
private bool _disposed; // Has Dispose been called?
private static DiagnosticListener s_allListeners; // linked list of all instances of DiagnosticListeners.
private static AllListenerObservable s_allListenerObservable; // to make callbacks to this object when listeners come into existence.
private static object s_lock = new object(); // A lock for
#if false
private static readonly DiagnosticListener s_default = new DiagnosticListener("DiagnosticListener.DefaultListener");
#endif
#endregion
}
}
| |
/****************************************************************************
Tilde
Copyright (c) 2008 Tantalus Media Pty
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.Text;
namespace Tilde.LuaDebugger
{
public class SendMessageBuffer
{
public SendMessageBuffer(int size)
{
mData = new byte[size];
mPosition = 0;
mMessageStart = 0;
mSizeofObjectID = 0;
mSizeofNumber = 0;
}
public byte [] Data
{
get { return mData; }
}
public int Length
{
get { return mPosition; }
set { mPosition = value; }
}
public int BytesRemaining
{
get { return mData.Length - mPosition; }
}
public int SizeofObjectID
{
get { return mSizeofObjectID; }
set { mSizeofObjectID = value; }
}
public int SizeofNumber
{
get { return mSizeofNumber; }
set { mSizeofNumber = value; }
}
public void Begin()
{
mMessageStart = mPosition;
mPosition += 4;
}
public int End()
{
Write((int)mPosition - mMessageStart, mMessageStart);
return mPosition;
}
public void WriteValue(LuaValue value)
{
Write((int)value.Type);
if (value.Type == LuaValueType.NUMBER)
WriteNumber(value.AsNumber());
else
WriteObjectID(value.Value);
}
public void WriteNumber(double value)
{
switch (mSizeofNumber)
{
case 4: Write((float)value); break;
case 8: Write((double)value); break;
default: throw new ProtocolException(String.Format("Unknown size specified for lua_Number type: {0}", mSizeofNumber));
}
}
public void WriteObjectID(Int64 value)
{
switch (mSizeofObjectID)
{
case 4: Write((Int32)value); break;
case 8: Write((Int64)value); break;
default: throw new ProtocolException(String.Format("Unknown size specified for LuaDebuggerObjectID type: {0}", mSizeofObjectID));
}
}
public void Write(double value)
{
if (BytesRemaining < 8)
throw new ProtocolException("Output buffer overflow");
if (!IsAligned(mPosition, 4))
throw new ProtocolException("Output buffer alignment is not suitable for writing 'double'");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, mPosition, bytes.Length);
mPosition += bytes.Length;
}
public void Write(float value)
{
if (BytesRemaining < 4)
throw new ProtocolException("Output buffer overflow");
if (!IsAligned(mPosition, 4))
throw new ProtocolException("Output buffer alignment is not suitable for writing 'float'");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, mPosition, bytes.Length);
mPosition += bytes.Length;
}
public void Write(Int64 value)
{
if (BytesRemaining < 8)
throw new ProtocolException("Output buffer overflow");
if (!IsAligned(mPosition, 4))
throw new ProtocolException("Output buffer alignment is not suitable for writing 'Int64'");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, mPosition, bytes.Length);
mPosition += bytes.Length;
}
public void Write(int value)
{
if (BytesRemaining < 4)
throw new ProtocolException("Output buffer overflow");
if (!IsAligned(mPosition, 4))
throw new ProtocolException("Output buffer alignment is not suitable for writing 'int'");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, mPosition, bytes.Length);
mPosition += bytes.Length;
}
public void Write(uint value)
{
if (BytesRemaining < 4)
throw new ProtocolException("Output buffer overflow");
if (!IsAligned(mPosition, 4))
throw new ProtocolException("Output buffer alignment is not suitable for writing 'uint'");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, mPosition, bytes.Length);
mPosition += bytes.Length;
}
public void Write(short value)
{
if (BytesRemaining < 2)
throw new ProtocolException("Output buffer overflow");
if (!IsAligned(mPosition, 2))
throw new ProtocolException("Output buffer alignment is not suitable for writing 'short'");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, mPosition, bytes.Length);
mPosition += bytes.Length;
}
public void Write(ushort value)
{
if (BytesRemaining < 2)
throw new ProtocolException("Output buffer overflow");
if (!IsAligned(mPosition, 2))
throw new ProtocolException("Output buffer alignment is not suitable for writing 'ushort'");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, mPosition, bytes.Length);
mPosition += bytes.Length;
}
public void Write(char value)
{
if (BytesRemaining < 1)
throw new ProtocolException("Output buffer overflow");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, mPosition, bytes.Length);
mPosition += bytes.Length;
}
public void Write(byte value)
{
if (BytesRemaining < 1)
throw new ProtocolException("Output buffer overflow");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, mPosition, bytes.Length);
mPosition += bytes.Length;
}
public void Write(string value)
{
Write((int)value.Length);
if (value.Length > 0)
{
char[] chars = value.ToCharArray();
if (BytesRemaining < RoundUp(chars.Length, 4))
throw new ProtocolException("Output buffer overflow");
for (int index = 0; index < chars.Length; ++index)
mData[mPosition + index] = (byte)(chars[index]);
mPosition += RoundUp(chars.Length, 4);
}
}
public void Write(byte [] value)
{
Write((int)value.Length);
if (value.Length > 0)
{
if (BytesRemaining < RoundUp(value.Length, 4))
throw new ProtocolException("Output buffer overflow");
for (int index = 0; index < value.Length; ++index)
mData[mPosition + index] = (byte)(value[index]);
mPosition += RoundUp(value.Length, 4);
}
}
public void Write(int value, int position)
{
if (position < 0 || position > mData.Length - 4)
throw new ProtocolException("Output buffer overflow");
if (!IsAligned(position, 4))
throw new ProtocolException("Output buffer alignment is not suitable for writing 'int'");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, position, bytes.Length);
}
public void Write(uint value, int position)
{
if (position < 0 || position > mData.Length - 4)
throw new ProtocolException("Output buffer overflow");
if (!IsAligned(position, 4))
throw new ProtocolException("Output buffer alignment is not suitable for writing 'uint'");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, position, bytes.Length);
}
public void Write(short value, int position)
{
if (position < 0 || position > mData.Length - 2)
throw new ProtocolException("Output buffer overflow");
if (!IsAligned(position, 2))
throw new ProtocolException("Output buffer alignment is not suitable for writing 'short'");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, position, bytes.Length);
}
public void Write(ushort value, int position)
{
if (position < 0 || position > mData.Length - 2)
throw new ProtocolException("Output buffer overflow");
if (!IsAligned(position, 2))
throw new ProtocolException("Output buffer alignment is not suitable for writing 'ushort'");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, position, bytes.Length);
}
public void Write(char value, int position)
{
if (position < 0 || position > mData.Length - 1)
throw new ProtocolException("Output buffer overflow");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, position, bytes.Length);
}
public void Write(byte value, int position)
{
if (position < 0 || position > mData.Length - 1)
throw new ProtocolException("Output buffer overflow");
byte[] bytes = BitConverter.GetBytes(value);
Array.Copy(bytes, 0, mData, position, bytes.Length);
}
public static bool IsAligned(int value, int align)
{
return value % align == 0;
}
public static int RoundUp(int value, int align)
{
int diff = value % align;
if (diff != 0)
return value + (align - diff);
else
return value;
}
private byte[] mData;
private int mPosition;
private int mMessageStart;
int mSizeofObjectID;
int mSizeofNumber;
}
}
| |
/*
* 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;
namespace Lucene.Net.Demo.Html
{
public class Entities
{
internal static readonly System.Collections.Hashtable decoder = new System.Collections.Hashtable(300);
internal static readonly System.String[] encoder = new System.String[0x100];
internal static System.String Decode(System.String entity)
{
if (entity[entity.Length - 1] == ';')
// remove trailing semicolon
entity = entity.Substring(0, (entity.Length - 1) - (0));
if (entity[1] == '#')
{
int start = 2;
int radix = 10;
if (entity[2] == 'X' || entity[2] == 'x')
{
start++;
radix = 16;
}
System.Char c = (char) System.Convert.ToInt32(entity.Substring(start), radix);
return c.ToString();
}
else
{
System.String s = (System.String) decoder[entity];
if (s != null)
return s;
else
return "";
}
}
public static System.String Encode(System.String s)
{
int length = s.Length;
System.Text.StringBuilder buffer = new System.Text.StringBuilder(length * 2);
for (int i = 0; i < length; i++)
{
char c = s[i];
int j = (int) c;
if (j < 0x100 && encoder[j] != null)
{
buffer.Append(encoder[j]); // have a named encoding
buffer.Append(';');
}
else if (j < 0x80)
{
buffer.Append(c); // use ASCII value
}
else
{
buffer.Append("&#"); // use numeric encoding
buffer.Append((int) c);
buffer.Append(';');
}
}
return buffer.ToString();
}
internal static void Add(System.String entity, int value_Renamed)
{
decoder[entity] = ((char) value_Renamed).ToString();
if (value_Renamed < 0x100)
encoder[value_Renamed] = entity;
}
static Entities()
{
{
Add(" ", 160);
Add("¡", 161);
Add("¢", 162);
Add("£", 163);
Add("¤", 164);
Add("¥", 165);
Add("¦", 166);
Add("§", 167);
Add("¨", 168);
Add("©", 169);
Add("ª", 170);
Add("«", 171);
Add("¬", 172);
Add("­", 173);
Add("®", 174);
Add("¯", 175);
Add("°", 176);
Add("±", 177);
Add("²", 178);
Add("³", 179);
Add("´", 180);
Add("µ", 181);
Add("¶", 182);
Add("·", 183);
Add("¸", 184);
Add("¹", 185);
Add("º", 186);
Add("»", 187);
Add("¼", 188);
Add("½", 189);
Add("¾", 190);
Add("¿", 191);
Add("À", 192);
Add("Á", 193);
Add("Â", 194);
Add("Ã", 195);
Add("Ä", 196);
Add("Å", 197);
Add("Æ", 198);
Add("Ç", 199);
Add("È", 200);
Add("É", 201);
Add("Ê", 202);
Add("Ë", 203);
Add("Ì", 204);
Add("Í", 205);
Add("Î", 206);
Add("Ï", 207);
Add("Ð", 208);
Add("Ñ", 209);
Add("Ò", 210);
Add("Ó", 211);
Add("Ô", 212);
Add("Õ", 213);
Add("Ö", 214);
Add("×", 215);
Add("Ø", 216);
Add("Ù", 217);
Add("Ú", 218);
Add("Û", 219);
Add("Ü", 220);
Add("Ý", 221);
Add("Þ", 222);
Add("ß", 223);
Add("à", 224);
Add("á", 225);
Add("â", 226);
Add("ã", 227);
Add("ä", 228);
Add("å", 229);
Add("æ", 230);
Add("ç", 231);
Add("è", 232);
Add("é", 233);
Add("ê", 234);
Add("ë", 235);
Add("ì", 236);
Add("í", 237);
Add("î", 238);
Add("ï", 239);
Add("ð", 240);
Add("ñ", 241);
Add("ò", 242);
Add("ó", 243);
Add("ô", 244);
Add("õ", 245);
Add("ö", 246);
Add("÷", 247);
Add("ø", 248);
Add("ù", 249);
Add("ú", 250);
Add("û", 251);
Add("ü", 252);
Add("ý", 253);
Add("þ", 254);
Add("ÿ", 255);
Add("&fnof", 402);
Add("&Alpha", 913);
Add("&Beta", 914);
Add("&Gamma", 915);
Add("&Delta", 916);
Add("&Epsilon", 917);
Add("&Zeta", 918);
Add("&Eta", 919);
Add("&Theta", 920);
Add("&Iota", 921);
Add("&Kappa", 922);
Add("&Lambda", 923);
Add("&Mu", 924);
Add("&Nu", 925);
Add("&Xi", 926);
Add("&Omicron", 927);
Add("&Pi", 928);
Add("&Rho", 929);
Add("&Sigma", 931);
Add("&Tau", 932);
Add("&Upsilon", 933);
Add("&Phi", 934);
Add("&Chi", 935);
Add("&Psi", 936);
Add("&Omega", 937);
Add("&alpha", 945);
Add("&beta", 946);
Add("&gamma", 947);
Add("&delta", 948);
Add("&epsilon", 949);
Add("&zeta", 950);
Add("&eta", 951);
Add("&theta", 952);
Add("&iota", 953);
Add("&kappa", 954);
Add("&lambda", 955);
Add("&mu", 956);
Add("&nu", 957);
Add("&xi", 958);
Add("&omicron", 959);
Add("&pi", 960);
Add("&rho", 961);
Add("&sigmaf", 962);
Add("&sigma", 963);
Add("&tau", 964);
Add("&upsilon", 965);
Add("&phi", 966);
Add("&chi", 967);
Add("&psi", 968);
Add("&omega", 969);
Add("&thetasym", 977);
Add("&upsih", 978);
Add("&piv", 982);
Add("&bull", 8226);
Add("&hellip", 8230);
Add("&prime", 8242);
Add("&Prime", 8243);
Add("&oline", 8254);
Add("&frasl", 8260);
Add("&weierp", 8472);
Add("&image", 8465);
Add("&real", 8476);
Add("&trade", 8482);
Add("&alefsym", 8501);
Add("&larr", 8592);
Add("&uarr", 8593);
Add("&rarr", 8594);
Add("&darr", 8595);
Add("&harr", 8596);
Add("&crarr", 8629);
Add("&lArr", 8656);
Add("&uArr", 8657);
Add("&rArr", 8658);
Add("&dArr", 8659);
Add("&hArr", 8660);
Add("&forall", 8704);
Add("&part", 8706);
Add("&exist", 8707);
Add("&empty", 8709);
Add("&nabla", 8711);
Add("&isin", 8712);
Add("¬in", 8713);
Add("&ni", 8715);
Add("&prod", 8719);
Add("&sum", 8721);
Add("&minus", 8722);
Add("&lowast", 8727);
Add("&radic", 8730);
Add("&prop", 8733);
Add("&infin", 8734);
Add("&ang", 8736);
Add("&and", 8743);
Add("&or", 8744);
Add("&cap", 8745);
Add("&cup", 8746);
Add("&int", 8747);
Add("&there4", 8756);
Add("&sim", 8764);
Add("&cong", 8773);
Add("&asymp", 8776);
Add("&ne", 8800);
Add("&equiv", 8801);
Add("&le", 8804);
Add("&ge", 8805);
Add("&sub", 8834);
Add("&sup", 8835);
Add("&nsub", 8836);
Add("&sube", 8838);
Add("&supe", 8839);
Add("&oplus", 8853);
Add("&otimes", 8855);
Add("&perp", 8869);
Add("&sdot", 8901);
Add("&lceil", 8968);
Add("&rceil", 8969);
Add("&lfloor", 8970);
Add("&rfloor", 8971);
Add("&lang", 9001);
Add("&rang", 9002);
Add("&loz", 9674);
Add("&spades", 9824);
Add("&clubs", 9827);
Add("&hearts", 9829);
Add("&diams", 9830);
Add(""", 34);
Add("&", 38);
Add("<", 60);
Add(">", 62);
Add("&OElig", 338);
Add("&oelig", 339);
Add("&Scaron", 352);
Add("&scaron", 353);
Add("&Yuml", 376);
Add("&circ", 710);
Add("&tilde", 732);
Add("&ensp", 8194);
Add("&emsp", 8195);
Add("&thinsp", 8201);
Add("&zwnj", 8204);
Add("&zwj", 8205);
Add("&lrm", 8206);
Add("&rlm", 8207);
Add("&ndash", 8211);
Add("&mdash", 8212);
Add("&lsquo", 8216);
Add("&rsquo", 8217);
Add("&sbquo", 8218);
Add("&ldquo", 8220);
Add("&rdquo", 8221);
Add("&bdquo", 8222);
Add("&dagger", 8224);
Add("&Dagger", 8225);
Add("&permil", 8240);
Add("&lsaquo", 8249);
Add("&rsaquo", 8250);
Add("&euro", 8364);
}
}
}
}
| |
/*
* 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.IO;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI40;
using NUnit.Framework;
namespace Net.Pkcs11Interop.Tests.LowLevelAPI40
{
/// <summary>
/// C_SignEncryptUpdate and C_DecryptVerifyUpdate tests.
/// </summary>
[TestFixture()]
public class _24_SignEncryptAndDecryptVerifyTest
{
/// <summary>
/// Basic C_SignEncryptUpdate and C_DecryptVerifyUpdate test.
/// </summary>
[Test()]
public void _01_BasicSignEncryptAndDecryptVerifyTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
CKR rv = CKR.CKR_OK;
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
{
rv = pkcs11.C_Initialize(Settings.InitArgs40);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
uint slotId = Helpers.GetUsableSlot(pkcs11);
uint session = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate asymetric key pair
uint pubKeyId = CK.CK_INVALID_HANDLE;
uint privKeyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKeyPair(pkcs11, session, ref pubKeyId, ref privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify signing mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM signingMechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA1_RSA_PKCS);
// Generate symetric key
uint keyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKey(pkcs11, session, ref keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate random initialization vector
byte[] iv = new byte[8];
rv = pkcs11.C_GenerateRandom(session, iv, Convert.ToUInt32(iv.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify encryption mechanism with initialization vector as parameter.
// Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory.
CK_MECHANISM encryptionMechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv);
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Passw0rd");
byte[] signature = null;
byte[] encryptedData = null;
byte[] decryptedData = null;
// Multipart signing and encryption function C_SignEncryptUpdate can be used i.e. for signing and encryption of streamed data
using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream())
{
// Initialize signing operation
rv = pkcs11.C_SignInit(session, ref signingMechanism, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Initialize encryption operation
rv = pkcs11.C_EncryptInit(session, ref encryptionMechanism, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for source data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
// Prepare buffer for encrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] encryptedPart = new byte[8];
uint encryptedPartLen = Convert.ToUInt32(encryptedPart.Length);
// Read input stream with source data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0)
{
// Process each individual source data part
encryptedPartLen = Convert.ToUInt32(encryptedPart.Length);
rv = pkcs11.C_SignEncryptUpdate(session, part, Convert.ToUInt32(bytesRead), encryptedPart, ref encryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append encrypted data part to the output stream
outputStream.Write(encryptedPart, 0, Convert.ToInt32(encryptedPartLen));
}
// Get the length of signature in first call
uint signatureLen = 0;
rv = pkcs11.C_SignFinal(session, null, ref signatureLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(signatureLen > 0);
// Allocate array for signature
signature = new byte[signatureLen];
// Get signature in second call
rv = pkcs11.C_SignFinal(session, signature, ref signatureLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Get the length of last encrypted data part in first call
byte[] lastEncryptedPart = null;
uint lastEncryptedPartLen = 0;
rv = pkcs11.C_EncryptFinal(session, null, ref lastEncryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Allocate array for the last encrypted data part
lastEncryptedPart = new byte[lastEncryptedPartLen];
// Get the last encrypted data part in second call
rv = pkcs11.C_EncryptFinal(session, lastEncryptedPart, ref lastEncryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append the last encrypted data part to the output stream
outputStream.Write(lastEncryptedPart, 0, Convert.ToInt32(lastEncryptedPartLen));
// Read whole output stream to the byte array so we can compare results more easily
encryptedData = outputStream.ToArray();
}
// Do something interesting with signature and encrypted data
// Multipart decryption and verification function C_DecryptVerifyUpdate can be used i.e. for decryption and signature verification of streamed data
using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream())
{
// Initialize decryption operation
rv = pkcs11.C_DecryptInit(session, ref encryptionMechanism, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Initialize verification operation
rv = pkcs11.C_VerifyInit(session, ref signingMechanism, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for encrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] encryptedPart = new byte[8];
// Prepare buffer for decrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
uint partLen = Convert.ToUInt32(part.Length);
// Read input stream with encrypted data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(encryptedPart, 0, encryptedPart.Length)) > 0)
{
// Process each individual encrypted data part
partLen = Convert.ToUInt32(part.Length);
rv = pkcs11.C_DecryptVerifyUpdate(session, encryptedPart, Convert.ToUInt32(bytesRead), part, ref partLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append decrypted data part to the output stream
outputStream.Write(part, 0, Convert.ToInt32(partLen));
}
// Get the length of last decrypted data part in first call
byte[] lastPart = null;
uint lastPartLen = 0;
rv = pkcs11.C_DecryptFinal(session, null, ref lastPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Allocate array for the last decrypted data part
lastPart = new byte[lastPartLen];
// Get the last decrypted data part in second call
rv = pkcs11.C_DecryptFinal(session, lastPart, ref lastPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append the last decrypted data part to the output stream
outputStream.Write(lastPart, 0, Convert.ToInt32(lastPartLen));
// Read whole output stream to the byte array so we can compare results more easily
decryptedData = outputStream.ToArray();
// Verify signature
rv = pkcs11.C_VerifyFinal(session, signature, Convert.ToUInt32(signature.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Do something interesting with decrypted data and verification result
Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData));
// In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case)
UnmanagedMemory.Free(ref encryptionMechanism.Parameter);
encryptionMechanism.ParameterLen = 0;
rv = pkcs11.C_DestroyObject(session, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_DestroyObject(session, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_DestroyObject(session, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Microsoft.AspNetCore.Analyzers.RouteHandlers.CSharpRouteHandlerCodeFixVerifier<
Microsoft.AspNetCore.Analyzers.RouteHandlers.RouteHandlerAnalyzer,
Microsoft.AspNetCore.Analyzers.RouteHandlers.Fixers.DetectMismatchedParameterOptionalityFixer>;
namespace Microsoft.AspNetCore.Analyzers.RouteHandlers;
public partial class DetectMismatchedParameterOptionalityTest
{
[Fact]
public async Task MatchingRequiredOptionality_CanBeFixed()
{
var source = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name?}"", ({|#0:string name|}) => $""Hello {name}"");";
var fixedSource = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name?}"", (string? name) => $""Hello {name}"");";
var expectedDiagnostics = new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("name").WithLocation(0);
await VerifyCS.VerifyCodeFixAsync(source, expectedDiagnostics, fixedSource);
}
[Fact]
public async Task MatchingMultipleRequiredOptionality_CanBeFixed()
{
var source = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name?}/{title?}"", ({|#0:string name|}, {|#1:string title|}) => $""Hello {name}, you are a {title}."");
";
var fixedSource = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name?}/{title?}"", (string? name, string? title) => $""Hello {name}, you are a {title}."");
";
var expectedDiagnostics = new[] {
new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("name").WithLocation(0),
new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("title").WithLocation(1)
};
await VerifyCS.VerifyCodeFixAsync(source, expectedDiagnostics, fixedSource);
}
[Fact]
public async Task MatchingSingleRequiredOptionality_CanBeFixed()
{
var source = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name?}/{title?}"", ({|#0:string name|}, string? title) => $""Hello {name}, you are a {title}."");
";
var fixedSource = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name?}/{title?}"", (string? name, string? title) => $""Hello {name}, you are a {title}."");
";
var expectedDiagnostic = new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("name").WithLocation(0);
await VerifyCS.VerifyCodeFixAsync(source, expectedDiagnostic, fixedSource);
}
[Fact]
public async Task MismatchedOptionalityInMethodGroup_CanBeFixed()
{
var source = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
string SayHello({|#0:string name|}, {|#1:string title|}) => $""Hello {name}, you are a {title}."";
app.MapGet(""/hello/{name?}/{title?}"", SayHello);
";
var fixedSource = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
string SayHello(string? name, string? title) => $""Hello {name}, you are a {title}."";
app.MapGet(""/hello/{name?}/{title?}"", SayHello);
";
var expectedDiagnostics = new[] {
new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("name").WithLocation(0),
new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("title").WithLocation(1)
};
await VerifyCS.VerifyCodeFixAsync(source, expectedDiagnostics, fixedSource);
}
[Fact]
public async Task MismatchedOptionalityInMethodGroupFromPartialMethod_CanBeFixed()
{
var source = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name?}/{title?}"", ExternalImplementation.SayHello);
public partial class ExternalImplementation
{
public static partial string SayHello({|#0:string name|}, {|#1:string title|});
}
public partial class ExternalImplementation
{
public static partial string SayHello({|#2:string name|}, {|#3:string title|})
{
return $""Hello {name}, you are a {title}."";
}
}
";
var fixedSource = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name?}/{title?}"", ExternalImplementation.SayHello);
public partial class ExternalImplementation
{
public static partial string SayHello(string? name, string? title);
}
public partial class ExternalImplementation
{
public static partial string SayHello(string? name, string? title)
{
return $""Hello {name}, you are a {title}."";
}
}
";
// Diagnostics are produced at both the declaration and definition syntax
// for partial method definitions to support the CodeFix correctly resolving both.
var expectedDiagnostics = new[] {
new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("name").WithLocation(0),
new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("title").WithLocation(1),
new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("name").WithLocation(2),
new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("title").WithLocation(3)
};
await VerifyCS.VerifyCodeFixAsync(source, expectedDiagnostics, fixedSource);
}
[Fact]
public async Task MismatchedOptionalityInSeparateSource_CanBeFixed()
{
var usageSource = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name?}/{title?}"", Helpers.SayHello);
";
var source = @"
#nullable enable
using System;
public static class Helpers
{
public static string SayHello({|#0:string name|}, {|#1:string title|})
{
return $""Hello {name}, you are a {title}."";
}
}";
var fixedSource = @"
#nullable enable
using System;
public static class Helpers
{
public static string SayHello(string? name, string? title)
{
return $""Hello {name}, you are a {title}."";
}
}";
var expectedDiagnostics = new[] {
new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("name").WithLocation(0),
new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("title").WithLocation(1)
};
await VerifyCS.VerifyCodeFixAsync(source, expectedDiagnostics, fixedSource, usageSource);
}
[Fact]
public async Task MatchingRequiredOptionality_DoesNotProduceDiagnostics()
{
// Arrange
var source = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name}"", (string name) => $""Hello {name}"");
";
await VerifyCS.VerifyCodeFixAsync(source, source);
}
[Fact]
public async Task ParameterFromRouteOrQuery_DoesNotProduceDiagnostics()
{
// Arrange
var source = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name}"", (string name) => $""Hello {name}"");
";
await VerifyCS.VerifyCodeFixAsync(source, source);
}
[Fact]
public async Task MatchingOptionality_DoesNotProduceDiagnostics()
{
// Arrange
var source = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name?}"", (string? name) => $""Hello {name}"");
";
await VerifyCS.VerifyCodeFixAsync(source, source);
}
[Fact]
public async Task RequiredRouteParamOptionalArgument_DoesNotProduceDiagnostics()
{
// Arrange
var source = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name}"", (string? name) => $""Hello {name}"");
";
await VerifyCS.VerifyCodeFixAsync(source, source);
}
[Fact]
public async Task OptionalRouteParamRequiredArgument_WithFromRoute_ProducesDiagnostics()
{
// Arrange
var source = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
var app = WebApplication.Create();
app.MapGet(""/hello/{Age?}"", ({|#0:[FromRoute] int age|}) => $""Age: {age}"");
";
var fixedSource = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
var app = WebApplication.Create();
app.MapGet(""/hello/{Age?}"", ([FromRoute] int? age) => $""Age: {age}"");
";
var expectedDiagnostic = new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("age").WithLocation(0);
await VerifyCS.VerifyCodeFixAsync(source, expectedDiagnostic, fixedSource);
}
[Fact]
public async Task OptionalRouteParamRequiredArgument_WithRegexConstraint_ProducesDiagnostics()
{
// Arrange
var source = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{age:regex(^\\d{{3}}-\\d{{2}}-\\d{{4}}$)?}"", ({|#0:int age|}) => $""Age: {age}"");
";
var fixedSource = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{age:regex(^\\d{{3}}-\\d{{2}}-\\d{{4}}$)?}"", (int? age) => $""Age: {age}"");
";
var expectedDiagnostic = new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("age").WithLocation(0);
await VerifyCS.VerifyCodeFixAsync(source, expectedDiagnostic, fixedSource);
}
[Fact]
public async Task OptionalRouteParamRequiredArgument_WithTypeConstraint_ProducesDiagnostics()
{
// Arrange
var source = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{age:int?}"", ({|#0:int age|}) => $""Age: {age}"");
";
var fixedSource = @"
#nullable enable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{age:int?}"", (int? age) => $""Age: {age}"");
";
var expectedDiagnostic = new DiagnosticResult(DiagnosticDescriptors.DetectMismatchedParameterOptionality).WithArguments("age").WithLocation(0);
await VerifyCS.VerifyCodeFixAsync(source, expectedDiagnostic, fixedSource);
}
[Fact]
public async Task MatchingRequiredOptionality_WithDisabledNullability()
{
var source = @"
#nullable disable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name?}"", (string name) => $""Hello {name}"");
";
var fixedSource = @"
#nullable disable
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/hello/{name?}"", (string name) => $""Hello {name}"");
";
await VerifyCS.VerifyCodeFixAsync(source, fixedSource);
}
[Theory]
[InlineData("{id}", new[] { "id" }, new[] { "" })]
[InlineData("{category}/product/{group}", new[] { "category", "group" }, new[] { "", "" })]
[InlineData("{category:int}/product/{group:range(10, 20)}?", new[] { "category", "group" }, new[] { ":int", ":range(10, 20)" })]
[InlineData("{person:int}/{ssn:regex(^\\d{{3}}-\\d{{2}}-\\d{{4}}$)}", new[] { "person", "ssn" }, new[] { ":int", ":regex(^\\d{{3}}-\\d{{2}}-\\d{{4}}$)"})]
[InlineData("{area=Home}/{controller:required}/{id=0:int}", new[] { "area", "controller", "id" }, new[] { "=Home", ":required", "=0:int" })]
[InlineData("{category}/product/{group?}", new[] { "category", "group" }, new[] { "", "?"})]
[InlineData("{category}/{product}/{*sku}", new[] { "category", "product", "*sku" }, new[] { "", "", "" })]
[InlineData("{category}-product-{sku}", new[] { "category", "sku" }, new[] { "", "" } )]
[InlineData("category-{product}-sku", new[] { "product" }, new[] { "" } )]
[InlineData("{category}.{sku?}", new[] { "category", "sku" }, new[] { "", "?" })]
[InlineData("{category}.{product?}/{sku}", new[] { "category", "product", "sku" }, new[] { "", "?", "" })]
public void RouteTokenizer_Works_ForSimpleRouteTemplates(string template, string[] expectedNames, string[] expectedQualifiers)
{
// Arrange
var tokenizer = new RouteHandlerAnalyzer.RouteTokenEnumerator(template);
var actualNames = new List<string>();
var actualQualifiers = new List<string>();
// Act
while (tokenizer.MoveNext())
{
actualNames.Add(tokenizer.CurrentName.ToString());
actualQualifiers.Add(tokenizer.CurrentQualifiers.ToString());
}
// Assert
Assert.Equal(expectedNames, actualNames);
Assert.Equal(expectedQualifiers, actualQualifiers);
}
}
| |
// 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.Azure.AcceptanceTestsAzureSpecials
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestAzureSpecialParametersTestClient : ServiceClient<AutoRestAzureSpecialParametersTestClient>, IAutoRestAzureSpecialParametersTestClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Gets Azure subscription credentials.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The subscription id, which appears in the path, always modeled in
/// credentials. The value is always '1234-5678-9012-3456'
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// The api version, which appears in the query, the value is always
/// '2015-07-01-preview'
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IXMsClientRequestIdOperations.
/// </summary>
public virtual IXMsClientRequestIdOperations XMsClientRequestId { get; private set; }
/// <summary>
/// Gets the ISubscriptionInCredentialsOperations.
/// </summary>
public virtual ISubscriptionInCredentialsOperations SubscriptionInCredentials { get; private set; }
/// <summary>
/// Gets the ISubscriptionInMethodOperations.
/// </summary>
public virtual ISubscriptionInMethodOperations SubscriptionInMethod { get; private set; }
/// <summary>
/// Gets the IApiVersionDefaultOperations.
/// </summary>
public virtual IApiVersionDefaultOperations ApiVersionDefault { get; private set; }
/// <summary>
/// Gets the IApiVersionLocalOperations.
/// </summary>
public virtual IApiVersionLocalOperations ApiVersionLocal { get; private set; }
/// <summary>
/// Gets the ISkipUrlEncodingOperations.
/// </summary>
public virtual ISkipUrlEncodingOperations SkipUrlEncoding { get; private set; }
/// <summary>
/// Gets the IOdataOperations.
/// </summary>
public virtual IOdataOperations Odata { get; private set; }
/// <summary>
/// Gets the IHeaderOperations.
/// </summary>
public virtual IHeaderOperations Header { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestAzureSpecialParametersTestClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestAzureSpecialParametersTestClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestAzureSpecialParametersTestClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestAzureSpecialParametersTestClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestAzureSpecialParametersTestClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestAzureSpecialParametersTestClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestAzureSpecialParametersTestClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestAzureSpecialParametersTestClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.XMsClientRequestId = new XMsClientRequestIdOperations(this);
this.SubscriptionInCredentials = new SubscriptionInCredentialsOperations(this);
this.SubscriptionInMethod = new SubscriptionInMethodOperations(this);
this.ApiVersionDefault = new ApiVersionDefaultOperations(this);
this.ApiVersionLocal = new ApiVersionLocalOperations(this);
this.SkipUrlEncoding = new SkipUrlEncodingOperations(this);
this.Odata = new OdataOperations(this);
this.Header = new HeaderOperations(this);
this.BaseUri = new Uri("http://localhost");
this.ApiVersion = "2015-07-01-preview";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Chat.V1.Service.Channel
{
/// <summary>
/// FetchMessageOptions
/// </summary>
public class FetchMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The SID of the Service to fetch the resource from
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The unique ID of the Channel the message to fetch belongs to
/// </summary>
public string PathChannelSid { get; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchMessageOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param>
/// <param name="pathChannelSid"> The unique ID of the Channel the message to fetch belongs to </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
public FetchMessageOptions(string pathServiceSid, string pathChannelSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathChannelSid = pathChannelSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// CreateMessageOptions
/// </summary>
public class CreateMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The SID of the Service to create the resource under
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The unique ID of the channel the new resource belongs to
/// </summary>
public string PathChannelSid { get; }
/// <summary>
/// The message to send to the channel
/// </summary>
public string Body { get; }
/// <summary>
/// The identity of the new message's author
/// </summary>
public string From { get; set; }
/// <summary>
/// A valid JSON string that contains application-specific data
/// </summary>
public string Attributes { get; set; }
/// <summary>
/// Construct a new CreateMessageOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the resource under </param>
/// <param name="pathChannelSid"> The unique ID of the channel the new resource belongs to </param>
/// <param name="body"> The message to send to the channel </param>
public CreateMessageOptions(string pathServiceSid, string pathChannelSid, string body)
{
PathServiceSid = pathServiceSid;
PathChannelSid = pathChannelSid;
Body = body;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Body != null)
{
p.Add(new KeyValuePair<string, string>("Body", Body));
}
if (From != null)
{
p.Add(new KeyValuePair<string, string>("From", From));
}
if (Attributes != null)
{
p.Add(new KeyValuePair<string, string>("Attributes", Attributes));
}
return p;
}
}
/// <summary>
/// ReadMessageOptions
/// </summary>
public class ReadMessageOptions : ReadOptions<MessageResource>
{
/// <summary>
/// The SID of the Service to read the resources from
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The unique ID of the Channel the message to read belongs to
/// </summary>
public string PathChannelSid { get; }
/// <summary>
/// The sort order of the returned messages
/// </summary>
public MessageResource.OrderTypeEnum Order { get; set; }
/// <summary>
/// Construct a new ReadMessageOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the resources from </param>
/// <param name="pathChannelSid"> The unique ID of the Channel the message to read belongs to </param>
public ReadMessageOptions(string pathServiceSid, string pathChannelSid)
{
PathServiceSid = pathServiceSid;
PathChannelSid = pathChannelSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Order != null)
{
p.Add(new KeyValuePair<string, string>("Order", Order.ToString()));
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// DeleteMessageOptions
/// </summary>
public class DeleteMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The SID of the Service to delete the resource from
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The unique ID of the channel the message to delete belongs to
/// </summary>
public string PathChannelSid { get; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteMessageOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param>
/// <param name="pathChannelSid"> The unique ID of the channel the message to delete belongs to </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
public DeleteMessageOptions(string pathServiceSid, string pathChannelSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathChannelSid = pathChannelSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// UpdateMessageOptions
/// </summary>
public class UpdateMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The SID of the Service to update the resource from
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// he unique ID of the Channel the message belongs to
/// </summary>
public string PathChannelSid { get; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
public string PathSid { get; }
/// <summary>
/// The message to send to the channel
/// </summary>
public string Body { get; set; }
/// <summary>
/// A valid JSON string that contains application-specific data
/// </summary>
public string Attributes { get; set; }
/// <summary>
/// Construct a new UpdateMessageOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to update the resource from </param>
/// <param name="pathChannelSid"> he unique ID of the Channel the message belongs to </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
public UpdateMessageOptions(string pathServiceSid, string pathChannelSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathChannelSid = pathChannelSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Body != null)
{
p.Add(new KeyValuePair<string, string>("Body", Body));
}
if (Attributes != null)
{
p.Add(new KeyValuePair<string, string>("Attributes", Attributes));
}
return p;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Management.WebSites;
using Microsoft.WindowsAzure.Management.WebSites.Models;
namespace Microsoft.WindowsAzure.Management.WebSites
{
/// <summary>
/// The Web Sites Management API provides a RESTful set of web services
/// that interact with the Windows Azure Web Sites service to manage your
/// web sites. The API has entities that capture the relationship between
/// an end user and Windows Azure Web Sites service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for
/// more information)
/// </summary>
public static partial class WebSpaceOperationsExtensions
{
/// <summary>
/// Creates a source control user with permissions to publish to this
/// web space.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.WebSites.IWebSpaceOperations.
/// </param>
/// <param name='username'>
/// Required. The user name.
/// </param>
/// <param name='password'>
/// Required. The user password.
/// </param>
/// <param name='parameters'>
/// Optional. Parameters supplied to the Create Publishing User
/// operation.
/// </param>
/// <returns>
/// The Create Publishing User operation response.
/// </returns>
public static WebSpacesCreatePublishingUserResponse CreatePublishingUser(this IWebSpaceOperations operations, string username, string password, WebSpacesCreatePublishingUserParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IWebSpaceOperations)s).CreatePublishingUserAsync(username, password, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a source control user with permissions to publish to this
/// web space.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.WebSites.IWebSpaceOperations.
/// </param>
/// <param name='username'>
/// Required. The user name.
/// </param>
/// <param name='password'>
/// Required. The user password.
/// </param>
/// <param name='parameters'>
/// Optional. Parameters supplied to the Create Publishing User
/// operation.
/// </param>
/// <returns>
/// The Create Publishing User operation response.
/// </returns>
public static Task<WebSpacesCreatePublishingUserResponse> CreatePublishingUserAsync(this IWebSpaceOperations operations, string username, string password, WebSpacesCreatePublishingUserParameters parameters)
{
return operations.CreatePublishingUserAsync(username, password, parameters, CancellationToken.None);
}
/// <summary>
/// You can retrieve details for a specified web space name by issuing
/// an HTTP GET request. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn167017.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.WebSites.IWebSpaceOperations.
/// </param>
/// <param name='webSpaceName'>
/// Required. The name of the web space.
/// </param>
/// <returns>
/// The Get Web Space Details operation response.
/// </returns>
public static WebSpacesGetResponse Get(this IWebSpaceOperations operations, string webSpaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IWebSpaceOperations)s).GetAsync(webSpaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// You can retrieve details for a specified web space name by issuing
/// an HTTP GET request. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn167017.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.WebSites.IWebSpaceOperations.
/// </param>
/// <param name='webSpaceName'>
/// Required. The name of the web space.
/// </param>
/// <returns>
/// The Get Web Space Details operation response.
/// </returns>
public static Task<WebSpacesGetResponse> GetAsync(this IWebSpaceOperations operations, string webSpaceName)
{
return operations.GetAsync(webSpaceName, CancellationToken.None);
}
/// <summary>
/// Get the DNS Suffix for this subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.WebSites.IWebSpaceOperations.
/// </param>
/// <returns>
/// The Get DNS Suffix operation response.
/// </returns>
public static WebSpacesGetDnsSuffixResponse GetDnsSuffix(this IWebSpaceOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IWebSpaceOperations)s).GetDnsSuffixAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the DNS Suffix for this subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.WebSites.IWebSpaceOperations.
/// </param>
/// <returns>
/// The Get DNS Suffix operation response.
/// </returns>
public static Task<WebSpacesGetDnsSuffixResponse> GetDnsSuffixAsync(this IWebSpaceOperations operations)
{
return operations.GetDnsSuffixAsync(CancellationToken.None);
}
/// <summary>
/// You can list the web spaces under the current subscription by
/// issuing a GET request. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn166961.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.WebSites.IWebSpaceOperations.
/// </param>
/// <returns>
/// The List Web Spaces operation response.
/// </returns>
public static WebSpacesListResponse List(this IWebSpaceOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IWebSpaceOperations)s).ListAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// You can list the web spaces under the current subscription by
/// issuing a GET request. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn166961.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.WebSites.IWebSpaceOperations.
/// </param>
/// <returns>
/// The List Web Spaces operation response.
/// </returns>
public static Task<WebSpacesListResponse> ListAsync(this IWebSpaceOperations operations)
{
return operations.ListAsync(CancellationToken.None);
}
/// <summary>
/// Get the available geo regions for this web space.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.WebSites.IWebSpaceOperations.
/// </param>
/// <returns>
/// The List Geo Regions operation response.
/// </returns>
public static WebSpacesListGeoRegionsResponse ListGeoRegions(this IWebSpaceOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IWebSpaceOperations)s).ListGeoRegionsAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the available geo regions for this web space.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.WebSites.IWebSpaceOperations.
/// </param>
/// <returns>
/// The List Geo Regions operation response.
/// </returns>
public static Task<WebSpacesListGeoRegionsResponse> ListGeoRegionsAsync(this IWebSpaceOperations operations)
{
return operations.ListGeoRegionsAsync(CancellationToken.None);
}
/// <summary>
/// Get the source control users allowed to publish to this web space.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.WebSites.IWebSpaceOperations.
/// </param>
/// <returns>
/// The List Publishing Users operation response.
/// </returns>
public static WebSpacesListPublishingUsersResponse ListPublishingUsers(this IWebSpaceOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IWebSpaceOperations)s).ListPublishingUsersAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the source control users allowed to publish to this web space.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.WebSites.IWebSpaceOperations.
/// </param>
/// <returns>
/// The List Publishing Users operation response.
/// </returns>
public static Task<WebSpacesListPublishingUsersResponse> ListPublishingUsersAsync(this IWebSpaceOperations operations)
{
return operations.ListPublishingUsersAsync(CancellationToken.None);
}
/// <summary>
/// You can retrieve a list of all web sites in a web space by issuing
/// an HTTP GET request. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn236429.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.WebSites.IWebSpaceOperations.
/// </param>
/// <param name='webSpaceName'>
/// Required. The name of the web space.
/// </param>
/// <param name='parameters'>
/// Optional. Additional parameters.
/// </param>
/// <returns>
/// The List Web Sites operation response.
/// </returns>
public static WebSpacesListWebSitesResponse ListWebSites(this IWebSpaceOperations operations, string webSpaceName, WebSiteListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IWebSpaceOperations)s).ListWebSitesAsync(webSpaceName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// You can retrieve a list of all web sites in a web space by issuing
/// an HTTP GET request. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn236429.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.WebSites.IWebSpaceOperations.
/// </param>
/// <param name='webSpaceName'>
/// Required. The name of the web space.
/// </param>
/// <param name='parameters'>
/// Optional. Additional parameters.
/// </param>
/// <returns>
/// The List Web Sites operation response.
/// </returns>
public static Task<WebSpacesListWebSitesResponse> ListWebSitesAsync(this IWebSpaceOperations operations, string webSpaceName, WebSiteListParameters parameters)
{
return operations.ListWebSitesAsync(webSpaceName, parameters, CancellationToken.None);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
namespace System.Security.Cryptography
{
/// <summary>
/// Utility class to strongly type algorithms used with CNG. Since all CNG APIs which require an
/// algorithm name take the name as a string, we use this string wrapper class to specifically mark
/// which parameters are expected to be algorithms. We also provide a list of well known algorithm
/// names, which helps Intellisense users find a set of good algorithm names to use.
/// </summary>
[Serializable]
public sealed class CngAlgorithm : IEquatable<CngAlgorithm>
{
public CngAlgorithm(string algorithm)
{
if (algorithm == null)
throw new ArgumentNullException(nameof(algorithm));
if (algorithm.Length == 0)
throw new ArgumentException(SR.Format(SR.Cryptography_InvalidAlgorithmName, algorithm), nameof(algorithm));
_algorithm = algorithm;
}
/// <summary>
/// Name of the algorithm
/// </summary>
public string Algorithm
{
get
{
return _algorithm;
}
}
public static bool operator ==(CngAlgorithm left, CngAlgorithm right)
{
if (object.ReferenceEquals(left, null))
{
return object.ReferenceEquals(right, null);
}
return left.Equals(right);
}
public static bool operator !=(CngAlgorithm left, CngAlgorithm right)
{
if (object.ReferenceEquals(left, null))
{
return !object.ReferenceEquals(right, null);
}
return !left.Equals(right);
}
public override bool Equals(object obj)
{
Debug.Assert(_algorithm != null);
return Equals(obj as CngAlgorithm);
}
public bool Equals(CngAlgorithm other)
{
if (object.ReferenceEquals(other, null))
{
return false;
}
return _algorithm.Equals(other.Algorithm);
}
public override int GetHashCode()
{
Debug.Assert(_algorithm != null);
return _algorithm.GetHashCode();
}
public override string ToString()
{
Debug.Assert(_algorithm != null);
return _algorithm;
}
//
// Well known algorithms
//
public static CngAlgorithm Rsa
{
get
{
return s_rsa ?? (s_rsa = new CngAlgorithm("RSA")); // BCRYPT_RSA_ALGORITHM
}
}
public static CngAlgorithm ECDiffieHellman
{
get
{
return s_ecdh ?? (s_ecdh = new CngAlgorithm("ECDH")); // BCRYPT_ECDH_ALGORITHM
}
}
public static CngAlgorithm ECDiffieHellmanP256
{
get
{
return s_ecdhp256 ?? (s_ecdhp256 = new CngAlgorithm("ECDH_P256")); // BCRYPT_ECDH_P256_ALGORITHM
}
}
public static CngAlgorithm ECDiffieHellmanP384
{
get
{
return s_ecdhp384 ?? (s_ecdhp384 = new CngAlgorithm("ECDH_P384")); // BCRYPT_ECDH_P384_ALGORITHM
}
}
public static CngAlgorithm ECDiffieHellmanP521
{
get
{
return s_ecdhp521 ?? (s_ecdhp521 = new CngAlgorithm("ECDH_P521")); // BCRYPT_ECDH_P521_ALGORITHM
}
}
public static CngAlgorithm ECDsa
{
get
{
return s_ecdsa ?? (s_ecdsa = new CngAlgorithm("ECDSA")); // BCRYPT_ECDSA_ALGORITHM
}
}
public static CngAlgorithm ECDsaP256
{
get
{
return s_ecdsap256 ?? (s_ecdsap256 = new CngAlgorithm("ECDSA_P256")); // BCRYPT_ECDSA_P256_ALGORITHM
}
}
public static CngAlgorithm ECDsaP384
{
get
{
return s_ecdsap384 ?? (s_ecdsap384 = new CngAlgorithm("ECDSA_P384")); // BCRYPT_ECDSA_P384_ALGORITHM
}
}
public static CngAlgorithm ECDsaP521
{
get
{
return s_ecdsap521 ?? (s_ecdsap521 = new CngAlgorithm("ECDSA_P521")); // BCRYPT_ECDSA_P521_ALGORITHM
}
}
public static CngAlgorithm MD5
{
get
{
return s_md5 ?? (s_md5 = new CngAlgorithm("MD5")); // BCRYPT_MD5_ALGORITHM
}
}
public static CngAlgorithm Sha1
{
get
{
return s_sha1 ?? (s_sha1 = new CngAlgorithm("SHA1")); // BCRYPT_SHA1_ALGORITHM
}
}
public static CngAlgorithm Sha256
{
get
{
return s_sha256 ?? (s_sha256 = new CngAlgorithm("SHA256")); // BCRYPT_SHA256_ALGORITHM
}
}
public static CngAlgorithm Sha384
{
get
{
return s_sha384 ?? (s_sha384 = new CngAlgorithm("SHA384")); // BCRYPT_SHA384_ALGORITHM
}
}
public static CngAlgorithm Sha512
{
get
{
return s_sha512 ?? (s_sha512 = new CngAlgorithm("SHA512")); // BCRYPT_SHA512_ALGORITHM
}
}
private static CngAlgorithm s_ecdh;
private static CngAlgorithm s_ecdhp256;
private static CngAlgorithm s_ecdhp384;
private static CngAlgorithm s_ecdhp521;
private static CngAlgorithm s_ecdsa;
private static CngAlgorithm s_ecdsap256;
private static CngAlgorithm s_ecdsap384;
private static CngAlgorithm s_ecdsap521;
private static CngAlgorithm s_md5;
private static CngAlgorithm s_sha1;
private static CngAlgorithm s_sha256;
private static CngAlgorithm s_sha384;
private static CngAlgorithm s_sha512;
private static CngAlgorithm s_rsa;
private readonly string _algorithm;
}
}
| |
using System;
namespace Wasm.Interpret
{
/// <summary>
/// Defines helper functions that operate on WebAssembly values.
/// </summary>
public static class ValueHelpers
{
/// <summary>
/// Takes a WebAssembly value type and maps it to its corresponding CLR type.
/// </summary>
/// <param name="type">The type to map to a CLR type.</param>
/// <returns>A CLR type.</returns>
public static Type ToClrType(WasmValueType type)
{
switch (type)
{
case WasmValueType.Float32:
return typeof(float);
case WasmValueType.Float64:
return typeof(double);
case WasmValueType.Int32:
return typeof(int);
case WasmValueType.Int64:
return typeof(long);
default:
throw new WasmException($"Cannot convert unknown WebAssembly type '{type}' to a CLR type.");
}
}
/// <summary>
/// Takes a type and maps it to its corresponding WebAssembly value type.
/// </summary>
/// <param name="type">The type to map to a WebAssembly value type.</param>
/// <returns>A WebAssembly value type.</returns>
public static WasmValueType ToWasmValueType(Type type)
{
if (type == typeof(int))
{
return WasmValueType.Int32;
}
else if (type == typeof(long))
{
return WasmValueType.Int64;
}
else if (type == typeof(float))
{
return WasmValueType.Float32;
}
else if (type == typeof(double))
{
return WasmValueType.Float64;
}
else
{
throw new WasmException($"Type '{type}' does not map to a WebAssembly type.");
}
}
/// <summary>
/// Takes a type and maps it to its corresponding WebAssembly value type.
/// </summary>
/// <typeparam name="T">The type to map to a WebAssembly value type.</typeparam>
/// <returns>A WebAssembly value type.</returns>
public static WasmValueType ToWasmValueType<T>()
{
return ToWasmValueType(typeof(T));
}
/// <summary>
/// Reinterprets the given 32-bit integer's bits as a 32-bit floating-point
/// number.
/// </summary>
/// <param name="value">The value to reinterpret.</param>
/// <returns>A 32-bit floating-point number.</returns>
public static unsafe float ReinterpretAsFloat32(int value)
{
return *(float*)&value;
}
/// <summary>
/// Reinterprets the given 32-bit floating-point number's bits as a 32-bit
/// integer.
/// </summary>
/// <param name="value">The value to reinterpret.</param>
/// <returns>A 32-bit integer.</returns>
public static unsafe int ReinterpretAsInt32(float value)
{
return *(int*)&value;
}
/// <summary>
/// Reinterprets the given 64-bit integer's bits as a 64-bit floating-point
/// number.
/// </summary>
/// <param name="value">The value to reinterpret.</param>
/// <returns>A 64-bit floating-point number.</returns>
public static double ReinterpretAsFloat64(long value)
{
return BitConverter.Int64BitsToDouble(value);
}
/// <summary>
/// Reinterprets the given 64-bit floating-point number's bits as a 64-bit
/// integer.
/// </summary>
/// <param name="value">The value to reinterpret.</param>
/// <returns>A 64-bit integer.</returns>
public static long ReinterpretAsInt64(double value)
{
return BitConverter.DoubleToInt64Bits(value);
}
/// <summary>
/// Rotates the first operand to the left by the number of
/// bits given by the second operand.
/// </summary>
/// <param name="left">The first operand.</param>
/// <param name="right">The second operand.</param>
public static int RotateLeft(int left, int right)
{
var rhs = right;
var lhs = (uint)left;
uint result = (lhs << rhs) | (lhs >> (32 - rhs));
return (int)result;
}
/// <summary>
/// Rotates the first operand to the right by the number of
/// bits given by the second operand.
/// </summary>
/// <param name="left">The first operand.</param>
/// <param name="right">The second operand.</param>
public static int RotateRight(int left, int right)
{
var rhs = right;
var lhs = (uint)left;
uint result = (lhs >> rhs) | (lhs << (32 - rhs));
return (int)result;
}
/// <summary>
/// Counts the number of leading zero bits in the given integer.
/// </summary>
/// <param name="value">The operand.</param>
public static int CountLeadingZeros(int value)
{
var uintVal = (uint)value;
int numOfLeadingZeros = 32;
while (uintVal != 0)
{
numOfLeadingZeros--;
uintVal >>= 1;
}
return numOfLeadingZeros;
}
/// <summary>
/// Counts the number of trailing zero bits in the given integer.
/// </summary>
/// <param name="value">The operand.</param>
public static int CountTrailingZeros(int value)
{
var uintVal = (uint)value;
if (uintVal == 0u)
{
return 32;
}
int numOfTrailingZeros = 0;
while ((uintVal & 0x1u) == 0u)
{
numOfTrailingZeros++;
uintVal >>= 1;
}
return numOfTrailingZeros;
}
/// <summary>
/// Counts the number of one bits in the given integer.
/// </summary>
/// <param name="value">The operand.</param>
public static int PopCount(int value)
{
var uintVal = (uint)value;
int numOfOnes = 0;
while (uintVal != 0)
{
numOfOnes += (int)(uintVal & 0x1u);
uintVal >>= 1;
}
return numOfOnes;
}
/// <summary>
/// Rotates the first operand to the left by the number of
/// bits given by the second operand.
/// </summary>
/// <param name="left">The first operand.</param>
/// <param name="right">The second operand.</param>
public static long RotateLeft(long left, long right)
{
var rhs = (int)right;
var lhs = (ulong)left;
ulong result = (lhs << rhs) | (lhs >> (64 - rhs));
return (long)result;
}
/// <summary>
/// Rotates the first operand to the right by the number of
/// bits given by the second operand.
/// </summary>
/// <param name="left">The first operand.</param>
/// <param name="right">The second operand.</param>
public static long RotateRight(long left, long right)
{
var rhs = (int)right;
var lhs = (ulong)left;
ulong result = (lhs >> rhs) | (lhs << (64 - rhs));
return (long)result;
}
/// <summary>
/// Counts the number of leading zero bits in the given integer.
/// </summary>
/// <param name="value">The operand.</param>
public static int CountLeadingZeros(long value)
{
var uintVal = (ulong)value;
int numOfLeadingZeros = 64;
while (uintVal != 0)
{
numOfLeadingZeros--;
uintVal >>= 1;
}
return numOfLeadingZeros;
}
/// <summary>
/// Counts the number of trailing zero bits in the given integer.
/// </summary>
/// <param name="value">The operand.</param>
public static int CountTrailingZeros(long value)
{
var uintVal = (ulong)value;
if (uintVal == 0ul)
{
return 64;
}
int numOfTrailingZeros = 0;
while ((uintVal & 0x1u) == 0u)
{
numOfTrailingZeros++;
uintVal >>= 1;
}
return numOfTrailingZeros;
}
/// <summary>
/// Counts the number of one bits in the given integer.
/// </summary>
/// <param name="value">The operand.</param>
public static int PopCount(long value)
{
var uintVal = (ulong)value;
int numOfOnes = 0;
while (uintVal != 0)
{
numOfOnes += (int)(uintVal & 0x1u);
uintVal >>= 1;
}
return numOfOnes;
}
// Based on the StackOverflow answer by Deduplicator:
// https://stackoverflow.com/questions/26576285/how-can-i-get-the-sign-bit-of-a-double
private static readonly int float32SignMask = unchecked((int)0x80000000);
private static readonly long float64SignMask = unchecked((long)0x8000000000000000);
/// <summary>
/// Tests if the sign bit of the given 32-bit floating point value is set,
/// i.e., if the value is negative.
/// </summary>
/// <param name="value">The value to test.</param>
/// <returns><c>true</c> if the value's sign bit is set; otherwise, <c>false</c>.</returns>
public static bool Signbit(float value)
{
return (ReinterpretAsInt32(value) & float32SignMask) == float32SignMask;
}
/// <summary>
/// Composes a 32-bit floating point number with the magnitude of the first
/// argument and the sign of the second.
/// </summary>
/// <param name="left">The argument whose magnitude is used.</param>
/// <param name="right">The argument whose sign bit is used.</param>
public static float Copysign(float left, float right)
{
int leftBits = ReinterpretAsInt32(left);
int rightBits = ReinterpretAsInt32(right);
int resultBits = (leftBits & ~float32SignMask) | (rightBits & float32SignMask);
return ReinterpretAsFloat32(resultBits);
}
/// <summary>
/// Tests if the sign bit of the given 64-bit floating point value is set,
/// i.e., if the value is negative.
/// </summary>
/// <param name="value">The value to test.</param>
/// <returns><c>true</c> if the value's sign bit is set; otherwise, <c>false</c>.</returns>
public static bool Signbit(double value)
{
return (ReinterpretAsInt64(value) & float64SignMask) == float64SignMask;
}
/// <summary>
/// Composes a 64-bit floating point number with the magnitude of the first
/// argument and the sign of the second.
/// </summary>
/// <param name="left">The argument whose magnitude is used.</param>
/// <param name="right">The argument whose sign bit is used.</param>
public static double Copysign(double left, double right)
{
long leftBits = ReinterpretAsInt64(left);
long rightBits = ReinterpretAsInt64(right);
long resultBits = (leftBits & ~float64SignMask) | (rightBits & float64SignMask);
return ReinterpretAsFloat64(resultBits);
}
/// <summary>
/// Sets the sign of a 32-bit floating point number.
/// </summary>
/// <param name="value">A number whose magnitude is preserved and sign is rewritten.</param>
/// <param name="isNegative">The sign to assign to <paramref name="value"/>.</param>
/// <returns>A number that is equal to <paramref name="value"/> in magnitude and <paramref name="isNegative"/> in sign.</returns>
public static float Setsign(float value, bool isNegative)
{
return Copysign(value, isNegative ? -1.0f : 1.0f);
}
/// <summary>
/// Sets the sign of a 64-bit floating point number.
/// </summary>
/// <param name="value">A number whose magnitude is preserved and sign is rewritten.</param>
/// <param name="isNegative">The sign to assign to <paramref name="value"/>.</param>
/// <returns>A number that is equal to <paramref name="value"/> in magnitude and <paramref name="isNegative"/> in sign.</returns>
public static double Setsign(double value, bool isNegative)
{
return Copysign(value, isNegative ? -1.0 : 1.0);
}
/// <summary>
/// Takes a 32-bit floating point number and truncates it to a
/// 32-bit signed integer.
/// </summary>
/// <param name="value">A 32-bit floating point number to truncate.</param>
/// <returns>A 32-bit integer that is the truncated version of <paramref name="value"/>.</returns>
public static int TruncateToInt32(float value)
{
if (float.IsInfinity(value))
{
return ThrowInfinityToInt<int>();
}
else if (float.IsNaN(value))
{
return ThrowNaNToInt<int>();
}
else
{
return checked((int)value);
}
}
/// <summary>
/// Takes a 32-bit floating point number and truncates it to a
/// 32-bit unsigned integer.
/// </summary>
/// <param name="value">A 32-bit floating point number to truncate.</param>
/// <returns>A 32-bit integer that is the truncated version of <paramref name="value"/>.</returns>
public static uint TruncateToUInt32(float value)
{
if (float.IsInfinity(value))
{
return ThrowInfinityToInt<uint>();
}
else if (float.IsNaN(value))
{
return ThrowNaNToInt<uint>();
}
else
{
return checked((uint)value);
}
}
/// <summary>
/// Takes a 64-bit floating point number and truncates it to a
/// 32-bit signed integer.
/// </summary>
/// <param name="value">A 64-bit floating point number to truncate.</param>
/// <returns>A 32-bit integer that is the truncated version of <paramref name="value"/>.</returns>
public static int TruncateToInt32(double value)
{
if (double.IsInfinity(value))
{
return ThrowInfinityToInt<int>();
}
else if (double.IsNaN(value))
{
return ThrowNaNToInt<int>();
}
else
{
return checked((int)value);
}
}
/// <summary>
/// Takes a 64-bit floating point number and truncates it to a
/// 32-bit unsigned integer.
/// </summary>
/// <param name="value">A 64-bit floating point number to truncate.</param>
/// <returns>A 32-bit integer that is the truncated version of <paramref name="value"/>.</returns>
public static uint TruncateToUInt32(double value)
{
if (double.IsInfinity(value))
{
return ThrowInfinityToInt<uint>();
}
else if (double.IsNaN(value))
{
return ThrowNaNToInt<uint>();
}
else
{
return checked((uint)value);
}
}
/// <summary>
/// Takes a 32-bit floating point number and truncates it to a
/// 64-bit signed integer.
/// </summary>
/// <param name="value">A 32-bit floating point number to truncate.</param>
/// <returns>A 64-bit integer that is the truncated version of <paramref name="value"/>.</returns>
public static long TruncateToInt64(float value)
{
if (float.IsInfinity(value))
{
return ThrowInfinityToInt<long>();
}
else if (float.IsNaN(value))
{
return ThrowNaNToInt<long>();
}
else
{
return checked((long)value);
}
}
/// <summary>
/// Takes a 32-bit floating point number and truncates it to a
/// 64-bit unsigned integer.
/// </summary>
/// <param name="value">A 32-bit floating point number to truncate.</param>
/// <returns>A 64-bit integer that is the truncated version of <paramref name="value"/>.</returns>
public static ulong TruncateToUInt64(float value)
{
if (float.IsInfinity(value))
{
return ThrowInfinityToInt<ulong>();
}
else if (float.IsNaN(value))
{
return ThrowNaNToInt<ulong>();
}
else
{
return checked((ulong)value);
}
}
/// <summary>
/// Takes a 64-bit floating point number and truncates it to a
/// 64-bit signed integer.
/// </summary>
/// <param name="value">A 64-bit floating point number to truncate.</param>
/// <returns>A 64-bit integer that is the truncated version of <paramref name="value"/>.</returns>
public static long TruncateToInt64(double value)
{
if (double.IsInfinity(value))
{
return ThrowInfinityToInt<long>();
}
else if (double.IsNaN(value))
{
return ThrowNaNToInt<long>();
}
else
{
return checked((long)value);
}
}
/// <summary>
/// Takes a 64-bit floating point number and truncates it to a
/// 64-bit unsigned integer.
/// </summary>
/// <param name="value">A 64-bit floating point number to truncate.</param>
/// <returns>A 64-bit integer that is the truncated version of <paramref name="value"/>.</returns>
public static ulong TruncateToUInt64(double value)
{
if (double.IsInfinity(value))
{
return ThrowInfinityToInt<ulong>();
}
else if (double.IsNaN(value))
{
return ThrowNaNToInt<ulong>();
}
else
{
return checked((ulong)value);
}
}
/// <summary>
/// Computes the remainder of two signed 32-bit integers, as specified by
/// the WebAssembly spec.
/// </summary>
/// <param name="lhs">A first integer.</param>
/// <param name="rhs">A second integer.</param>
/// <returns>The remainder after division of <paramref name="lhs"/> and <paramref name="rhs"/>.</returns>
public static int RemS(int lhs, int rhs)
{
if (lhs == int.MinValue && rhs == -1)
{
// We need to check for this corner case. As per the OpCodes.Rem docs:
//
// Note that on the Intel-based platforms an OverflowException is thrown when computing (minint rem -1).
//
return 0;
}
else
{
return lhs % rhs;
}
}
/// <summary>
/// Computes the remainder of two signed 64-bit integers, as specified by
/// the WebAssembly spec.
/// </summary>
/// <param name="lhs">A first integer.</param>
/// <param name="rhs">A second integer.</param>
/// <returns>The remainder after division of <paramref name="lhs"/> and <paramref name="rhs"/>.</returns>
public static long RemS(long lhs, long rhs)
{
if (lhs == long.MinValue && rhs == -1)
{
// We need to check for this corner case. As per the OpCodes.Rem docs:
//
// Note that on the Intel-based platforms an OverflowException is thrown when computing (minint rem -1).
//
return 0;
}
else
{
return lhs % rhs;
}
}
private static T ThrowInfinityToInt<T>()
{
throw new TrapException(
"Cannot convert infinity to an integer.",
TrapException.SpecMessages.IntegerOverflow);
}
private static T ThrowNaNToInt<T>()
{
throw new TrapException(
"Cannot convert NaN to an integer.",
TrapException.SpecMessages.InvalidConversionToInteger);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// The default hooks that are most likely be overridden/implemented by a game
//-----------------------------------------------------------------------------
function onServerCreated()
{
// Invoked by createServer(), when server is created and ready to go
// Server::GameType is sent to the master server.
// This variable should uniquely identify your game and/or mod.
$Server::GameType = "Test App";
// Load up any objects or datablocks saved to the editor managed scripts
%datablockFiles = new ArrayObject();
%datablockFiles.add( "art/ribbons/ribbonExec.cs" );
%datablockFiles.add( "art/particles/managedParticleData.cs" );
%datablockFiles.add( "art/particles/managedParticleEmitterData.cs" );
%datablockFiles.add( "art/decals/managedDecalData.cs" );
%datablockFiles.add( "art/datablocks/managedDatablocks.cs" );
%datablockFiles.add( "art/forest/managedItemData.cs" );
%datablockFiles.add( "art/datablocks/datablockExec.cs" );
loadDatablockFiles( %datablockFiles, true );
// Run the other gameplay scripts in this folder
exec("./scriptExec.cs");
// For backwards compatibility...
createGame();
}
function loadDatablockFiles( %datablockFiles, %recurse )
{
if ( %recurse )
{
recursiveLoadDatablockFiles( %datablockFiles, 9999 );
return;
}
%count = %datablockFiles.count();
for ( %i=0; %i < %count; %i++ )
{
%file = %datablockFiles.getKey( %i );
if ( !isScriptFile( %file ) )
continue;
exec( %file );
}
// Destroy the incoming list.
%datablockFiles.delete();
}
function recursiveLoadDatablockFiles( %datablockFiles, %previousErrors )
{
%reloadDatablockFiles = new ArrayObject();
// Keep track of the number of datablocks that
// failed during this pass.
%failedDatablocks = 0;
// Try re-executing the list of datablock files.
%count = %datablockFiles.count();
for ( %i=0; %i < %count; %i++ )
{
%file = %datablockFiles.getKey( %i );
if ( !isScriptFile( %file ) )
continue;
// Start counting copy constructor creation errors.
$Con::objectCopyFailures = 0;
exec( %file );
// If errors occured then store this file for re-exec later.
if ( $Con::objectCopyFailures > 0 )
{
%reloadDatablockFiles.add( %file );
%failedDatablocks = %failedDatablocks + $Con::objectCopyFailures;
}
}
// Clear the object copy failure counter so that
// we get console error messages again.
$Con::objectCopyFailures = -1;
// Delete the old incoming list... we're done with it.
%datablockFiles.delete();
// If we still have datablocks to retry.
%newCount = %reloadDatablockFiles.count();
if ( %newCount > 0 )
{
// If the datablock failures have not been reduced
// from the last pass then we must have a real syntax
// error and not just a bad dependancy.
if ( %lastFailures > %failedDatablocks )
recursiveLoadDatablockFiles( %reloadDatablockFiles, %failedDatablocks );
else
{
// Since we must have real syntax errors do one
// last normal exec to output error messages.
loadDatablockFiles( %reloadDatablockFiles, false );
}
return;
}
// Cleanup the empty reload list.
%reloadDatablockFiles.delete();
}
function onServerDestroyed()
{
// Invoked by destroyServer(), right before the server is destroyed
destroyGame();
}
function onMissionLoaded()
{
// Called by loadMission() once the mission is finished loading
startGame();
}
function onMissionEnded()
{
// Called by endMission(), right before the mission is destroyed
endGame();
}
function onMissionReset()
{
// Called by resetMission(), after all the temporary mission objects
// have been deleted.
}
//-----------------------------------------------------------------------------
// These methods are extensions to the GameConnection class. Extending
// GameConnection make is easier to deal with some of this functionality,
// but these could also be implemented as stand-alone functions.
//-----------------------------------------------------------------------------
function GameConnection::onClientEnterGame(%this)
{
// Called for each client after it's finished downloading the
// mission and is ready to start playing.
}
function GameConnection::onClientLeaveGame(%this)
{
// Call for each client that drops
}
//-----------------------------------------------------------------------------
// Functions that implement game-play
// These are here for backwards compatibilty only, games and/or mods should
// really be overloading the server and mission functions listed ubove.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
function createGame()
{
// This function is called by onServerCreated (above)
}
function destroyGame()
{
// This function is called by onServerDestroyed (above)
}
//-----------------------------------------------------------------------------
function startGame()
{
// This is where the game play should start
// The default onMissionLoaded function starts the game.
}
function endGame()
{
// This is where the game play should end
// The default onMissionEnded function shuts down the game.
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using System.Xml;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Security.Permissions;
using log4net;
using FluorineFx.AMF3;
using FluorineFx.Configuration;
using FluorineFx.Exceptions;
namespace FluorineFx.IO.Bytecode.CodeDom
{
/// <summary>
/// This type supports the Fluorine infrastructure and is not intended to be used directly from your code.
/// </summary>
class AMF3ReflectionOptimizer : AMF0ReflectionOptimizer
{
private static readonly ILog log = LogManager.GetLogger(typeof(AMF3ReflectionOptimizer));
ClassDefinition _classDefinition;
public AMF3ReflectionOptimizer(Type type, ClassDefinition classDefinition, AMFReader reader) : base(type, reader)
{
_classDefinition = classDefinition;
}
protected override string GenerateCode(object instance)
{
Type type = instance.GetType();
_layouter.Append(GetHeader());
_layouter.AppendFormat(GetClassDefinition(), _mappedClass.FullName.Replace('.', '_').Replace("+", "__"), _mappedClass.FullName);
_layouter.Begin();
_layouter.Begin();
_layouter.AppendFormat("{0} instance = new {0}();", _mappedClass.FullName);
_layouter.Append("reader.AddAMF3ObjectReference(instance);");
_layouter.Append("byte typeCode = 0;");
for (int i = 0; i < _classDefinition.MemberCount; i++)
{
string key = _classDefinition.Members[i].Name;
object value = _reader.ReadAMF3Data();
_reader.SetMember(instance, key, value);
_layouter.Append("typeCode = reader.ReadByte();");
MemberInfo[] memberInfos = type.GetMember(key);
if (memberInfos != null && memberInfos.Length > 0)
GeneratePropertySet(memberInfos[0]);
else
{
//Log this error (do not throw exception), otherwise our current AMF stream becomes unreliable
log.Warn(__Res.GetString(__Res.Optimizer_Warning));
string msg = __Res.GetString(__Res.Reflection_MemberNotFound, string.Format("{0}.{1}", _mappedClass.FullName, key));
log.Warn(msg);
_layouter.AppendFormat("//{0}", msg);
_layouter.Append("reader.ReadAMF3Data(typeCode);");
}
}
_layouter.Append("return instance;");
_layouter.End();
_layouter.Append("}");
_layouter.End();
_layouter.Append("}"); // Close class
_layouter.Append("}"); // Close namespace
return _layouter.ToString();
}
private void GeneratePropertySet(MemberInfo memberInfo)
{
Type memberType = null;
if (memberInfo is PropertyInfo)
{
PropertyInfo propertyInfo = memberInfo as PropertyInfo;
memberType = propertyInfo.PropertyType;
}
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = memberInfo as FieldInfo;
memberType = fieldInfo.FieldType;
}
_layouter.AppendFormat("//Setting member {0}", memberInfo.Name);
//The primitive types are: Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Char, Double, Single
if (memberType.IsPrimitive || memberType == typeof(decimal))
{
switch (Type.GetTypeCode(memberType))
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.Int16:
case TypeCode.UInt32:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Decimal:
case TypeCode.Single:
case TypeCode.Double:
_layouter.Append("if( typeCode == AMF3TypeCode.Number )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = ({1})reader.ReadDouble();", memberInfo.Name, memberType.FullName);
_layouter.End();
_layouter.Append("else if( typeCode == AMF3TypeCode.Integer )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = ({1})reader.ReadAMF3Int();", memberInfo.Name, memberType.FullName);
_layouter.End();
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadAMF3Data(typeCode);");
_layouter.End();
break;
case TypeCode.Boolean:
_layouter.Append("if( typeCode == AMF3TypeCode.BooleanFalse )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = false;", memberInfo.Name);
_layouter.End();
_layouter.Append("else if( typeCode == AMF3TypeCode.BooleanTrue )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = true;", memberInfo.Name);
_layouter.End();
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadAMF3Data(typeCode);");
_layouter.End();
break;
case TypeCode.Char:
_layouter.Append("if( typeCode == AMF3TypeCode.String )");
_layouter.Append("{");
_layouter.Begin();
_layouter.AppendFormat("string str{0} = reader.ReadAMF3String();", memberInfo.Name);
_layouter.AppendFormat("if( str{0} != null && str{0} != string.Empty )", memberInfo.Name);
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = str{0}[0];", memberInfo.Name);
_layouter.End();
_layouter.End();
_layouter.Append("}");
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadAMF3Data(typeCode);");
_layouter.End();
break;
}
return;
}
if (memberType.IsEnum)
{
_layouter.Append("if( typeCode == AMF3TypeCode.String )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = ({1})Enum.Parse(typeof({1}), reader.ReadAMF3String(), true);", memberInfo.Name, memberType.FullName);
_layouter.End();
_layouter.Append("else if( typeCode == AMF3TypeCode.Integer )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = ({1})Enum.ToObject(typeof({1}), reader.ReadAMF3Int());", memberInfo.Name, memberType.FullName);
_layouter.End();
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadAMF3Data(typeCode);");
_layouter.End();
return;
}
if (memberType == typeof(DateTime))
{
_layouter.Append("if( typeCode == AMF3TypeCode.DateTime )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = reader.ReadAMF3Date();", memberInfo.Name);
_layouter.End();
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadAMF3Data(typeCode);");
_layouter.End();
return;
}
if (memberType == typeof(Guid))
{
_layouter.Append("if( typeCode == AMF3TypeCode.String )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = new Guid(reader.ReadAMF3String());", memberInfo.Name);
_layouter.End();
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadAMF3Data(typeCode);");
_layouter.End();
return;
}
if (memberType.IsValueType)
{
//structs are not handled
throw new FluorineException("Struct value types are not supported");
}
if (memberType == typeof(string))
{
_layouter.Append("if( typeCode == AMF3TypeCode.String )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = reader.ReadAMF3String();", memberInfo.Name);
_layouter.End();
_layouter.Append("else if( typeCode == AMF3TypeCode.Null )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = null;", memberInfo.Name);
_layouter.End();
_layouter.Append("else if( typeCode == AMF3TypeCode.Undefined )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = null;", memberInfo.Name);
_layouter.End();
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadAMF3Data(typeCode);");
_layouter.End();
return;
}
if (memberType == typeof(XmlDocument))
{
_layouter.Append("if( typeCode == AMF3TypeCode.Xml )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = reader.ReadAMF3XmlDocument();", memberInfo.Name);
_layouter.End();
_layouter.Append("else if( typeCode == AMF3TypeCode.Xml2 )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = reader.ReadAMF3XmlDocument();", memberInfo.Name);
_layouter.End();
_layouter.Append("else if( typeCode == AMF3TypeCode.Null )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = null;", memberInfo.Name);
_layouter.End();
_layouter.Append("else if( typeCode == AMF3TypeCode.Undefined )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = null;", memberInfo.Name);
_layouter.End();
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadAMF3Data(typeCode);");
_layouter.End();
return;
}
_layouter.AppendFormat("instance.{0} = ({1})TypeHelper.ChangeType(reader.ReadAMF3Data(typeCode), typeof({1}));", memberInfo.Name, TypeHelper.GetCSharpName(memberType));
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.Globalization;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Common.Logger;
namespace Alachisoft.NCache.Caching.Util
{
internal class OleDbConnectionPool : ResourcePool
{
internal class SqlDbResourceInfo : IDisposable
{
private OleDbConnection _conn;
private IDictionary _syncData;
public SqlDbResourceInfo(OleDbConnection conn)
{
_conn = conn;
}
#region / --- IDisposable --- /
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or
/// resetting unmanaged resources.
/// </summary>
void IDisposable.Dispose()
{
if(_conn != null)
{
lock (_conn)
{
_conn.Close();
_conn.Dispose();
_conn = null;
}
}
}
#endregion
public OleDbConnection Connection
{
get { return _conn; }
set { _conn = value; }
}
public IDictionary DbSyncInfo
{
get {return _syncData;}
set {_syncData = value;}
}
}
private ILogger _ncacheLog;
ILogger NCacheLog
{
get { return _ncacheLog; }
}
public OleDbConnectionPool(ILogger NCacheLog)
{
this._ncacheLog = NCacheLog;
}
/// <summary>
/// Adds a connection to the _connectionTable if already not present.
/// Otherwise, increments the referrence count for it.
/// </summary>
/// <param name="connectionString"></param>
/// <returns></returns>
public OleDbConnection PoolConnection(string connString, OleDbConnection connection)
{
lock (this)
{
string connKey = connString.ToLower();
SqlDbResourceInfo connInfo = (SqlDbResourceInfo)GetResource(connKey);
if (connInfo == null)
{
connection.Open();
connInfo = new SqlDbResourceInfo(connection);
AddResource(connKey, connInfo);
}
else
{
AddResource(connKey, null); // To increase the reference count
}
return connInfo.Connection;
}
}
/// <summary>
/// When connection is no more required, it is closed and removed from the
/// _connectionTable.
/// </summary>
/// <param name="connString"></param>
public void RemoveConnection(string connString)
{
lock (this)
{
RemoveResource(connString); //temporarily not removing connection instance.
}
}
/// <summary>
/// Wrapper for ResourcePool.GetResource(string key).
/// </summary>
/// <param name="connString"></param>
/// <returns></returns>
public OleDbConnection GetConnection(string connString)
{
lock (this)
{
SqlDbResourceInfo connInfo = (SqlDbResourceInfo) GetResource(connString);
if(connInfo != null)
return connInfo.Connection;
return null;
}
}
/// <summary>
/// Wrapper for ResourcePool.GetResource(string key).
/// </summary>
/// <param name="connString"></param>
/// <returns></returns>
public IDictionary GetResourceSyncInfo(string connString)
{
lock (this)
{
SqlDbResourceInfo connInfo = (SqlDbResourceInfo) GetResource(connString);
if(connInfo != null)
return connInfo.DbSyncInfo;
return null;
}
}
/// <summary>
/// Acquire the modified records in ncache_db_sync table
/// </summary>
/// <param name="syncTable"></param>
/// <param name="cacheName"></param>
public void AcquireSyncData(string syncTable, string cacheName)
{
lock (this)
{
IEnumerator em = Keys.GetEnumerator();
while (em.MoveNext())
{
SqlDbResourceInfo connInfo = (SqlDbResourceInfo) GetResource((string)em.Current);
IDictionary dbSyncInfo = LoadTableData(syncTable, cacheName, connInfo.Connection);
connInfo.DbSyncInfo = dbSyncInfo;
}
}
}
/// <summary>
/// Removes the modified records in ncache_db_sync table
/// </summary>
/// <param name="syncTable"></param>
/// <param name="cacheName"></param>
public void RemoveSyncData(string syncTable, string cacheName)
{
lock (this)
{
IEnumerator em = Keys.GetEnumerator();
while (em.MoveNext())
{
SqlDbResourceInfo connInfo = (SqlDbResourceInfo)GetResource((string)em.Current);
RemoveTableData(syncTable, cacheName, connInfo.Connection);
connInfo.DbSyncInfo = null;
}
}
}
/// <summary>
/// Remove all the stored sync information
/// </summary>
public void FlushSyncData()
{
lock (this)
{
IEnumerator em = Keys.GetEnumerator();
while (em.MoveNext())
{
SqlDbResourceInfo connInfo = (SqlDbResourceInfo) GetResource((string)em.Current);
connInfo.DbSyncInfo = null;
}
}
}
/// <summary>
/// Load the modified records for the given cache and set these flags to false
/// </summary>
/// <returns></returns>
private Hashtable LoadTableData(string syncTable, string cacheName, OleDbConnection connection)
{
object[] tableInfo = new object[] { syncTable, cacheName };
Hashtable tableData = new Hashtable();
OleDbDataReader reader = null;
OleDbCommand command = null;
string cacheKey = "";
bool modified = false;
bool hasRows = false;
lock (connection)
{
var transaction = connection.BeginTransaction(System.Data.IsolationLevel.RepeatableRead);
try
{
if (connection.State != ConnectionState.Open)
connection.Open();
command = connection.CreateCommand();
command.CommandText = string.Format(CultureInfo.InvariantCulture, "UPDATE {0} SET WORK_IN_PROGRESS = 1 WHERE CACHE_ID = '{1}' AND MODIFIED = 1", tableInfo);
command.CommandType = CommandType.Text;
command.Transaction = transaction;
reader = command.ExecuteReader();
}
catch (Exception ex)
{
NCacheLog.Error(cacheName, ex.ToString());
transaction.Rollback();
return null;
}
finally
{
if (reader != null)
{
reader.Close();
reader.Dispose();
reader = null;
}
if (command != null)
{
command.Dispose();
command = null;
}
}
try
{
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
command = connection.CreateCommand();
command.CommandText = string.Format(CultureInfo.InvariantCulture, "SELECT CACHE_KEY, MODIFIED FROM {0} WHERE CACHE_ID = '{1}' AND WORK_IN_PROGRESS = 1", tableInfo);
command.CommandType = CommandType.Text;
command.Transaction = transaction;
reader = command.ExecuteReader();
hasRows = reader.HasRows;
while (reader.Read())
{
cacheKey = Convert.ToString(reader.GetValue(0));
modified = Convert.ToBoolean(reader.GetValue(1));
tableData.Add(cacheKey, modified);
}
}
catch (Exception ex)
{
NCacheLog.Error(cacheName, ex.ToString());
transaction.Rollback();
return null;
}
finally
{
if (reader != null)
{
reader.Close();
reader.Dispose();
reader = null;
}
if (command != null)
{
command.Dispose();
command = null;
}
}
transaction.Commit();
}
return tableData;
}
/// <summary>
/// Remove the modified records from ncache_db_sync
/// </summary>
/// <param name="syncTable"></param>
/// <param name="cacheName"></param>
/// <param name="connection"></param>
/// <returns></returns>
private bool RemoveTableData(string syncTable, string cacheName, OleDbConnection connection)
{
object[] tableInfo = new object[] { syncTable, cacheName };
OleDbCommand command = null;
lock (connection)
{
try
{
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
command = connection.CreateCommand();
command.CommandText = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0} WHERE CACHE_ID = '{1}' AND WORK_IN_PROGRESS = 1", tableInfo);
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
NCacheLog.Error(cacheName, ex.ToString());
return false;
}
finally
{
if (command != null)
{
command.Dispose();
command = null;
}
}
}
}
/// <summary>
/// Gets the keys which have been modified in the database.
/// call this method after acquiring the latest database state.
/// </summary>
/// <returns> array list of all the modified keys. </returns>
internal ArrayList GetExpiredKeys()
{
ArrayList keys = new ArrayList();
lock (this)
{
IEnumerator em = Keys.GetEnumerator();
while (em.MoveNext())
{
SqlDbResourceInfo connInfo = (SqlDbResourceInfo)GetResource((string)em.Current);
if (connInfo != null && connInfo.DbSyncInfo != null)
{
keys.AddRange(connInfo.DbSyncInfo.Keys);
connInfo.DbSyncInfo = null;
}
}
}
return keys;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using bv.winclient.Core;
using DevExpress.XtraPrinting;
using DevExpress.XtraReports.UI;
using eidss.model.Model;
using eidss.model.Model.Report;
namespace EIDSS.Reports.Flexible.Visitors
{
public class ReportVisitor : FlexNodeVisitor
{
private const int MaxSubreportHeight = 700;
public Dictionary<int, int> LevelFont { get; set; }
public override void Visit(FlexNodeReport node)
{
// create subreport for root node and for non-leaf node
if (node.IsRoot)
{
var report = new FlexReport();
node.AssignedControl = report;
}
else
{
if ((node.Count != 0) && (!(node.DataItem is FlexTableItem)))
{
var childReport = new FlexReport();
node.AssignedControl = childReport;
if (node.DataItem is FlexLabelItem)
{
var labelItem = ((FlexLabelItem) node.DataItem);
childReport.Text = labelItem.Text;
childReport.Font = new Font(CurrentFontName,
labelItem.FontSize + ReportSettings.DeltaFontSize - GetDeltaFontForNode(node),
(FontStyle) labelItem.FontStyle | FontStyle.Bold);
}
MakeControlsLink(node);
}
else
{
if (node.DataItem is FlexTableItem)
{
var parentControl = (XRControl) ((FlexNodeReport) node.ParentNode).AssignedControl;
if (TableVisitor.IsNodeHasTableParent(node) && !(parentControl is FlexTable))
{
throw new ApplicationException("Non-root table node should have parent of type XRTableRow");
}
var table = new FlexTable();
var tableItem = ((FlexTableItem) node.DataItem);
if (!TableVisitor.IsNodeHasTableParent(node))
{
var childReport = new FlexReport();
node.AssignedControl = childReport;
childReport.Text = string.Empty;
MakeControlsLink(node);
parentControl = childReport.HeaderBand;
}
else
{
table.Borders = BorderSide.Right | BorderSide.Bottom;
var parentTable = ((FlexTable) parentControl);
parentControl = CreateParentCell(parentTable, node);
table.Height = parentControl.Height;
}
table.HeaderCell.Text = tableItem.Text;
// Note: uncomment for debug
//table.HeaderCell.Text = string.Format("({0}) {1}", node.DataItem.Width, tableItem.Text);
table.HeaderCell.Font = new Font(CurrentFontName,
WinClientContext.CurrentFont.Size,
FontStyle.Regular);
table.Width = node.DataItem.Width;
parentControl.Controls.Add(table);
node.AssignedControl = table;
}
else if (node.DataItem is FlexLabelItem)
{
var nd = (FlexNodeReport) node.ParentNode;
var label = nd.AssignedControl is FlexTable
? CreateParentCell((FlexTable) nd.AssignedControl, node)
: new XRLabel();
var labelItem = (FlexLabelItem) node.DataItem;
label.Padding = new PaddingInfo(ReportSettings.Padding, ReportSettings.Padding, 0, 0, 100F);
label.Text = labelItem.Text;
// Note: uncomment for debug
// label.Text = string.Format("({0}) {1}", node.DataItem.Width, labelItem.Text);
label.Font = new Font(CurrentFontName,
labelItem.FontSize - GetDeltaFontForNode(node),
(FontStyle) labelItem.FontStyle);
label.ForeColor = labelItem.Color;
if (labelItem.IsParameterValue)
{
label.Borders = BorderSide.Bottom;
string toMeasure = string.IsNullOrEmpty(label.Text) ? "X" : label.Text;
SizeF size = WinUtils.MeasureString(toMeasure, label.Font, labelItem.Width);
if (labelItem.Height > size.Height)
{
labelItem.Height = (int) size.Height;
}
}
//Note: [ivan] uncomment for debug
//label.Borders = BorderSide.All;
//
node.AssignedControl = label;
if (!(((FlexNodeReport) node.ParentNode).AssignedControl is FlexTable))
{
MakeControlsLink(node);
}
}
}
}
}
private static XRTableCell CreateParentCell(FlexTable parentTable, FlexNodeBase node)
{
var parentCell = new XRTableCell();
parentCell.StylePriority.UseBorders = false;
parentCell.Width = node.DataItem.Width;
var parentRow = parentTable.InnerRow;
var levelVisitor = new LevelVisitor();
((FlexNodeReport) node.ParentNode).AcceptForward(levelVisitor);
parentRow.Cells.Add(parentCell);
return parentCell;
}
private int GetDeltaFontForNode(FlexNodeBase node)
{
return (LevelFont != null) && (LevelFont.ContainsKey(node.Level))
? LevelFont[node.Level]
: 0;
}
private static void MakeControlsLink(FlexNodeReport node)
{
if (!node.IsRoot && node.DataItem != null)
{
var nd = (FlexNodeReport) node.ParentNode;
var parentControl = (XRControl) nd.AssignedControl;
if (nd.AssignedControl is FlexReport)
{
var parentReport = ((FlexReport) nd.AssignedControl);
parentControl = parentReport.DetailBand;
}
// Calculate delta for summary height of subreports below.
//it needs because real subreport height not equal to corresponding node.DataItem.Height
int delta = 0;
foreach (var subreport in parentControl.Controls.OfType<XRSubreport>())
{
var otherChild = node.ParentNode.ChildList.SingleOrDefault(
n => ((XRControl) ((FlexNodeReport) n).AssignedControl) == subreport.ReportSource);
if (otherChild != null)
{
delta += subreport.Height - otherChild.DataItem.Height;
}
}
if (node.AssignedControl is FlexReport)
{
var childReport = (FlexReport) node.AssignedControl;
childReport.Width = node.DataItem.Width;
var currentSubreport = new XRSubreport
{
Location = new Point(node.DataItem.Left, node.DataItem.Top + delta),
Size = new Size(node.DataItem.Width, Math.Min(MaxSubreportHeight, node.DataItem.Height)),
ReportSource = childReport
};
parentControl.Controls.Add(currentSubreport);
}
else
{
var ctrl = (XRControl) node.AssignedControl;
ctrl.Left = node.DataItem.Left;
ctrl.Top = node.DataItem.Top + delta;
ctrl.Width = node.DataItem.Width;
ctrl.Height = node.DataItem.Height;
parentControl.Controls.Add(ctrl);
}
}
}
}
}
| |
// 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.Speech.V1P1Beta1.Snippets
{
using Google.Api.Gax.Grpc;
using Google.LongRunning;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedSpeechClientSnippets
{
/// <summary>Snippet for Recognize</summary>
public void RecognizeRequestObject()
{
// Snippet: Recognize(RecognizeRequest, CallSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize request argument(s)
RecognizeRequest request = new RecognizeRequest
{
Config = new RecognitionConfig(),
Audio = new RecognitionAudio(),
};
// Make the request
RecognizeResponse response = speechClient.Recognize(request);
// End snippet
}
/// <summary>Snippet for RecognizeAsync</summary>
public async Task RecognizeRequestObjectAsync()
{
// Snippet: RecognizeAsync(RecognizeRequest, CallSettings)
// Additional: RecognizeAsync(RecognizeRequest, CancellationToken)
// Create client
SpeechClient speechClient = await SpeechClient.CreateAsync();
// Initialize request argument(s)
RecognizeRequest request = new RecognizeRequest
{
Config = new RecognitionConfig(),
Audio = new RecognitionAudio(),
};
// Make the request
RecognizeResponse response = await speechClient.RecognizeAsync(request);
// End snippet
}
/// <summary>Snippet for Recognize</summary>
public void Recognize()
{
// Snippet: Recognize(RecognitionConfig, RecognitionAudio, CallSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize request argument(s)
RecognitionConfig config = new RecognitionConfig();
RecognitionAudio audio = new RecognitionAudio();
// Make the request
RecognizeResponse response = speechClient.Recognize(config, audio);
// End snippet
}
/// <summary>Snippet for RecognizeAsync</summary>
public async Task RecognizeAsync()
{
// Snippet: RecognizeAsync(RecognitionConfig, RecognitionAudio, CallSettings)
// Additional: RecognizeAsync(RecognitionConfig, RecognitionAudio, CancellationToken)
// Create client
SpeechClient speechClient = await SpeechClient.CreateAsync();
// Initialize request argument(s)
RecognitionConfig config = new RecognitionConfig();
RecognitionAudio audio = new RecognitionAudio();
// Make the request
RecognizeResponse response = await speechClient.RecognizeAsync(config, audio);
// End snippet
}
/// <summary>Snippet for LongRunningRecognize</summary>
public void LongRunningRecognizeRequestObject()
{
// Snippet: LongRunningRecognize(LongRunningRecognizeRequest, CallSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize request argument(s)
LongRunningRecognizeRequest request = new LongRunningRecognizeRequest
{
Config = new RecognitionConfig(),
Audio = new RecognitionAudio(),
OutputConfig = new TranscriptOutputConfig(),
};
// Make the request
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = speechClient.LongRunningRecognize(request);
// Poll until the returned long-running operation is complete
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
LongRunningRecognizeResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = speechClient.PollOnceLongRunningRecognize(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for LongRunningRecognizeAsync</summary>
public async Task LongRunningRecognizeRequestObjectAsync()
{
// Snippet: LongRunningRecognizeAsync(LongRunningRecognizeRequest, CallSettings)
// Additional: LongRunningRecognizeAsync(LongRunningRecognizeRequest, CancellationToken)
// Create client
SpeechClient speechClient = await SpeechClient.CreateAsync();
// Initialize request argument(s)
LongRunningRecognizeRequest request = new LongRunningRecognizeRequest
{
Config = new RecognitionConfig(),
Audio = new RecognitionAudio(),
OutputConfig = new TranscriptOutputConfig(),
};
// Make the request
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = await speechClient.LongRunningRecognizeAsync(request);
// Poll until the returned long-running operation is complete
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
LongRunningRecognizeResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = await speechClient.PollOnceLongRunningRecognizeAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for LongRunningRecognize</summary>
public void LongRunningRecognize()
{
// Snippet: LongRunningRecognize(RecognitionConfig, RecognitionAudio, CallSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize request argument(s)
RecognitionConfig config = new RecognitionConfig();
RecognitionAudio audio = new RecognitionAudio();
// Make the request
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = speechClient.LongRunningRecognize(config, audio);
// Poll until the returned long-running operation is complete
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
LongRunningRecognizeResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = speechClient.PollOnceLongRunningRecognize(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for LongRunningRecognizeAsync</summary>
public async Task LongRunningRecognizeAsync()
{
// Snippet: LongRunningRecognizeAsync(RecognitionConfig, RecognitionAudio, CallSettings)
// Additional: LongRunningRecognizeAsync(RecognitionConfig, RecognitionAudio, CancellationToken)
// Create client
SpeechClient speechClient = await SpeechClient.CreateAsync();
// Initialize request argument(s)
RecognitionConfig config = new RecognitionConfig();
RecognitionAudio audio = new RecognitionAudio();
// Make the request
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = await speechClient.LongRunningRecognizeAsync(config, audio);
// Poll until the returned long-running operation is complete
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
LongRunningRecognizeResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = await speechClient.PollOnceLongRunningRecognizeAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for StreamingRecognize</summary>
public async Task StreamingRecognize()
{
// Snippet: StreamingRecognize(CallSettings, BidirectionalStreamingSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize streaming call, retrieving the stream object
SpeechClient.StreamingRecognizeStream response = speechClient.StreamingRecognize();
// Sending requests and retrieving responses can be arbitrarily interleaved
// Exact sequence will depend on client/server behavior
// Create task to do something with responses from server
Task responseHandlerTask = Task.Run(async () =>
{
// Note that C# 8 code can use await foreach
AsyncResponseStream<StreamingRecognizeResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
StreamingRecognizeResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
});
// Send requests to the server
bool done = false;
while (!done)
{
// Initialize a request
StreamingRecognizeRequest request = new StreamingRecognizeRequest
{
StreamingConfig = new StreamingRecognitionConfig(),
};
// Stream a request to the server
await response.WriteAsync(request);
// Set "done" to true when sending requests is complete
}
// Complete writing requests to the stream
await response.WriteCompleteAsync();
// Await the response handler
// This will complete once all server responses have been processed
await responseHandlerTask;
// End snippet
}
}
}
| |
//---------------------------------------------------------------------------
//
// File: HtmlParser.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Parser for Html-to-Xaml converter
//
//---------------------------------------------------------------------------
using System;
using System.Xml;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text; // StringBuilder
// important TODOS:
// TODO 1. Start tags: The ParseXmlElement function has been modified to be called after both the
// angle bracket < and element name have been read, instead of just the < bracket and some valid name character,
// previously the case. This change was made so that elements with optional closing tags could read a new
// element's start tag and decide whether they were required to close. However, there is a question of whether to
// handle this in the parser or lexical analyzer. It is currently handled in the parser - the lexical analyzer still
// recognizes a start tag opener as a '<' + valid name start char; it is the parser that reads the actual name.
// this is correct behavior assuming that the name is a valid html name, because the lexical analyzer should not know anything
// about optional closing tags, etc. UPDATED: 10/13/2004: I am updating this to read the whole start tag of something
// that is not an HTML, treat it as empty, and add it to the tree. That way the converter will know it's there, but
// it will hvae no content. We could also partially recover by trying to look up and match names if they are similar
// TODO 2. Invalid element names: However, it might make sense to give the lexical analyzer the ability to identify
// a valid html element name and not return something as a start tag otherwise. For example, if we type <good>, should
// the lexical analyzer return that it has found the start of an element when this is not the case in HTML? But this will
// require implementing a lookahead token in the lexical analyzer so that it can treat an invalid element name as text. One
// character of lookahead will not be enough.
// TODO 3. Attributes: The attribute recovery is poor when reading attribute values in quotes - if no closing quotes are found,
// the lexical analyzer just keeps reading and if it eventually reaches the end of file, it would have just skipped everything.
// There are a couple of ways to deal with this: 1) stop reading attributes when we encounter a '>' character - this doesn't allow
// the '>' character to be used in attribute values, but it can still be used as an entity. 2) Maintain a HTML-specific list
// of attributes and their values that each html element can take, and if we find correct attribute namesand values for an
// element we use them regardless of the quotes, this way we could just ignore something invalid. One more option: 3) Read ahead
// in the quoted value and if we find an end of file, we can return to where we were and process as text. However this requires
// a lot of lookahead and a resettable reader.
// TODO 4: elements with optional closing tags: For elements with optional closing tags, we always close the element if we find
// that one of it's ancestors has closed. This condition may be too broad and we should develop a better heuristic. We should also
// improve the heuristics for closing certain elements when the next element starts
// TODO 5. Nesting: Support for unbalanced nesting, e.g. <b> <i> </b> </i>: this is not presently supported. To support it we may need
// to maintain two xml elements, one the element that represents what has already been read and another represents what we are presently reading.
// Then if we encounter an unbalanced nesting tag we could close the element that was supposed to close, save the current element
// and store it in the list of already-read content, and then open a new element to which all tags that are currently open
// can be applied. Is there a better way to do this? Should we do it at all?
// TODO 6. Elements with optional starting tags: there are 4 such elements in the HTML 4 specification - html, tbody, body and head.
// The current recovery doesn;t do anything for any of these elements except the html element, because it's not critical - head
// and body elementscan be contained within html element, and tbody is contained within table. To extend this for XHTML
// extensions, and to recover in case other elements are missing start tags, we would need to insert an extra recursive call
// to ParseXmlElement for the missing start tag. It is suggested to do this by giving ParseXmlElement an argument that specifies
// a name to use. If this argument is null, it assumes its name is the next token from the lexical analyzer and continues
// exactly as it does now. However, if the argument contains a valid html element name then it takes that value as its name
// and continues as before. This way, if the next token is the element that should actually be its child, it will see
// the name in the next step and initiate a recursive call. We would also need to add some logic in the loop for when a start tag
// is found - if the start tag is not compatible with current context and indicates that a start tag has been missed, then we
// can initiate the extra recursive call and give it the name of the missed start tag. The issues are when to insert this logic,
// and if we want to support it over multiple missing start tags. If we insert it at the time a start tag is read in element
// text, then we can support only one missing start tag, since the extra call will read the next start tag and make a recursive
// call without checking the context. This is a conceptual problem, and the check should be made just before a recursive call,
// with the choice being whether we should supply an element name as argument, or leave it as NULL and read from the input
// TODO 7: Context: Is it appropriate to keep track of context here? For example, should we only expect td, tr elements when
// reading a table and ignore them otherwise? This may be too much of a load on the parser, I think it's better if the converter
// deals with it
namespace HTMLConverter
{
/// <summary>
/// HtmlParser class accepts a string of possibly badly formed Html, parses it and returns a string
/// of well-formed Html that is as close to the original string in content as possible
/// </summary>
internal class HtmlParser
{
// ---------------------------------------------------------------------
//
// Constructors
//
// ---------------------------------------------------------------------
#region Constructors
/// <summary>
/// Constructor. Initializes the _htmlLexicalAnalayzer element with the given input string
/// </summary>
/// <param name="inputString">
/// string to parsed into well-formed Html
/// </param>
private HtmlParser(string inputString)
{
// Create an output xml document
_document = new XmlDocument();
// initialize open tag stack
_openedElements = new Stack<XmlElement>();
_pendingInlineElements = new Stack<XmlElement>();
// initialize lexical analyzer
_htmlLexicalAnalyzer = new HtmlLexicalAnalyzer(inputString);
// get first token from input, expecting text
_htmlLexicalAnalyzer.GetNextContentToken();
}
#endregion Constructors
// ---------------------------------------------------------------------
//
// Internal Methods
//
// ---------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// Instantiates an HtmlParser element and calls the parsing function on the given input string
/// </summary>
/// <param name="htmlString">
/// Input string of pssibly badly-formed Html to be parsed into well-formed Html
/// </param>
/// <returns>
/// XmlElement rep
/// </returns>
internal static XmlElement ParseHtml(string htmlString)
{
HtmlParser htmlParser = new HtmlParser(htmlString);
XmlElement htmlRootElement = htmlParser.ParseHtmlContent();
return htmlRootElement;
}
// .....................................................................
//
// Html Header on Clipboard
//
// .....................................................................
// Html header structure.
// Version:1.0
// StartHTML:000000000
// EndHTML:000000000
// StartFragment:000000000
// EndFragment:000000000
// StartSelection:000000000
// EndSelection:000000000
internal const string HtmlHeader = "Version:1.0\r\nStartHTML:{0:D10}\r\nEndHTML:{1:D10}\r\nStartFragment:{2:D10}\r\nEndFragment:{3:D10}\r\nStartSelection:{4:D10}\r\nEndSelection:{5:D10}\r\n";
internal const string HtmlStartFragmentComment = "<!--StartFragment-->";
internal const string HtmlEndFragmentComment = "<!--EndFragment-->";
/// <summary>
/// Extracts Html string from clipboard data by parsing header information in htmlDataString
/// </summary>
/// <param name="htmlDataString">
/// String representing Html clipboard data. This includes Html header
/// </param>
/// <returns>
/// String containing only the Html data part of htmlDataString, without header
/// </returns>
internal static string ExtractHtmlFromClipboardData(string htmlDataString)
{
int startHtmlIndex = htmlDataString.IndexOf("StartHTML:");
if (startHtmlIndex < 0)
{
return "ERROR: Urecognized html header";
}
// TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length),
// which could be wrong assumption. We need to implement more flrxible parsing here
startHtmlIndex = Int32.Parse(htmlDataString.Substring(startHtmlIndex + "StartHTML:".Length, "0123456789".Length));
if (startHtmlIndex < 0 || startHtmlIndex > htmlDataString.Length)
{
return "ERROR: Urecognized html header";
}
int endHtmlIndex = htmlDataString.IndexOf("EndHTML:");
if (endHtmlIndex < 0)
{
return "ERROR: Urecognized html header";
}
// TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length),
// which could be wrong assumption. We need to implement more flrxible parsing here
endHtmlIndex = Int32.Parse(htmlDataString.Substring(endHtmlIndex + "EndHTML:".Length, "0123456789".Length));
if (endHtmlIndex > htmlDataString.Length)
{
endHtmlIndex = htmlDataString.Length;
}
return htmlDataString.Substring(startHtmlIndex, endHtmlIndex - startHtmlIndex);
}
/// <summary>
/// Adds Xhtml header information to Html data string so that it can be placed on clipboard
/// </summary>
/// <param name="htmlString">
/// Html string to be placed on clipboard with appropriate header
/// </param>
/// <returns>
/// String wrapping htmlString with appropriate Html header
/// </returns>
internal static string AddHtmlClipboardHeader(string htmlString)
{
StringBuilder stringBuilder = new StringBuilder();
// each of 6 numbers is represented by "{0:D10}" in the format string
// must actually occupy 10 digit positions ("0123456789")
int startHTML = HtmlHeader.Length + 6 * ("0123456789".Length - "{0:D10}".Length);
int endHTML = startHTML + htmlString.Length;
int startFragment = htmlString.IndexOf(HtmlStartFragmentComment, 0);
if (startFragment >= 0)
{
startFragment = startHTML + startFragment + HtmlStartFragmentComment.Length;
}
else
{
startFragment = startHTML;
}
int endFragment = htmlString.IndexOf(HtmlEndFragmentComment, 0);
if (endFragment >= 0)
{
endFragment = startHTML + endFragment;
}
else
{
endFragment = endHTML;
}
// Create HTML clipboard header string
stringBuilder.AppendFormat(HtmlHeader, startHTML, endHTML, startFragment, endFragment, startFragment, endFragment);
// Append HTML body.
stringBuilder.Append(htmlString);
return stringBuilder.ToString();
}
#endregion Internal Methods
// ---------------------------------------------------------------------
//
// Private methods
//
// ---------------------------------------------------------------------
#region Private Methods
private void InvariantAssert(bool condition, string message)
{
if (!condition)
{
throw new Exception("Assertion error: " + message);
}
}
/// <summary>
/// Parses the stream of html tokens starting
/// from the name of top-level element.
/// Returns XmlElement representing the top-level
/// html element
/// </summary>
private XmlElement ParseHtmlContent()
{
// Create artificial root elelemt to be able to group multiple top-level elements
// We create "html" element which may be a duplicate of real HTML element, which is ok, as HtmlConverter will swallow it painlessly..
XmlElement htmlRootElement = _document.CreateElement("html", XhtmlNamespace);
OpenStructuringElement(htmlRootElement);
while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EOF)
{
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.OpeningTagStart)
{
_htmlLexicalAnalyzer.GetNextTagToken();
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
string htmlElementName = _htmlLexicalAnalyzer.NextToken.ToLower();
_htmlLexicalAnalyzer.GetNextTagToken();
// Create an element
XmlElement htmlElement = _document.CreateElement(htmlElementName, XhtmlNamespace);
// Parse element attributes
ParseAttributes(htmlElement);
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.EmptyTagEnd || HtmlSchema.IsEmptyElement(htmlElementName))
{
// It is an element without content (because of explicit slash or based on implicit knowledge aboout html)
AddEmptyElement(htmlElement);
}
else if (HtmlSchema.IsInlineElement(htmlElementName))
{
// Elements known as formatting are pushed to some special
// pending stack, which allows them to be transferred
// over block tags - by doing this we convert
// overlapping tags into normal heirarchical element structure.
OpenInlineElement(htmlElement);
}
else if (HtmlSchema.IsBlockElement(htmlElementName) || HtmlSchema.IsKnownOpenableElement(htmlElementName))
{
// This includes no-scope elements
OpenStructuringElement(htmlElement);
}
else
{
// Do nothing. Skip the whole opening tag.
// Ignoring all unknown elements on their start tags.
// Thus we will ignore them on closinng tag as well.
// Anyway we don't know what to do withthem on conversion to Xaml.
}
}
else
{
// Note that the token following opening angle bracket must be a name - lexical analyzer must guarantee that.
// Otherwise - we skip the angle bracket and continue parsing the content as if it is just text.
// Add the following asserion here, right? or output "<" as a text run instead?:
// InvariantAssert(false, "Angle bracket without a following name is not expected");
}
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.ClosingTagStart)
{
_htmlLexicalAnalyzer.GetNextTagToken();
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
string htmlElementName = _htmlLexicalAnalyzer.NextToken.ToLower();
// Skip the name token. Assume that the following token is end of tag,
// but do not check this. If it is not true, we simply ignore one token
// - this is our recovery from bad xml in this case.
_htmlLexicalAnalyzer.GetNextTagToken();
CloseElement(htmlElementName);
}
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Text)
{
AddTextContent(_htmlLexicalAnalyzer.NextToken);
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Comment)
{
AddComment(_htmlLexicalAnalyzer.NextToken);
}
_htmlLexicalAnalyzer.GetNextContentToken();
}
// Get rid of the artificial root element
if (htmlRootElement.FirstChild is XmlElement &&
htmlRootElement.FirstChild == htmlRootElement.LastChild &&
htmlRootElement.FirstChild.LocalName.ToLower() == "html")
{
htmlRootElement = (XmlElement)htmlRootElement.FirstChild;
}
return htmlRootElement;
}
private XmlElement CreateElementCopy(XmlElement htmlElement)
{
XmlElement htmlElementCopy = _document.CreateElement(htmlElement.LocalName, XhtmlNamespace);
for (int i = 0; i < htmlElement.Attributes.Count; i++)
{
XmlAttribute attribute = htmlElement.Attributes[i];
htmlElementCopy.SetAttribute(attribute.Name, attribute.Value);
}
return htmlElementCopy;
}
private void AddEmptyElement(XmlElement htmlEmptyElement)
{
InvariantAssert(_openedElements.Count > 0, "AddEmptyElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlEmptyElement);
}
private void OpenInlineElement(XmlElement htmlInlineElement)
{
_pendingInlineElements.Push(htmlInlineElement);
}
// Opens structurig element such as Div or Table etc.
private void OpenStructuringElement(XmlElement htmlElement)
{
// Close all pending inline elements
// All block elements are considered as delimiters for inline elements
// which forces all inline elements to be closed and re-opened in the following
// structural element (if any).
// By doing that we guarantee that all inline elements appear only within most nested blocks
if (HtmlSchema.IsBlockElement(htmlElement.LocalName))
{
while (_openedElements.Count > 0 && HtmlSchema.IsInlineElement(_openedElements.Peek().LocalName))
{
XmlElement htmlInlineElement = _openedElements.Pop();
InvariantAssert(_openedElements.Count > 0, "OpenStructuringElement: stack of opened elements cannot become empty here");
_pendingInlineElements.Push(CreateElementCopy(htmlInlineElement));
}
}
// Add this block element to its parent
if (_openedElements.Count > 0)
{
XmlElement htmlParent = _openedElements.Peek();
// Check some known block elements for auto-closing (LI and P)
if (HtmlSchema.ClosesOnNextElementStart(htmlParent.LocalName, htmlElement.LocalName))
{
_openedElements.Pop();
htmlParent = _openedElements.Count > 0 ? _openedElements.Peek() : null;
}
if (htmlParent != null)
{
// NOTE:
// Actually we never expect null - it would mean two top-level P or LI (without a parent).
// In such weird case we will loose all paragraphs except the first one...
htmlParent.AppendChild(htmlElement);
}
}
// Push it onto a stack
_openedElements.Push(htmlElement);
}
private bool IsElementOpened(string htmlElementName)
{
foreach (XmlElement openedElement in _openedElements)
{
if (openedElement.LocalName == htmlElementName)
{
return true;
}
}
return false;
}
private void CloseElement(string htmlElementName)
{
// Check if the element is opened and already added to the parent
InvariantAssert(_openedElements.Count > 0, "CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
// Check if the element is opened and still waiting to be added to the parent
if (_pendingInlineElements.Count > 0 && _pendingInlineElements.Peek().LocalName == htmlElementName)
{
// Closing an empty inline element.
// Note that HtmlConverter will skip empty inlines, but for completeness we keep them here on parser level.
XmlElement htmlInlineElement = _pendingInlineElements.Pop();
InvariantAssert(_openedElements.Count > 0, "CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlInlineElement);
return;
}
else if (IsElementOpened(htmlElementName))
{
while (_openedElements.Count > 1) // we never pop the last element - the artificial root
{
// Close all unbalanced elements.
XmlElement htmlOpenedElement = _openedElements.Pop();
if (htmlOpenedElement.LocalName == htmlElementName)
{
return;
}
if (HtmlSchema.IsInlineElement(htmlOpenedElement.LocalName))
{
// Unbalances Inlines will be transfered to the next element content
_pendingInlineElements.Push(CreateElementCopy(htmlOpenedElement));
}
}
}
// If element was not opened, we simply ignore the unbalanced closing tag
return;
}
private void AddTextContent(string textContent)
{
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0, "AddTextContent: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
XmlText textNode = _document.CreateTextNode(textContent);
htmlParent.AppendChild(textNode);
}
private void AddComment(string comment)
{
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0, "AddComment: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
XmlComment xmlComment = _document.CreateComment(comment);
htmlParent.AppendChild(xmlComment);
}
// Moves all inline elements pending for opening to actual document
// and adds them to current open stack.
private void OpenPendingInlineElements()
{
if (_pendingInlineElements.Count > 0)
{
XmlElement htmlInlineElement = _pendingInlineElements.Pop();
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0, "OpenPendingInlineElements: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlInlineElement);
_openedElements.Push(htmlInlineElement);
}
}
private void ParseAttributes(XmlElement xmlElement)
{
while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EOF && //
_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.TagEnd && //
_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EmptyTagEnd)
{
// read next attribute (name=value)
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
string attributeName = _htmlLexicalAnalyzer.NextToken;
_htmlLexicalAnalyzer.GetNextEqualSignToken();
_htmlLexicalAnalyzer.GetNextAtomToken();
string attributeValue = _htmlLexicalAnalyzer.NextToken;
try
{
xmlElement.SetAttribute(attributeName, attributeValue);
}
catch(XmlException)
{
}
}
_htmlLexicalAnalyzer.GetNextTagToken();
}
}
#endregion Private Methods
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
#region Private Fields
internal const string XhtmlNamespace = "http://www.w3.org/1999/xhtml";
private HtmlLexicalAnalyzer _htmlLexicalAnalyzer;
// document from which all elements are created
private XmlDocument _document;
// stack for open elements
Stack<XmlElement> _openedElements;
Stack<XmlElement> _pendingInlineElements;
#endregion Private Fields
}
}
| |
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;
namespace EdiEngine.Standards.X12_004010.Maps
{
public class M_138 : MapLoop
{
public M_138() : base(null)
{
Content.AddRange(new MapBaseEntity[] {
new BGN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new ERP() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new L_N1(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 2 },
new L_IN1(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 10 },
new L_TST(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
new L_DEG(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new L_SST(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new L_PCL(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new L_ATV(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
//1000
public class L_N1 : MapLoop
{
public L_N1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2000
public class L_IN1 : MapLoop
{
public L_IN1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new IN1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new IN2() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 10 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new IND() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new LUI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new COM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new RQS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new SCA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_EMS(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
//2100
public class L_EMS : MapLoop
{
public L_EMS(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new EMS() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//3000
public class L_TST : MapLoop
{
public L_TST(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new TST() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new L_SBT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//3100
public class L_SBT : MapLoop
{
public L_SBT(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SBT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new SRE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_RAP(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_SCA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//3110
public class L_RAP : MapLoop
{
public L_RAP(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new RAP() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new EMS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//3120
public class L_SCA : MapLoop
{
public L_SCA(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SCA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new FOS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//3130
public class L_N1_1 : MapLoop
{
public L_N1_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//4000
public class L_DEG : MapLoop
{
public L_DEG(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new DEG() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new FOS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
});
}
}
//5000
public class L_SST : MapLoop
{
public L_SST(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SST() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new SSE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new SUM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new FOS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_N1_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//5100
public class L_N1_2 : MapLoop
{
public L_N1_2(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//6000
public class L_PCL : MapLoop
{
public L_PCL(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new PCL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new SSE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new FOS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_DEG_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
//6100
public class L_DEG_1 : MapLoop
{
public L_DEG_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new DEG() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new SUM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new FOS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 30 },
});
}
}
//7000
public class L_ATV : MapLoop
{
public L_ATV(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new ATV() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new EMS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;
using System.Threading;
using Xunit;
using System.Diagnostics.Tracing;
using System.Text.RegularExpressions;
using System.Diagnostics;
using SdtEventSources;
namespace BasicEventSourceTests
{
public class TestsWriteEvent
{
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
/// <summary>
/// Tests WriteEvent using the manifest based mechanism.
/// Tests the ETW path.
/// </summary>
[Fact]
public void Test_WriteEvent_Manifest_ETW()
{
using (var listener = new EtwListener())
{
Test_WriteEvent(listener, false);
}
}
#endif // USE_ETW
/// <summary>
/// Tests WriteEvent using the manifest based mechanism.
/// Tests bTraceListener path.
/// </summary>
[Fact]
public void Test_WriteEvent_Manifest_EventListener()
{
using (var listener = new EventListenerListener())
{
Test_WriteEvent(listener, false);
}
}
/// <summary>
/// Tests WriteEvent using the manifest based mechanism.
/// Tests bTraceListener path using events instead of virtual callbacks.
/// </summary>
[Fact]
public void Test_WriteEvent_Manifest_EventListener_UseEvents()
{
Test_WriteEvent(new EventListenerListener(true), false);
}
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
/// <summary>
/// Tests WriteEvent using the self-describing mechanism.
/// Tests both the ETW and TraceListener paths.
/// </summary>
[Fact]
public void Test_WriteEvent_SelfDescribing_ETW()
{
using (var listener = new EtwListener())
{
Test_WriteEvent(listener, true);
}
}
#endif
/// <summary>
/// Tests WriteEvent using the self-describing mechanism.
/// Tests both the ETW and TraceListener paths.
/// </summary>
[Fact]
public void Test_WriteEvent_SelfDescribing_EventListener()
{
using (var listener = new EventListenerListener())
{
Test_WriteEvent(listener, true);
}
}
/// <summary>
/// Tests WriteEvent using the self-describing mechanism.
/// Tests both the ETW and TraceListener paths using events
/// instead of virtual callbacks.
/// </summary>
[Fact]
public void Test_WriteEvent_SelfDescribing_EventListener_UseEvents()
{
Test_WriteEvent(new EventListenerListener(true), true);
}
[Fact]
public void Test_WriteEvent_NoAttribute()
{
using (EventSourceNoAttribute es = new EventSourceNoAttribute())
{
Listener el = new EventListenerListener(true);
var tests = new List<SubTest>();
string arg = "a sample string";
tests.Add(new SubTest("Write/Basic/EventWith9Strings",
delegate ()
{
es.EventNoAttributes(arg);
},
delegate (Event evt)
{
Assert.Equal(es.Name, evt.ProviderName);
Assert.Equal("EventNoAttributes", evt.EventName);
Assert.Equal(arg, (string)evt.PayloadValue(0, null));
}));
EventTestHarness.RunTests(tests, el, es);
}
}
/// <summary>
/// Helper method for the two tests above.
/// </summary>
private void Test_WriteEvent(Listener listener, bool useSelfDescribingEvents)
{
using (var logger = new SdtEventSources.EventSourceTest(useSelfDescribingEvents))
{
var tests = new List<SubTest>();
/*************************************************************************/
tests.Add(new SubTest("WriteEvent/Basic/EventII",
delegate () { logger.EventII(10, 11); },
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventII", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "arg1"), 10);
Assert.Equal(evt.PayloadValue(1, "arg2"), 11);
}));
/*************************************************************************/
tests.Add(new SubTest("WriteEvent/Basic/EventSS",
delegate () { logger.EventSS("one", "two"); },
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventSS", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "arg1"), "one");
Assert.Equal(evt.PayloadValue(1, "arg2"), "two");
}));
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/EventWithManyTypeArgs",
delegate ()
{
logger.EventWithManyTypeArgs("Hello", 1, 2, 3, 'a', 4, 5, 6, 7,
(float)10.0, (double)11.0, logger.Guid);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithManyTypeArgs", evt.EventName);
Assert.Equal("Hello", evt.PayloadValue(0, "msg"));
Assert.Equal((float)10.0, evt.PayloadValue(9, "f"));
Assert.Equal((double)11.0, evt.PayloadValue(10, "d"));
Assert.Equal(logger.Guid, evt.PayloadValue(11, "guid"));
}));
#endif // USE_ETW
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/EventWith7Strings",
delegate ()
{
logger.EventWith7Strings("s0", "s1", "s2", "s3", "s4", "s5", "s6");
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWith7Strings", evt.EventName);
Assert.Equal("s0", (string)evt.PayloadValue(0, "s0"));
Assert.Equal("s6", (string)evt.PayloadValue(6, "s6"));
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/EventWith9Strings",
delegate ()
{
logger.EventWith9Strings("s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8");
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWith9Strings", evt.EventName);
Assert.Equal("s0", (string)evt.PayloadValue(0, "s0"));
Assert.Equal("s8", (string)evt.PayloadValue(8, "s8"));
}));
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
/*************************************************************************/
tests.Add(new SubTest("Write/Activity/EventWithXferWeirdArgs",
delegate ()
{
var actid = Guid.NewGuid();
logger.EventWithXferWeirdArgs(actid,
(IntPtr)128,
true,
SdtEventSources.MyLongEnum.LongVal1);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
// We log EventWithXferWeirdArgs in one case and
// WorkWeirdArgs/Send in the other
Assert.True(evt.EventName.Contains("WeirdArgs"));
Assert.Equal("128", evt.PayloadValue(0, "iptr").ToString());
Assert.Equal(true, (bool)evt.PayloadValue(1, "b"));
Assert.Equal((long)SdtEventSources.MyLongEnum.LongVal1, (long)evt.PayloadValue(2, "le"));
}));
#endif // USE_ETW
/*************************************************************************/
/*************************** ENUM TESTING *******************************/
/*************************************************************************/
/*************************************************************************/
tests.Add(new SubTest("WriteEvent/Enum/EventEnum",
delegate ()
{
logger.EventEnum(SdtEventSources.MyColor.Blue);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventEnum", evt.EventName);
Assert.Equal(1, (int)evt.PayloadValue(0, "x"));
if (evt.IsEtw && !useSelfDescribingEvents)
Assert.Equal("Blue", evt.PayloadString(0, "x"));
}));
tests.Add(new SubTest("WriteEvent/Enum/EventEnum1",
delegate ()
{
logger.EventEnum1(SdtEventSources.MyColor.Blue);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventEnum1", evt.EventName);
Assert.Equal(1, (int)evt.PayloadValue(0, "x"));
if (evt.IsEtw && !useSelfDescribingEvents)
Assert.Equal("Blue", evt.PayloadString(0, "x"));
}));
tests.Add(new SubTest("WriteEvent/Basic/EventWithIntIntString",
delegate () { logger.EventWithIntIntString(10, 11, "test"); },
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithIntIntString", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "i1"), 10);
Assert.Equal(evt.PayloadValue(1, "i2"), 11);
Assert.Equal(evt.PayloadValue(2, "str"), "test");
}));
tests.Add(new SubTest("WriteEvent/Basic/EventWithIntLongString",
delegate () { logger.EventWithIntLongString(10, (long)11, "test"); },
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithIntLongString", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "i1"), 10);
Assert.Equal(evt.PayloadValue(1, "l1"), (long)11);
Assert.Equal(evt.PayloadValue(2, "str"), "test");
}));
tests.Add(new SubTest("WriteEvent/Basic/EventWithString",
delegate () { logger.EventWithString(null); },
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal(1, evt.PayloadCount);
Assert.Equal("", evt.PayloadValue(0, null));
}));
tests.Add(new SubTest("WriteEvent/Basic/EventWithIntAndString",
delegate () { logger.EventWithIntAndString(12, null); },
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal(2, evt.PayloadCount);
Assert.Equal(12, evt.PayloadValue(0, null));
Assert.Equal("", evt.PayloadValue(1, null));
}));
tests.Add(new SubTest("WriteEvent/Basic/EventWithLongAndString",
delegate () { logger.EventWithLongAndString(120L, null); },
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal(2, evt.PayloadCount);
Assert.Equal(120L, evt.PayloadValue(0, null));
Assert.Equal("", evt.PayloadValue(1, null));
}));
tests.Add(new SubTest("WriteEvent/Basic/EventWithStringAndInt",
delegate () { logger.EventWithStringAndInt(null, 12); },
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal(2, evt.PayloadCount);
Assert.Equal("", evt.PayloadValue(0, null));
Assert.Equal(12, evt.PayloadValue(1, null));
}));
tests.Add(new SubTest("WriteEvent/Basic/EventWithStringAndIntAndInt",
delegate () { logger.EventWithStringAndIntAndInt(null, 12, 13); },
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal(3, evt.PayloadCount);
Assert.Equal("", evt.PayloadValue(0, null));
Assert.Equal(12, evt.PayloadValue(1, null));
Assert.Equal(13, evt.PayloadValue(2, null));
}));
tests.Add(new SubTest("WriteEvent/Basic/EventWithStringAndLong",
delegate () { logger.EventWithStringAndLong(null, 120L); },
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal(2, evt.PayloadCount);
Assert.Equal("", evt.PayloadValue(0, null));
Assert.Equal(120L, evt.PayloadValue(1, null));
}));
tests.Add(new SubTest("WriteEvent/Basic/EventWithStringAndString",
delegate () { logger.EventWithStringAndString(null, null); },
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal(2, evt.PayloadCount);
Assert.Equal("", evt.PayloadValue(0, null));
Assert.Equal("", evt.PayloadValue(1, null));
}));
tests.Add(new SubTest("WriteEvent/Basic/EventWithStringAndStringAndString",
delegate () { logger.EventWithStringAndStringAndString(null, null, null); },
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal(3, evt.PayloadCount);
Assert.Equal("", evt.PayloadValue(0, null));
Assert.Equal("", evt.PayloadValue(1, null));
Assert.Equal("", evt.PayloadValue(2, null));
}));
if (useSelfDescribingEvents)
{
tests.Add(new SubTest("WriteEvent/Basic/EventVarArgsWithString",
delegate () { logger.EventVarArgsWithString(1, 2, 12, null); },
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal(4, evt.PayloadCount);
Assert.Equal(1, evt.PayloadValue(0, null));
Assert.Equal(2, evt.PayloadValue(1, null));
Assert.Equal(12, evt.PayloadValue(2, null));
Assert.Equal("", evt.PayloadValue(3, null));
}));
}
// Probably belongs in the user TestUsersErrors.cs.
if (!useSelfDescribingEvents)
{
tests.Add(new SubTest("WriteEvent/Basic/EventWithIncorrectNumberOfParameters",
delegate ()
{
logger.EventWithIncorrectNumberOfParameters("TestMessage", "TestPath", 10);
},
delegate (List<Event> evts)
{
Assert.True(0 < evts.Count);
// We give an error message in EventListener case but not the ETW case.
if (1 < evts.Count)
{
Assert.Equal(2, evts.Count);
Assert.Equal(logger.Name, evts[0].ProviderName);
Assert.Equal("EventSourceMessage", evts[0].EventName);
string errorMsg = evts[0].PayloadString(0, "message");
Assert.True(Regex.IsMatch(errorMsg, "called with 1.*defined with 3"));
}
int eventIdx = evts.Count - 1;
Assert.Equal(logger.Name, evts[eventIdx].ProviderName);
Assert.Equal("EventWithIncorrectNumberOfParameters", evts[eventIdx].EventName);
Assert.Equal("{TestPath:10}TestMessage", evts[eventIdx].PayloadString(0, "message"));
}));
}
// If you only wish to run one or several of the tests you can filter them here by
// Uncommenting the following line.
// tests = tests.FindAll(test => Regex.IsMatch(test.Name, "ventWithByteArray"));
// Next run the same tests with the TraceLogging path.
EventTestHarness.RunTests(tests, listener, logger);
}
}
/**********************************************************************/
/// <summary>
/// Tests sending complex data (class, arrays etc) from WriteEvent
/// Tests the EventListener case
/// </summary>
[Fact]
public void Test_WriteEvent_ComplexData_SelfDescribing_EventListener()
{
using (var listener = new EventListenerListener())
{
Test_WriteEvent_ComplexData_SelfDescribing(listener);
}
}
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
/// <summary>
/// Tests sending complex data (class, arrays etc) from WriteEvent
/// Tests the EventListener case
/// </summary>
[Fact]
public void Test_WriteEvent_ComplexData_SelfDescribing_ETW()
{
using (var listener = new EtwListener())
{
Test_WriteEvent_ComplexData_SelfDescribing(listener);
}
}
#endif // USE_ETW
private void Test_WriteEvent_ComplexData_SelfDescribing(Listener listener)
{
using (var logger = new EventSourceTestSelfDescribingOnly())
{
var tests = new List<SubTest>();
byte[] byteArray = { 0, 1, 2, 3 };
tests.Add(new SubTest("WriteEvent/SelfDescribingOnly/Byte[]",
delegate ()
{
logger.EventByteArrayInt(byteArray, 5);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventByteArrayInt", evt.EventName);
var eventArray = evt.PayloadValue(0, "array");
Array.Equals(eventArray, byteArray);
Assert.Equal(5, evt.PayloadValue(1, "anInt"));
}));
tests.Add(new SubTest("WriteEvent/SelfDescribingOnly/UserData",
delegate ()
{
logger.EventUserDataInt(new UserData() { x = 3, y = 8 }, 5);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventUserDataInt", evt.EventName);
var aClass = (IDictionary<string, object>)evt.PayloadValue(0, "aClass");
Assert.Equal(3, (int)aClass["x"]);
Assert.Equal(8, (int)aClass["y"]);
Assert.Equal(5, evt.PayloadValue(1, "anInt"));
}));
// If you only wish to run one or several of the tests you can filter them here by
// Uncommenting the following line.
// tests = tests.FindAll(test => Regex.IsMatch(test.Name, "ventWithByteArray"));
// Next run the same tests with the TraceLogging path.
EventTestHarness.RunTests(tests, listener, logger);
}
}
/**********************************************************************/
/// <summary>
/// Tests sending complex data (class, arrays etc) from WriteEvent
/// Uses Manifest format
/// Tests the EventListener case
/// </summary>
[Fact]
public void Test_WriteEvent_ByteArray_Manifest_EventListener()
{
using (var listener = new EventListenerListener())
{
Test_WriteEvent_ByteArray(false, listener);
}
}
/// <summary>
/// Tests sending complex data (class, arrays etc) from WriteEvent
/// Uses Manifest format
/// Tests the EventListener case using events instead of virtual
/// callbacks.
/// </summary>
[Fact]
public void Test_WriteEvent_ByteArray_Manifest_EventListener_UseEvents()
{
Test_WriteEvent_ByteArray(false, new EventListenerListener(true));
}
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
/// <summary>
/// Tests sending complex data (class, arrays etc) from WriteEvent
/// Uses Manifest format
/// Tests the EventListener case
/// </summary>
[Fact]
public void Test_WriteEvent_ByteArray_Manifest_ETW()
{
using (var listener = new EtwListener())
{
Test_WriteEvent_ByteArray(false, listener);
}
}
#endif // USE_ETW
/// <summary>
/// Tests sending complex data (class, arrays etc) from WriteEvent
/// Uses Self-Describing format
/// Tests the EventListener case
/// </summary>
[Fact]
public void Test_WriteEvent_ByteArray_SelfDescribing_EventListener()
{
using (var listener = new EventListenerListener())
{
Test_WriteEvent_ByteArray(true, listener);
}
}
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
/// <summary>
/// Tests sending complex data (class, arrays etc) from WriteEvent
/// Uses Self-Describing format
/// Tests the EventListener case
/// </summary>
[Fact]
public void Test_WriteEvent_ByteArray_SelfDescribing_ETW()
{
using (var listener = new EtwListener())
{
Test_WriteEvent_ByteArray(true, listener);
}
}
#endif // USE_ETW
private void Test_WriteEvent_ByteArray(bool useSelfDescribingEvents, Listener listener)
{
EventSourceSettings settings = EventSourceSettings.EtwManifestEventFormat;
if (useSelfDescribingEvents)
settings = EventSourceSettings.EtwSelfDescribingEventFormat;
using (var logger = new EventSourceTestByteArray(settings))
{
var tests = new List<SubTest>();
/*************************************************************************/
/**************************** byte[] TESTING *****************************/
/*************************************************************************/
// We only support arrays of any type with the SelfDescribing case.
/*************************************************************************/
byte[] blob = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
tests.Add(new SubTest("Write/Array/EventWithByteArrayArg",
delegate ()
{
logger.EventWithByteArrayArg(blob, 1000);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithByteArrayArg", evt.EventName);
if (evt.IsEventListener)
{
byte[] retBlob = (byte[])evt.PayloadValue(0, "blob");
Assert.NotNull(retBlob);
Assert.True(Equal(blob, retBlob));
Assert.Equal(1000, (int)evt.PayloadValue(1, "n"));
}
}));
if (!useSelfDescribingEvents)
{
/*************************************************************************/
tests.Add(new SubTest("Write/Array/NonEventCallingEventWithBytePtrArg",
delegate ()
{
logger.NonEventCallingEventWithBytePtrArg(blob, 2, 4, 1001);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithBytePtrArg", evt.EventName);
if (evt.IsEtw)
{
Assert.Equal(2, evt.PayloadCount);
byte[] retBlob = (byte[])evt.PayloadValue(0, "blob");
Assert.Equal(4, retBlob.Length);
Assert.Equal(retBlob[0], blob[2]);
Assert.Equal(retBlob[3], blob[2 + 3]);
Assert.Equal(1001, (int)evt.PayloadValue(1, "n"));
}
else
{
Assert.Equal(3, evt.PayloadCount);
byte[] retBlob = (byte[])evt.PayloadValue(1, "blob");
Assert.Equal(1001, (int)evt.PayloadValue(2, "n"));
}
}));
}
tests.Add(new SubTest("Write/Array/EventWithLongByteArray",
delegate ()
{
logger.EventWithLongByteArray(blob, 1000);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithLongByteArray", evt.EventName);
Assert.Equal(2, evt.PayloadCount);
byte[] retBlob = (byte[])evt.PayloadValue(0, "blob");
Assert.True(Equal(blob, retBlob));
Assert.Equal(1000, (long)evt.PayloadValue(1, "lng"));
}));
// If you only wish to run one or several of the tests you can filter them here by
// Uncommenting the following line.
// tests = tests.FindAll(test => Regex.IsMatch(test.Name, "ventWithByteArray"));
// Next run the same tests with the TraceLogging path.
EventTestHarness.RunTests(tests, listener, logger);
}
}
/**********************************************************************/
// Helper that compares two arrays for equality.
private static bool Equal(byte[] blob1, byte[] blob2)
{
if (blob1.Length != blob2.Length)
return false;
for (int i = 0; i < blob1.Length; i++)
if (blob1[i] != blob2[i])
return false;
return true;
}
}
[EventData]
public class UserData
{
public int x { get; set; }
public int y { get; set; }
}
/// <summary>
/// Used to show the more complex data type that
/// </summary>
public sealed class EventSourceTestSelfDescribingOnly : EventSource
{
public EventSourceTestSelfDescribingOnly() : base(EventSourceSettings.EtwSelfDescribingEventFormat) { }
public void EventByteArrayInt(byte[] array, int anInt) { WriteEvent(1, array, anInt); }
public void EventUserDataInt(UserData aClass, int anInt) { WriteEvent(2, aClass, anInt); }
}
public sealed class EventSourceTestByteArray : EventSource
{
public EventSourceTestByteArray(EventSourceSettings settings) : base(settings) { }
// byte[] args not supported on 4.5
[Event(1, Level = EventLevel.Informational, Message = "Int arg after byte array: {1}")]
public void EventWithByteArrayArg(byte[] blob, int n)
{ WriteEvent(1, blob, n); }
[NonEvent]
public unsafe void NonEventCallingEventWithBytePtrArg(byte[] blob, int start, uint size, int n)
{
if (blob == null || start + size > blob.Length)
throw new ArgumentException("start + size must be smaller than blob.Length");
fixed (byte* p = blob)
EventWithBytePtrArg(size, p + start, n);
}
[Event(2, Level = EventLevel.Informational, Message = "Int arg after byte ptr: {2}")]
public unsafe void EventWithBytePtrArg(uint blobSize, byte* blob, int n)
{
if (IsEnabled())
{
{
EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
descrs[0].DataPointer = (IntPtr)(&blobSize);
descrs[0].Size = 4;
descrs[1].DataPointer = (IntPtr)blob;
descrs[1].Size = (int)blobSize;
descrs[2].Size = 4;
descrs[2].DataPointer = (IntPtr)(&n);
WriteEventCore(2, 3, descrs);
}
}
}
[Event(3, Level = EventLevel.Informational, Message = "long after byte array: {1}")]
public void EventWithLongByteArray(byte[] blob, long lng)
{ WriteEvent(3, blob, lng); }
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Baseline;
using Marten.Storage;
using Marten.Testing.Events.Projections;
using Marten.Testing.Events.Utils;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;
namespace Marten.Testing.Events
{
[Collection("projections")]
public class end_to_end_event_capture_and_fetching_the_stream_Tests : OneOffConfigurationsContext
{
private static readonly string[] SameTenants = { "tenant", "tenant" };
private static readonly string[] DiffetentTenants = { "tenant", "differentTenant" };
private static readonly string[] DefaultTenant = { Tenancy.DefaultTenantId };
public end_to_end_event_capture_and_fetching_the_stream_Tests() : base("projections")
{
}
public static TheoryData<DocumentTracking, TenancyStyle, string[]> SessionParams = new TheoryData<DocumentTracking, TenancyStyle, string[]>
{
{ DocumentTracking.IdentityOnly, TenancyStyle.Conjoined, SameTenants },
{ DocumentTracking.DirtyTracking, TenancyStyle.Conjoined, DiffetentTenants },
{ DocumentTracking.IdentityOnly, TenancyStyle.Conjoined, SameTenants },
{ DocumentTracking.DirtyTracking, TenancyStyle.Conjoined, DiffetentTenants },
{ DocumentTracking.IdentityOnly, TenancyStyle.Single, DefaultTenant },
{ DocumentTracking.DirtyTracking, TenancyStyle.Single, DefaultTenant },
{ DocumentTracking.IdentityOnly, TenancyStyle.Single, DiffetentTenants },
{ DocumentTracking.DirtyTracking, TenancyStyle.Single, DiffetentTenants },
{ DocumentTracking.IdentityOnly, TenancyStyle.Single, SameTenants },
{ DocumentTracking.DirtyTracking, TenancyStyle.Single, SameTenants },
};
[Theory]
[MemberData(nameof(SessionParams))]
public void capture_events_to_a_new_stream_and_fetch_the_events_back(DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
When.CalledForEach(tenants, (tenantId, index) =>
{
using (var session = store.OpenSession(tenantId, sessionType))
{
// SAMPLE: start-stream-with-aggregate-type
var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } };
var departed = new MembersDeparted { Members = new[] { "Thom" } };
var id = session.Events.StartStream<Quest>(joined, departed).Id;
session.SaveChanges();
// ENDSAMPLE
var streamEvents = session.Events.FetchStream(id);
streamEvents.Count().ShouldBe(2);
streamEvents.ElementAt(0).Data.ShouldBeOfType<MembersJoined>();
streamEvents.ElementAt(0).Version.ShouldBe(1);
streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersDeparted>();
streamEvents.ElementAt(1).Version.ShouldBe(2);
streamEvents.Each(e => e.Timestamp.ShouldNotBe(default(DateTimeOffset)));
}
}).ShouldSucceed();
}
[Theory]
[MemberData(nameof(SessionParams))]
public Task capture_events_to_a_new_stream_and_fetch_the_events_back_async(DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
return When.CalledForEachAsync(tenants, async (tenantId, index) =>
{
using (var session = store.OpenSession(tenantId, sessionType))
{
// SAMPLE: start-stream-with-aggregate-type
var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } };
var departed = new MembersDeparted { Members = new[] { "Thom" } };
var id = session.Events.StartStream<Quest>(joined, departed).Id;
await session.SaveChangesAsync();
// ENDSAMPLE
var streamEvents = await session.Events.FetchStreamAsync(id);
streamEvents.Count().ShouldBe(2);
streamEvents.ElementAt(0).Data.ShouldBeOfType<MembersJoined>();
streamEvents.ElementAt(0).Version.ShouldBe(1);
streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersDeparted>();
streamEvents.ElementAt(1).Version.ShouldBe(2);
streamEvents.Each(e => e.Timestamp.ShouldNotBe(default(DateTimeOffset)));
}
}).ShouldSucceedAsync();
}
[Theory]
[MemberData(nameof(SessionParams))]
public Task capture_events_to_a_new_stream_and_fetch_the_events_back_async_with_linq(DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
return When.CalledForEachAsync(tenants, async (tenantId, index) =>
{
using (var session = store.OpenSession(tenantId, sessionType))
{
// SAMPLE: start-stream-with-aggregate-type
var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } };
var departed = new MembersDeparted { Members = new[] { "Thom" } };
var id = session.Events.StartStream<Quest>(joined, departed).Id;
await session.SaveChangesAsync();
// ENDSAMPLE
var streamEvents = await session.Events.QueryAllRawEvents()
.Where(x => x.StreamId == id).OrderBy(x => x.Version).ToListAsync();
streamEvents.Count().ShouldBe(2);
streamEvents.ElementAt(0).Data.ShouldBeOfType<MembersJoined>();
streamEvents.ElementAt(0).Version.ShouldBe(1);
streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersDeparted>();
streamEvents.ElementAt(1).Version.ShouldBe(2);
streamEvents.Each(e => e.Timestamp.ShouldNotBe(default(DateTimeOffset)));
}
}).ShouldSucceedAsync();
}
[Theory]
[MemberData(nameof(SessionParams))]
public void capture_events_to_a_new_stream_and_fetch_the_events_back_sync_with_linq(DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
When.CalledForEach(tenants, (tenantId, index) =>
{
using (var session = store.OpenSession(tenantId, sessionType))
{
// SAMPLE: start-stream-with-aggregate-type
var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } };
var departed = new MembersDeparted { Members = new[] { "Thom" } };
var id = session.Events.StartStream<Quest>(joined, departed).Id;
session.SaveChanges();
// ENDSAMPLE
var streamEvents = session.Events.QueryAllRawEvents()
.Where(x => x.StreamId == id).OrderBy(x => x.Version).ToList();
streamEvents.Count().ShouldBe(2);
streamEvents.ElementAt(0).Data.ShouldBeOfType<MembersJoined>();
streamEvents.ElementAt(0).Version.ShouldBe(1);
streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersDeparted>();
streamEvents.ElementAt(1).Version.ShouldBe(2);
streamEvents.Each(e => e.Timestamp.ShouldNotBe(default(DateTimeOffset)));
}
}).ShouldSucceed();
}
[Theory]
[MemberData(nameof(SessionParams))]
public void live_aggregate_equals_inlined_aggregate_without_hidden_contracts(DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
var questId = Guid.NewGuid();
When.CalledForEach(tenants, (tenantId, index) =>
{
using (var session = store.OpenSession(tenantId, sessionType))
{
//Note Id = questId, is we remove it from first message then AggregateStream will return party.Id=default(Guid) that is not equals to Load<QuestParty> result
var started = new QuestStarted { /*Id = questId,*/ Name = "Destroy the One Ring" };
var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Merry");
session.Events.StartStream<Quest>(questId, started, joined1);
session.SaveChanges();
}
using (var session = store.OpenSession(tenantId, sessionType))
{
var liveAggregate = session.Events.AggregateStream<QuestParty>(questId);
var inlinedAggregate = session.Load<QuestParty>(questId);
liveAggregate.Id.ShouldBe(inlinedAggregate.Id);
inlinedAggregate.ToString().ShouldBe(liveAggregate.ToString());
}
}).ShouldThrowIf(
(tenancyStyle == TenancyStyle.Single && tenants.Length > 1) || (tenancyStyle == TenancyStyle.Conjoined && tenants.SequenceEqual(SameTenants))
);
}
[Theory]
[MemberData(nameof(SessionParams))]
public void open_persisted_stream_in_new_store_with_same_settings(DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
var questId = Guid.NewGuid();
When.CalledForEach(tenants, (tenantId, index) =>
{
using (var session = store.OpenSession(tenantId, sessionType))
{
//Note "Id = questId" @see live_aggregate_equals_inlined_aggregate...
var started = new QuestStarted { Id = questId, Name = "Destroy the One Ring" };
var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Merry");
session.Events.StartStream<Quest>(questId, started, joined1);
session.SaveChanges();
}
// events-aggregate-on-the-fly - works with same store
using (var session = store.OpenSession(tenantId, sessionType))
{
// questId is the id of the stream
var party = session.Events.AggregateStream<QuestParty>(questId);
party.Id.ShouldBe(questId);
SpecificationExtensions.ShouldNotBeNull(party);
var party_at_version_3 = session.Events
.AggregateStream<QuestParty>(questId, 3);
party_at_version_3.ShouldNotBeNull();
var party_yesterday = session.Events
.AggregateStream<QuestParty>(questId, timestamp: DateTime.UtcNow.AddDays(-1));
SpecificationExtensions.ShouldNotBeNull(party_yesterday);
}
using (var session = store.OpenSession(tenantId, sessionType))
{
var party = session.Load<QuestParty>(questId);
party.Id.ShouldBe(questId);
}
var newStore = InitStore(tenancyStyle, false);
//Inline is working
using (var session = store.OpenSession(tenantId, sessionType))
{
var party = session.Load<QuestParty>(questId);
SpecificationExtensions.ShouldNotBeNull(party);
}
//GetAll
using (var session = store.OpenSession(tenantId, sessionType))
{
var parties = session.Events.QueryRawEventDataOnly<QuestParty>().ToArray();
foreach (var party in parties)
{
SpecificationExtensions.ShouldNotBeNull(party);
}
}
//This AggregateStream fail with NPE
using (var session = newStore.OpenSession(tenantId, sessionType))
{
// questId is the id of the stream
var party = session.Events.AggregateStream<QuestParty>(questId);//Here we get NPE
party.Id.ShouldBe(questId);
var party_at_version_3 = session.Events
.AggregateStream<QuestParty>(questId, 3);
party_at_version_3.Id.ShouldBe(questId);
var party_yesterday = session.Events
.AggregateStream<QuestParty>(questId, timestamp: DateTime.UtcNow.AddDays(-1));
party_yesterday.Id.ShouldBe(questId);
}
}).ShouldThrowIf(
(tenancyStyle == TenancyStyle.Single && tenants.Length > 1) || (tenancyStyle == TenancyStyle.Conjoined && tenants.SequenceEqual(SameTenants))
);
}
[Theory]
[MemberData(nameof(SessionParams))]
public void query_before_saving(DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
var questId = Guid.NewGuid();
When.CalledForEach(tenants, (tenantId, index) =>
{
using (var session = store.OpenSession(tenantId, sessionType))
{
var parties = session.Query<QuestParty>().ToArray();
parties.Length.ShouldBeLessThanOrEqualTo(index);
}
//This SaveChanges will fail with missing method (ro collection configured?)
using (var session = store.OpenSession(tenantId, sessionType))
{
var started = new QuestStarted { Name = "Destroy the One Ring" };
var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Merry");
session.Events.StartStream<Quest>(questId, started, joined1);
session.SaveChanges();
var party = session.Events.AggregateStream<QuestParty>(questId);
party.Id.ShouldBe(questId);
}
}).ShouldThrowIf(
(tenancyStyle == TenancyStyle.Single && tenants.Length > 1) || (tenancyStyle == TenancyStyle.Conjoined && tenants.SequenceEqual(SameTenants))
);
}
[Theory]
[MemberData(nameof(SessionParams))]
public Task aggregate_stream_async_has_the_id(DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
var questId = Guid.NewGuid();
return When.CalledForEachAsync(tenants, async (tenantId, index) =>
{
using (var session = store.OpenSession(tenantId, sessionType))
{
var parties = await session.Query<QuestParty>().ToListAsync();
parties.Count.ShouldBeLessThanOrEqualTo(index);
}
//This SaveChanges will fail with missing method (ro collection configured?)
using (var session = store.OpenSession(tenantId, sessionType))
{
var started = new QuestStarted { Name = "Destroy the One Ring" };
var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Merry");
session.Events.StartStream<Quest>(questId, started, joined1);
await session.SaveChangesAsync();
var party = await session.Events.AggregateStreamAsync<QuestParty>(questId);
party.Id.ShouldBe(questId);
}
}).ShouldThrowIfAsync(
(tenancyStyle == TenancyStyle.Single && tenants.Length > 1) || (tenancyStyle == TenancyStyle.Conjoined && tenants.SequenceEqual(SameTenants))
);
}
[Theory]
[MemberData(nameof(SessionParams))]
public void capture_events_to_a_new_stream_and_fetch_the_events_back_with_stream_id_provided(
DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
When.CalledForEach(tenants, (tenantId, index) =>
{
using (var session = store.OpenSession(tenantId, sessionType))
{
// SAMPLE: start-stream-with-existing-guid
var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } };
var departed = new MembersDeparted { Members = new[] { "Thom" } };
var id = Guid.NewGuid();
session.Events.StartStream<Quest>(id, joined, departed);
session.SaveChanges();
// ENDSAMPLE
var streamEvents = session.Events.FetchStream(id);
streamEvents.Count().ShouldBe(2);
streamEvents.ElementAt(0).Data.ShouldBeOfType<MembersJoined>();
streamEvents.ElementAt(0).Version.ShouldBe(1);
streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersDeparted>();
streamEvents.ElementAt(1).Version.ShouldBe(2);
}
}).ShouldSucceed();
}
[Theory]
[MemberData(nameof(SessionParams))]
public void capture_events_to_a_non_existing_stream_and_fetch_the_events_back(DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
When.CalledForEach(tenants, (tenantId, index) =>
{
using (var session = store.OpenSession(tenantId, sessionType))
{
var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } };
var departed = new MembersDeparted { Members = new[] { "Thom" } };
var id = Guid.NewGuid();
session.Events.StartStream<Quest>(id, joined);
session.Events.Append(id, departed);
session.SaveChanges();
var streamEvents = session.Events.FetchStream(id);
streamEvents.Count().ShouldBe(2);
streamEvents.ElementAt(0).Data.ShouldBeOfType<MembersJoined>();
streamEvents.ElementAt(0).Version.ShouldBe(1);
streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersDeparted>();
streamEvents.ElementAt(1).Version.ShouldBe(2);
}
}).ShouldSucceed();
}
[Theory]
[MemberData(nameof(SessionParams))]
public void capture_events_to_an_existing_stream_and_fetch_the_events_back(DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
var id = Guid.NewGuid();
When.CalledForEach(tenants, (tenantId, index) =>
{
var started = new QuestStarted();
using (var session = store.OpenSession(tenantId, sessionType))
{
session.Events.StartStream<Quest>(id, started);
session.SaveChanges();
}
using (var session = store.OpenSession(tenantId, sessionType))
{
var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } };
var departed = new MembersDeparted { Members = new[] { "Thom" } };
session.Events.Append(id, joined);
session.Events.Append(id, departed);
session.SaveChanges();
var streamEvents = session.Events.FetchStream(id);
streamEvents.Count().ShouldBe(3);
streamEvents.ElementAt(0).Data.ShouldBeOfType<QuestStarted>();
streamEvents.ElementAt(0).Version.ShouldBe(1);
streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersJoined>();
streamEvents.ElementAt(1).Version.ShouldBe(2);
streamEvents.ElementAt(2).Data.ShouldBeOfType<MembersDeparted>();
streamEvents.ElementAt(2).Version.ShouldBe(3);
}
}).ShouldThrowIf(
(tenancyStyle == TenancyStyle.Single && tenants.Length > 1) || (tenancyStyle == TenancyStyle.Conjoined && tenants.SequenceEqual(SameTenants))
);
}
[Theory]
[MemberData(nameof(SessionParams))]
public void capture_events_to_a_new_stream_and_fetch_the_events_back_in_another_database_schema(
DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
When.CalledForEach(tenants, (tenantId, index) =>
{
using (var session = store.OpenSession(tenantId, sessionType))
{
var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } };
var departed = new MembersDeparted { Members = new[] { "Thom" } };
var id = session.Events.StartStream<Quest>(joined, departed).Id;
session.SaveChanges();
var streamEvents = session.Events.FetchStream(id);
streamEvents.Count().ShouldBe(2);
streamEvents.ElementAt(0).Data.ShouldBeOfType<MembersJoined>();
streamEvents.ElementAt(0).Version.ShouldBe(1);
streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersDeparted>();
streamEvents.ElementAt(1).Version.ShouldBe(2);
}
}).ShouldSucceed();
}
[Theory]
[MemberData(nameof(SessionParams))]
public void
capture_events_to_a_new_stream_and_fetch_the_events_back_with_stream_id_provided_in_another_database_schema(
DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
When.CalledForEach(tenants, (tenantId, index) =>
{
using (var session = store.OpenSession(tenantId, sessionType))
{
var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } };
var departed = new MembersDeparted { Members = new[] { "Thom" } };
var id = Guid.NewGuid();
session.Events.StartStream<Quest>(id, joined, departed);
session.SaveChanges();
var streamEvents = session.Events.FetchStream(id);
streamEvents.Count().ShouldBe(2);
streamEvents.ElementAt(0).Data.ShouldBeOfType<MembersJoined>();
streamEvents.ElementAt(0).Version.ShouldBe(1);
streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersDeparted>();
streamEvents.ElementAt(1).Version.ShouldBe(2);
streamEvents.Each(x => SpecificationExtensions.ShouldBeGreaterThan(x.Sequence, 0L));
}
}).ShouldSucceed();
}
[Theory]
[MemberData(nameof(SessionParams))]
public void capture_events_to_a_non_existing_stream_and_fetch_the_events_back_in_another_database_schema(
DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
When.CalledForEach(tenants, (tenantId, index) =>
{
using (var session = store.OpenSession(tenantId, sessionType))
{
var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } };
var departed = new MembersDeparted { Members = new[] { "Thom" } };
var id = Guid.NewGuid();
session.Events.StartStream<Quest>(id, joined);
session.Events.Append(id, departed);
session.SaveChanges();
var streamEvents = session.Events.FetchStream(id);
streamEvents.Count().ShouldBe(2);
streamEvents.ElementAt(0).Data.ShouldBeOfType<MembersJoined>();
streamEvents.ElementAt(0).Version.ShouldBe(1);
streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersDeparted>();
streamEvents.ElementAt(1).Version.ShouldBe(2);
}
}).ShouldSucceed();
}
[Theory]
[MemberData(nameof(SessionParams))]
public void capture_events_to_an_existing_stream_and_fetch_the_events_back_in_another_database_schema(
DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
var id = Guid.NewGuid();
When.CalledForEach(tenants, (tenantId, index) =>
{
var started = new QuestStarted();
using (var session = store.OpenSession(tenantId, sessionType))
{
session.Events.StartStream<Quest>(id, started);
session.SaveChanges();
}
using (var session = store.OpenSession(tenantId, sessionType))
{
// SAMPLE: append-events
var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } };
var departed = new MembersDeparted { Members = new[] { "Thom" } };
session.Events.Append(id, joined, departed);
session.SaveChanges();
// ENDSAMPLE
var streamEvents = session.Events.FetchStream(id);
streamEvents.Count().ShouldBe(3);
streamEvents.ElementAt(0).Data.ShouldBeOfType<QuestStarted>();
streamEvents.ElementAt(0).Version.ShouldBe(1);
streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersJoined>();
streamEvents.ElementAt(1).Version.ShouldBe(2);
streamEvents.ElementAt(2).Data.ShouldBeOfType<MembersDeparted>();
streamEvents.ElementAt(2).Version.ShouldBe(3);
}
}).ShouldThrowIf(
(tenancyStyle == TenancyStyle.Single && tenants.Length > 1) || (tenancyStyle == TenancyStyle.Conjoined && tenants.SequenceEqual(SameTenants))
);
}
[Theory]
[MemberData(nameof(SessionParams))]
public void assert_on_max_event_id_on_event_stream_append(
DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
var id = Guid.NewGuid();
When.CalledForEach(tenants, (tenantId, index) =>
{
var started = new QuestStarted();
using (var session = store.OpenSession(tenantId, sessionType))
{
// SAMPLE: append-events-assert-on-eventid
session.Events.StartStream<Quest>(id, started);
session.SaveChanges();
var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } };
var departed = new MembersDeparted { Members = new[] { "Thom" } };
// Events are appended into the stream only if the maximum event id for the stream
// would be 3 after the append operation.
session.Events.Append(id, 3, joined, departed);
session.SaveChanges();
// ENDSAMPLE
}
}).ShouldThrowIf(
(tenancyStyle == TenancyStyle.Single && tenants.Length > 1) || (tenancyStyle == TenancyStyle.Conjoined && tenants.SequenceEqual(SameTenants))
);
}
[Theory]
[MemberData(nameof(SessionParams))]
public void capture_immutable_events(DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle);
var id = Guid.NewGuid();
When.CalledForEach(tenants, (tenantId, index) =>
{
var immutableEvent = new ImmutableEvent(id, "some-name");
using (var session = store.OpenSession(tenantId, sessionType))
{
session.Events.Append(id, immutableEvent);
session.SaveChanges();
}
using (var session = store.OpenSession(tenantId, sessionType))
{
var streamEvents = session.Events.FetchStream(id);
streamEvents.Count.ShouldBe(1);
var @event = streamEvents.ElementAt(0).Data.ShouldBeOfType<ImmutableEvent>();
@event.Id.ShouldBe(id);
@event.Name.ShouldBe("some-name");
}
}).ShouldThrowIf(
(tenancyStyle == TenancyStyle.Single && tenants.Length > 1) || (tenancyStyle == TenancyStyle.Conjoined && tenants.SequenceEqual(SameTenants))
);
}
[Theory]
[MemberData(nameof(SessionParams))]
public void capture_immutable_events_with_for_update_lock(DocumentTracking sessionType, TenancyStyle tenancyStyle, string[] tenants)
{
var store = InitStore(tenancyStyle, useAppendEventForUpdateLock: true);
var id = Guid.NewGuid();
When.CalledForEach(tenants, (tenantId, index) =>
{
var immutableEvent = new ImmutableEvent(id, "some-name");
using (var session = store.OpenSession(tenantId, sessionType))
{
session.Events.Append(id, immutableEvent);
session.SaveChanges();
}
using (var session = store.OpenSession(tenantId, sessionType))
{
var streamEvents = session.Events.FetchStream(id);
streamEvents.Count.ShouldBe(1);
var @event = streamEvents.ElementAt(0).Data.ShouldBeOfType<ImmutableEvent>();
@event.Id.ShouldBe(id);
@event.Name.ShouldBe("some-name");
}
}).ShouldThrowIf(
(tenancyStyle == TenancyStyle.Single && tenants.Length > 1) || (tenancyStyle == TenancyStyle.Conjoined && tenants.SequenceEqual(SameTenants))
);
}
private DocumentStore InitStore(TenancyStyle tenancyStyle, bool cleanSchema = true, bool useAppendEventForUpdateLock = false)
{
var databaseSchema = $"end_to_end_event_capture_{tenancyStyle.ToString().ToLower()}";
var store = StoreOptions(_ =>
{
_.Events.DatabaseSchemaName = databaseSchema;
_.Events.TenancyStyle = tenancyStyle;
_.Events.UseAppendEventForUpdateLock = useAppendEventForUpdateLock;
_.AutoCreateSchemaObjects = AutoCreate.All;
if (tenancyStyle == TenancyStyle.Conjoined)
_.Policies.AllDocumentsAreMultiTenanted();
_.Connection(ConnectionSource.ConnectionString);
_.Events.InlineProjections.AggregateStreamsWith<QuestParty>();
_.Events.AddEventType(typeof(MembersJoined));
_.Events.AddEventType(typeof(MembersDeparted));
_.Events.AddEventType(typeof(QuestStarted));
}, cleanSchema);
return store;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>TopicConstant</c> resource.</summary>
public sealed partial class TopicConstantName : gax::IResourceName, sys::IEquatable<TopicConstantName>
{
/// <summary>The possible contents of <see cref="TopicConstantName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>topicConstants/{topic_id}</c>.</summary>
Topic = 1,
}
private static gax::PathTemplate s_topic = new gax::PathTemplate("topicConstants/{topic_id}");
/// <summary>Creates a <see cref="TopicConstantName"/> 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="TopicConstantName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static TopicConstantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new TopicConstantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="TopicConstantName"/> with the pattern <c>topicConstants/{topic_id}</c>.
/// </summary>
/// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="TopicConstantName"/> constructed from the provided ids.</returns>
public static TopicConstantName FromTopic(string topicId) =>
new TopicConstantName(ResourceNameType.Topic, topicId: gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TopicConstantName"/> with pattern
/// <c>topicConstants/{topic_id}</c>.
/// </summary>
/// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TopicConstantName"/> with pattern <c>topicConstants/{topic_id}</c>
/// .
/// </returns>
public static string Format(string topicId) => FormatTopic(topicId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TopicConstantName"/> with pattern
/// <c>topicConstants/{topic_id}</c>.
/// </summary>
/// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TopicConstantName"/> with pattern <c>topicConstants/{topic_id}</c>
/// .
/// </returns>
public static string FormatTopic(string topicId) =>
s_topic.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="TopicConstantName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>topicConstants/{topic_id}</c></description></item></list>
/// </remarks>
/// <param name="topicConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="TopicConstantName"/> if successful.</returns>
public static TopicConstantName Parse(string topicConstantName) => Parse(topicConstantName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="TopicConstantName"/> 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>topicConstants/{topic_id}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="topicConstantName">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="TopicConstantName"/> if successful.</returns>
public static TopicConstantName Parse(string topicConstantName, bool allowUnparsed) =>
TryParse(topicConstantName, allowUnparsed, out TopicConstantName 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="TopicConstantName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>topicConstants/{topic_id}</c></description></item></list>
/// </remarks>
/// <param name="topicConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TopicConstantName"/>, 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 topicConstantName, out TopicConstantName result) =>
TryParse(topicConstantName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TopicConstantName"/> 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>topicConstants/{topic_id}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="topicConstantName">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="TopicConstantName"/>, 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 topicConstantName, bool allowUnparsed, out TopicConstantName result)
{
gax::GaxPreconditions.CheckNotNull(topicConstantName, nameof(topicConstantName));
gax::TemplatedResourceName resourceName;
if (s_topic.TryParseName(topicConstantName, out resourceName))
{
result = FromTopic(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(topicConstantName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private TopicConstantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string topicId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
TopicId = topicId;
}
/// <summary>
/// Constructs a new instance of a <see cref="TopicConstantName"/> class from the component parts of pattern
/// <c>topicConstants/{topic_id}</c>
/// </summary>
/// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param>
public TopicConstantName(string topicId) : this(ResourceNameType.Topic, topicId: gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId)))
{
}
/// <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>Topic</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TopicId { 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.Topic: return s_topic.Expand(TopicId);
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 TopicConstantName);
/// <inheritdoc/>
public bool Equals(TopicConstantName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(TopicConstantName a, TopicConstantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(TopicConstantName a, TopicConstantName b) => !(a == b);
}
public partial class TopicConstant
{
/// <summary>
/// <see cref="TopicConstantName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal TopicConstantName ResourceNameAsTopicConstantName
{
get => string.IsNullOrEmpty(ResourceName) ? null : TopicConstantName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="TopicConstantName"/>-typed view over the <see cref="TopicConstantParent"/> resource name
/// property.
/// </summary>
internal TopicConstantName TopicConstantParentAsTopicConstantName
{
get => string.IsNullOrEmpty(TopicConstantParent) ? null : TopicConstantName.Parse(TopicConstantParent, allowUnparsed: true);
set => TopicConstantParent = value?.ToString() ?? "";
}
}
}
| |
/* Genuine Channels product.
*
* Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved.
*
* This source code comes under and must be used and distributed according to the Genuine Channels license agreement.
*/
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Channels;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using Belikov.Common.ThreadProcessing;
using Belikov.GenuineChannels.BufferPooling;
using Belikov.GenuineChannels.Connection;
using Belikov.GenuineChannels.DotNetRemotingLayer;
using Belikov.GenuineChannels.Logbook;
using Belikov.GenuineChannels.Messaging;
using Belikov.GenuineChannels.Parameters;
using Belikov.GenuineChannels.Receiving;
using Belikov.GenuineChannels.Security;
using Belikov.GenuineChannels.TransportContext;
using Belikov.GenuineChannels.Utilities;
namespace Belikov.GenuineChannels.GenuineUdp
{
/// <summary>
/// Implements a Connection Manager servicing UDP connections.
/// </summary>
internal class UdpConnectionManager : ConnectionManager, ITimerConsumer
{
/// <summary>
/// Constructs an instance of the UdpConnectionManager class.
/// </summary>
/// <param name="iTransportContext">The transport context.</param>
public UdpConnectionManager(ITransportContext iTransportContext) : base(iTransportContext)
{
this.Local = new HostInformation("_gudp://" + iTransportContext.HostIdentifier, iTransportContext);
this._sendBuffer = new byte[(int) iTransportContext.IParameterProvider[GenuineParameter.UdpPacketSize]];
TimerProvider.Attach(this);
this._closeInvocationConnectionAfterInactivity = GenuineUtility.ConvertToMilliseconds(iTransportContext.IParameterProvider[GenuineParameter.CloseInvocationConnectionAfterInactivity]);
}
/// <summary>
/// Sends the message to the remote host.
/// </summary>
/// <param name="message">The message to be sent.</param>
protected override void InternalSend(Message message)
{
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
// get IP end point of the remote host
IPEndPoint remoteEndPoint;
if (message.Recipient.Uri != null && message.Recipient.Uri.StartsWith("_gb"))
remoteEndPoint = this._multicastTo;
else
remoteEndPoint = message.Recipient.PhysicalAddress as IPEndPoint;
if (remoteEndPoint == null)
{
try
{
int port;
string baseUrl = GenuineUtility.SplitToHostAndPort(message.Recipient.Url, out port);
message.Recipient.PhysicalAddress = remoteEndPoint = new IPEndPoint(GenuineUtility.ResolveIPAddress(baseUrl), port);
}
catch(Exception)
{
throw GenuineExceptions.Get_Send_DestinationIsUnreachable(message.Recipient.ToString());
}
}
Stream streamToSend = message.SerializedContent;
// write the host URI
if ((int) this.ITransportContext.IParameterProvider[GenuineParameter.CompatibilityLevel] > 0)
{
GenuineChunkedStream streamWith250Header = new GenuineChunkedStream(false);
BinaryWriter binaryWriter = new BinaryWriter(streamWith250Header);
streamWith250Header.Write(this.ITransportContext.BinaryHostIdentifier, 0, this.ITransportContext.BinaryHostIdentifier.Length);
binaryWriter.Write((int) message.Recipient.LocalHostUniqueIdentifier);
binaryWriter.Write((Int16) 0);
streamWith250Header.WriteStream(streamToSend);
streamToSend = streamWith250Header;
}
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "UdpConnectionManager.InternalSend",
LogMessageType.MessageIsSentSynchronously, null, message, message.Recipient, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
message.ConnectionLevelSecuritySession, message.ConnectionLevelSecuritySession == null ? null : message.ConnectionLevelSecuritySession.Name,
-1, 0, 0, 0, remoteEndPoint.ToString(), null, null, null,
"The message is being sent synchronously to {0}.", remoteEndPoint.ToString());
}
// send the message
byte[] streamId = Guid.NewGuid().ToByteArray();
lock (_socketLock)
{
for ( int chunkNumber = 1; ; chunkNumber++ )
{
// read the next chunk
int chunkSize = streamToSend.Read(this._sendBuffer, HEADER_SIZE, this._sendBuffer.Length - HEADER_SIZE);
// fill in the header
this._sendBuffer[0] = MessageCoder.COMMAND_MAGIC_CODE;
Buffer.BlockCopy(streamId, 0, this._sendBuffer, 1, 16);
if (chunkSize < this._sendBuffer.Length - HEADER_SIZE)
chunkNumber = - chunkNumber;
MessageCoder.WriteInt32(this._sendBuffer, 17, chunkNumber);
// and just send it!
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Transport] > 0 )
{
binaryLogWriter.WriteTransportContentEvent(LogCategory.Transport, "UdpConnectionManager.InternalSend",
LogMessageType.SynchronousSendingStarted, null, message, message.Recipient,
binaryLogWriter[LogCategory.Transport] > 1 ? new MemoryStream(GenuineUtility.CutOutBuffer(this._sendBuffer, 0, chunkSize + HEADER_SIZE)) : null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
this.DbgConnectionId, chunkSize + HEADER_SIZE, remoteEndPoint.ToString(),
null, null,
"Content is sent synchronously to {0}.", remoteEndPoint.ToString());
}
this._socket.SendTo(this._sendBuffer, 0, chunkSize + HEADER_SIZE, SocketFlags.None, remoteEndPoint);
if (chunkNumber < 0)
break;
}
}
}
#region -- Low-level socket stuff ----------------------------------------------------------
/// <summary>
/// The message registrator.
/// </summary>
public IMessageRegistrator _iMessageRegistrator = new MessageRegistratorWithLimitedTime();
/// <summary>
/// Specifies a value by which the remote host's information is extended after every received message.
/// </summary>
private int _closeInvocationConnectionAfterInactivity;
private Socket _socket;
private object _socketLock = new object();
private IPEndPoint _multicastTo;
private byte[] _sendBuffer;
private bool _closing;
private ManualResetEvent _receivingThreadClosed = new ManualResetEvent(true);
private Hashtable _streams = Hashtable.Synchronized(new Hashtable());
/// <summary>
/// Gets the connection identifier.
/// </summary>
public int DbgConnectionId
{
get
{
return this._dbgConnectionId;
}
}
private int _dbgConnectionId = ConnectionManager.GetUniqueConnectionId();
/// <summary>
/// (1) Magic code
/// (16) The unique stream id
/// (4) The sequence number of the current chunk (negative if it's the last chunk).
/// </summary>
private const int HEADER_SIZE = 21;
/// <summary>
/// Receives the content synchronously.
/// </summary>
private void ReceiveSynchronously()
{
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
byte[] receiveBuffer = null;
this._receivingThreadClosed.Reset();
try
{
int mtu = (int) this.ITransportContext.IParameterProvider[GenuineParameter.UdpMtu];
for ( ; ; )
{
if (this._closing)
return ;
if (BufferPool.GENERAL_BUFFER_SIZE >= mtu)
receiveBuffer = BufferPool.ObtainBuffer();
else
receiveBuffer = new byte[mtu];
try
{
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
EndPoint endPointReference = ipEndPoint;
int bytesReceived = this._socket.ReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref endPointReference);
ipEndPoint = (IPEndPoint) endPointReference;
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Transport] > 0 )
{
binaryLogWriter.WriteTransportContentEvent(LogCategory.Transport, "UdpConnectionManager.ReceiveSynchronously",
LogMessageType.ReceivingFinished, null, null, null,
binaryLogWriter[LogCategory.Transport] > 1 ? new MemoryStream(GenuineUtility.CutOutBuffer(receiveBuffer, 0, bytesReceived)) : null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
this.DbgConnectionId, bytesReceived, ipEndPoint.ToString(),
null, null,
"Content is received from {0}.", ipEndPoint.ToString());
}
// parse the header
if (bytesReceived < HEADER_SIZE)
throw GenuineExceptions.Get_Receive_IncorrectData();
if (receiveBuffer[0] != MessageCoder.COMMAND_MAGIC_CODE)
throw GenuineExceptions.Get_Receive_IncorrectData();
// get the packet identifier
byte[] guidBuffer = new byte[16];
Buffer.BlockCopy(receiveBuffer, 1, guidBuffer, 0, 16);
Guid packetGuid = new Guid(guidBuffer);
// and chunk number
int chunkNumber = MessageCoder.ReadInt32(receiveBuffer, 17);
bool isLast = chunkNumber < 0;
if (chunkNumber < 0)
chunkNumber = - chunkNumber;
chunkNumber --;
// process the chunk
StreamAssembled streamAssembled;
lock (this._streams.SyncRoot)
{
streamAssembled = this._streams[packetGuid] as StreamAssembled;
if (streamAssembled == null)
this._streams[packetGuid] = streamAssembled = new StreamAssembled(ipEndPoint, HEADER_SIZE);
if (streamAssembled.IsProcessed)
continue;
}
string uri = "gudp://" + ipEndPoint.ToString();
HostInformation remote = this.ITransportContext.KnownHosts[uri];
remote.Renew(this._closeInvocationConnectionAfterInactivity, false);
if ((int) this.ITransportContext.IParameterProvider[GenuineParameter.CompatibilityLevel] <= 0)
remote.UpdateUri(uri, 0, false);
if (streamAssembled.BufferReceived(chunkNumber, receiveBuffer, bytesReceived, isLast))
{
// prepare it for processing
this._streams.Remove(packetGuid);
streamAssembled.IsProcessed = true;
// read the remote host URI
if ((int) this.ITransportContext.IParameterProvider[GenuineParameter.CompatibilityLevel] > 0)
{
BinaryReader binaryReader = new BinaryReader(streamAssembled);
// read the URI
byte[] uriBuffer = new byte[16];
GenuineUtility.ReadDataFromStream(streamAssembled, uriBuffer, 0, uriBuffer.Length);
Guid remoteHostUriGuid = new Guid(uriBuffer);
string receivedUri = "_gudp://" + remoteHostUriGuid.ToString("N");
// read the remote host unique identifier
int remoteHostUniqueIdentifier = binaryReader.ReadInt32();
// update the host information
remote.UpdateUri(receivedUri, remoteHostUniqueIdentifier, false);
// and skip the skip space
GenuineUtility.CopyStreamToStream(streamAssembled, Stream.Null, binaryReader.ReadInt16());
}
// LOG:
if ( remote.PhysicalAddress == null && binaryLogWriter != null && binaryLogWriter[LogCategory.HostInformation] > 0 )
{
binaryLogWriter.WriteHostInformationEvent("UdpConnectionManager.ReceiveSynchronously",
LogMessageType.HostInformationCreated, null, remote,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null,
this.DbgConnectionId,
"HostInformation is ready for actions.");
}
remote.PhysicalAddress = endPointReference;
this.ITransportContext.IIncomingStreamHandler.HandleMessage(streamAssembled, remote, GenuineConnectionType.Persistent, string.Empty, -1, false, this._iMessageRegistrator, null, null);
}
}
catch(Exception ex)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "UdpConnectionManager.ReceiveSynchronously",
LogMessageType.ReceivingFinished, ex, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null,
this.DbgConnectionId, 0, 0, 0, null, null, null, null,
"UDP socket failure.");
}
if (this._closing)
return ;
this.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(GenuineEventType.GUdpSocketException, ex, this.Local, null));
}
}
}
finally
{
this._receivingThreadClosed.Set();
}
}
#endregion
#region -- Socket initialization -----------------------------------------------------------
/// <summary>
/// Starts listening to the specified end point and accepting incoming connections.
/// </summary>
/// <param name="endPoint">The end point.</param>
public override void StartListening(object endPoint)
{
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
this._closing = false;
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteConnectionParameterEvent(LogCategory.Connection, "UdpConnectionManager.StartListening",
LogMessageType.ConnectionParameters, null, null, this.ITransportContext.IParameterProvider,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, this.DbgConnectionId,
"UDP socket is being associated with the end point: {0}.", endPoint.ToString());
}
// get the ip end point
IPEndPoint ipEndPoint = null;
int port;
string url;
try
{
url = (string) endPoint;
url = GenuineUtility.SplitToHostAndPort(url, out port);
ipEndPoint = new IPEndPoint(GenuineUtility.ResolveIPAddress(url), port);
}
catch(Exception ex)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "UdpConnectionManager.StartListening",
LogMessageType.ListeningStarted, ex, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, this.DbgConnectionId, 0, 0, 0, null, null, null, null,
"The listening socket cannot be associated with the {0} local end point.", endPoint.ToString());
}
throw GenuineExceptions.Get_Server_IncorrectAddressToListen(endPoint as string);
}
lock (this)
{
if (this._socket != null)
throw GenuineExceptions.Get_Server_EndPointIsAlreadyBeingListenedTo(this._socket.LocalEndPoint.ToString());
// initialize the socket
this._socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
if (this.ITransportContext.IParameterProvider[GenuineParameter.UdpTtl] != null)
this._socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, (int) this.ITransportContext.IParameterProvider[GenuineParameter.UdpTtl]);
// Receive buffer size
this._socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, (int) this.ITransportContext.IParameterProvider[GenuineParameter.UdpReceiveBuffer]);
this._socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
this._socket.Bind(ipEndPoint);
// if it's an IP multicast sender
if (this.ITransportContext.IParameterProvider[GenuineParameter.UdpMulticastTo] != null)
{
try
{
url = (string) this.ITransportContext.IParameterProvider[GenuineParameter.UdpMulticastTo];
url = GenuineUtility.SplitToHostAndPort(url, out port);
this._multicastTo = new IPEndPoint(GenuineUtility.ResolveIPAddress(url), port);
this._socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
if (this.ITransportContext.IParameterProvider[GenuineParameter.UdpTtl] != null)
this._socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, (int) this.ITransportContext.IParameterProvider[GenuineParameter.UdpTtl]);
}
catch(Exception)
{
throw GenuineExceptions.Get_Channel_InvalidParameter("UdpMulticastTo");
}
}
// and join to the specified broadcast network
if (this.ITransportContext.IParameterProvider[GenuineParameter.UdpJoinTo] != null)
{
string joinTo = (string) this.ITransportContext.IParameterProvider[GenuineParameter.UdpJoinTo];
this._socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
IPAddress ipAddressToJoinTo = GenuineUtility.ResolveIPAddress(joinTo);
MulticastOption multicastOption = new MulticastOption(ipAddressToJoinTo, ipEndPoint.Address);
this._socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multicastOption);
}
// initiate receiving
Thread receivingThread = new Thread(new ThreadStart(this.ReceiveSynchronously));
receivingThread.IsBackground = true;
receivingThread.Start();
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "UdpConnectionManager.StartListening",
LogMessageType.ConnectionEstablished, null, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null,
this.DbgConnectionId, (int) GenuineConnectionType.Invocation, 0, 0, this.GetType().Name, this._socket.LocalEndPoint.ToString(), null, null,
"The UDP socket is ready for action.");
}
}
}
/// <summary>
/// Stops listening to the specified end point. Does not close any connections.
/// </summary>
/// <param name="endPoint">The end point</param>
public override void StopListening(object endPoint)
{
lock (this)
{
if (this._socket == null)
return ;
// LOG:
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "UdpConnectionManager.StopListening",
LogMessageType.ListeningStopped, null, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, this.DbgConnectionId, 0, 0, 0, null, null, null, null,
"The listening socket is not longer associated with the {0} local end point.", endPoint == null ? string.Empty : endPoint.ToString());
}
SocketUtility.CloseSocket(this._socket);
this._socket = null;
this._closing = true;
}
if (! this._receivingThreadClosed.WaitOne(TimeSpan.FromMinutes(2), false))
throw GenuineExceptions.Get_Processing_LogicError("Receiving thread didn't exit within 2 minutes.");
}
/// <summary>
/// Closes the specified connections to the remote host and releases acquired resources.
/// </summary>
/// <param name="hostInformation">Host information.</param>
/// <param name="genuineConnectionType">What kind of connections will be affected by this operation.</param>
/// <param name="reason">Reason of resource releasing.</param>
public override void ReleaseConnections(HostInformation hostInformation, GenuineConnectionType genuineConnectionType, Exception reason)
{
}
#endregion
#region -- Closing and disposing -----------------------------------------------------------
/// <summary>
/// Releases all resources.
/// </summary>
/// <param name="reason">The reason of disposing.</param>
public override void InternalDispose(Exception reason)
{
this.StopListening(null);
}
#endregion
#region -- ITimerConsumer Members ----------------------------------------------------------
/// <summary>
/// Releases expired streams.
/// </summary>
public void TimerCallback()
{
int now = GenuineUtility.TickCount;
int releaseAfter = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.UdpAssembleTimeSpan]);
lock (this._streams.SyncRoot)
{
// gather expired stream
ArrayList itemsDeleted = new ArrayList();
foreach (DictionaryEntry entry in this._streams)
{
StreamAssembled streamAssembled = (StreamAssembled) entry.Value;
if (GenuineUtility.IsTimeoutExpired(streamAssembled.Started + releaseAfter, now)
&& ! streamAssembled.IsProcessed)
{
itemsDeleted.Add(entry.Key);
streamAssembled.Close();
}
}
// and remove them
foreach (object key in itemsDeleted)
this._streams.Remove(key);
}
}
#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 log4net;
using Npgsql;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using System;
using System.Data;
using System.Reflection;
namespace OpenSim.Data.PGSQL
{
public class UserProfilesData: IProfilesData
{
static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#region Properites
string ConnectionString
{
get; set;
}
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
#endregion Properties
#region class Member Functions
public UserProfilesData(string connectionString)
{
ConnectionString = connectionString;
Init();
}
void Init()
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, "UserProfiles");
m.Update();
}
}
#endregion Member Functions
#region Classifieds Queries
/// <summary>
/// Gets the classified records.
/// </summary>
/// <returns>
/// Array of classified records
/// </returns>
/// <param name='creatorId'>
/// Creator identifier.
/// </param>
public OSDArray GetClassifiedRecords(UUID creatorId)
{
OSDArray data = new OSDArray();
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
string query = @"SELECT ""classifieduuid"", ""name"" FROM classifieds WHERE ""creatoruuid"" = :Id";
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("Id", creatorId);
using( NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default))
{
if(reader.HasRows)
{
while (reader.Read())
{
OSDMap n = new OSDMap();
UUID Id = UUID.Zero;
string Name = null;
try
{
UUID.TryParse(Convert.ToString( reader["classifieduuid"]), out Id);
Name = Convert.ToString(reader["name"]);
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": UserAccount exception {0}", e.Message);
}
n.Add("classifieduuid", OSD.FromUUID(Id));
n.Add("name", OSD.FromString(Name));
data.Add(n);
}
}
}
}
}
return data;
}
public bool UpdateClassifiedRecord(UserClassifiedAdd ad, ref string result)
{
string query = @"INSERT INTO classifieds ( ""classifieduuid"",""creatoruuid"", ""creationdate"", ""expirationdate"", ""category"",
""name"", ""description"", ""parceluuid"", ""parentestate"", ""snapshotuuid"", ""simname"",
""posglobal"", ""parcelname"", ""classifiedflags"", ""priceforlisting"")
Select :ClassifiedId, :CreatorId, :CreatedDate, :ExpirationDate, :Category,
:Name, :Description, :ParcelId, :ParentEstate, :SnapshotId, :SimName
:GlobalPos, :ParcelName, :Flags, :ListingPrice
Where not exists( Select ""classifieduuid"" from classifieds where ""classifieduuid"" = :ClassifiedId );
update classifieds
set category =:Category,
expirationdate = :ExpirationDate,
name = :Name,
description = :Description,
parentestate = :ParentEstate,
posglobal = :GlobalPos,
parcelname = :ParcelName,
classifiedflags = :Flags,
priceforlisting = :ListingPrice,
snapshotuuid = :SnapshotId
where classifieduuid = :ClassifiedId ;
";
if(string.IsNullOrEmpty(ad.ParcelName))
ad.ParcelName = "Unknown";
if(ad.ParcelId == null)
ad.ParcelId = UUID.Zero;
if(string.IsNullOrEmpty(ad.Description))
ad.Description = "No Description";
DateTime epoch = new DateTime(1970, 1, 1);
DateTime now = DateTime.Now;
TimeSpan epochnow = now - epoch;
TimeSpan duration;
DateTime expiration;
TimeSpan epochexp;
if(ad.Flags == 2)
{
duration = new TimeSpan(7,0,0,0);
expiration = now.Add(duration);
epochexp = expiration - epoch;
}
else
{
duration = new TimeSpan(365,0,0,0);
expiration = now.Add(duration);
epochexp = expiration - epoch;
}
ad.CreationDate = (int)epochnow.TotalSeconds;
ad.ExpirationDate = (int)epochexp.TotalSeconds;
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("ClassifiedId", ad.ClassifiedId.ToString());
cmd.Parameters.AddWithValue("CreatorId", ad.CreatorId.ToString());
cmd.Parameters.AddWithValue("CreatedDate", ad.CreationDate.ToString());
cmd.Parameters.AddWithValue("ExpirationDate", ad.ExpirationDate.ToString());
cmd.Parameters.AddWithValue("Category", ad.Category.ToString());
cmd.Parameters.AddWithValue("Name", ad.Name.ToString());
cmd.Parameters.AddWithValue("Description", ad.Description.ToString());
cmd.Parameters.AddWithValue("ParcelId", ad.ParcelId.ToString());
cmd.Parameters.AddWithValue("ParentEstate", ad.ParentEstate.ToString());
cmd.Parameters.AddWithValue("SnapshotId", ad.SnapshotId.ToString ());
cmd.Parameters.AddWithValue("SimName", ad.SimName.ToString());
cmd.Parameters.AddWithValue("GlobalPos", ad.GlobalPos.ToString());
cmd.Parameters.AddWithValue("ParcelName", ad.ParcelName.ToString());
cmd.Parameters.AddWithValue("Flags", ad.Flags.ToString());
cmd.Parameters.AddWithValue("ListingPrice", ad.Price.ToString ());
cmd.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": ClassifiedesUpdate exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool DeleteClassifiedRecord(UUID recordId)
{
string query = string.Empty;
query = @"DELETE FROM classifieds WHERE classifieduuid = :ClasifiedId ;";
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("ClassifiedId", recordId.ToString());
cmd.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": DeleteClassifiedRecord exception {0}", e.Message);
return false;
}
return true;
}
public bool GetClassifiedInfo(ref UserClassifiedAdd ad, ref string result)
{
string query = string.Empty;
query += "SELECT * FROM classifieds WHERE ";
query += "classifieduuid = :AdId";
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("AdId", ad.ClassifiedId.ToString());
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
if(reader.Read ())
{
ad.CreatorId = GetUUID(reader["creatoruuid"]);
ad.ParcelId = GetUUID(reader["parceluuid"]);
ad.SnapshotId = GetUUID(reader["snapshotuuid"]);
ad.CreationDate = Convert.ToInt32(reader["creationdate"]);
ad.ExpirationDate = Convert.ToInt32(reader["expirationdate"]);
ad.ParentEstate = Convert.ToInt32(reader["parentestate"]);
ad.Flags = (byte)Convert.ToInt16(reader["classifiedflags"]);
ad.Category = Convert.ToInt32(reader["category"]);
ad.Price = Convert.ToInt16(reader["priceforlisting"]);
ad.Name = reader["name"].ToString();
ad.Description = reader["description"].ToString();
ad.SimName = reader["simname"].ToString();
ad.GlobalPos = reader["posglobal"].ToString();
ad.ParcelName = reader["parcelname"].ToString();
}
}
}
dbcon.Close();
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": GetPickInfo exception {0}", e.Message);
}
return true;
}
public static UUID GetUUID( object uuidValue ) {
UUID ret = UUID.Zero;
UUID.TryParse(uuidValue.ToString(), out ret);
return ret;
}
#endregion Classifieds Queries
#region Picks Queries
public OSDArray GetAvatarPicks(UUID avatarId)
{
string query = string.Empty;
query += "SELECT \"pickuuid\",\"name\" FROM userpicks WHERE ";
query += "creatoruuid = :Id";
OSDArray data = new OSDArray();
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("Id", avatarId.ToString());
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
if(reader.HasRows)
{
while (reader.Read())
{
OSDMap record = new OSDMap();
record.Add("pickuuid",OSD.FromString((string)reader["pickuuid"]));
record.Add("name",OSD.FromString((string)reader["name"]));
data.Add(record);
}
}
}
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": GetAvatarPicks exception {0}", e.Message);
}
return data;
}
public UserProfilePick GetPickInfo(UUID avatarId, UUID pickId)
{
string query = string.Empty;
UserProfilePick pick = new UserProfilePick();
query += "SELECT * FROM userpicks WHERE ";
query += "creatoruuid = :CreatorId AND ";
query += "pickuuid = :PickId";
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("CreatorId", avatarId.ToString());
cmd.Parameters.AddWithValue("PickId", pickId.ToString());
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
if(reader.HasRows)
{
reader.Read();
string description = (string)reader["description"];
if (string.IsNullOrEmpty(description))
description = "No description given.";
UUID.TryParse((string)reader["pickuuid"], out pick.PickId);
UUID.TryParse((string)reader["creatoruuid"], out pick.CreatorId);
UUID.TryParse((string)reader["parceluuid"], out pick.ParcelId);
UUID.TryParse((string)reader["snapshotuuid"], out pick.SnapshotId);
pick.GlobalPos = (string)reader["posglobal"];
bool.TryParse((string)reader["toppick"], out pick.TopPick);
bool.TryParse((string)reader["enabled"], out pick.Enabled);
pick.Name = (string)reader["name"];
pick.Desc = description;
pick.User = (string)reader["user"];
pick.OriginalName = (string)reader["originalname"];
pick.SimName = (string)reader["simname"];
pick.SortOrder = (int)reader["sortorder"];
}
}
}
dbcon.Close();
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": GetPickInfo exception {0}", e.Message);
}
return pick;
}
public bool UpdatePicksRecord(UserProfilePick pick)
{
string query = string.Empty;
query = @"INSERT INTO userpicks VALUES ( :PickId, :CreatorId, :TopPick, :ParcelId,:Name, :Desc, :SnapshotId,:User,
:Original, :SimName, :GlobalPos, :SortOrder, :Enabled)
where not exists ( select pickid from userpicks where pickid = :pickid);
Update userpicks
set parceluuid = :ParcelId,
name = :Name,
description = :Desc,
snapshotuuid = :SnapshotId,
pickuuid = :PickId,
posglobal = :GlobalPos
where pickid = :PickId;
";
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("PickId", pick.PickId.ToString());
cmd.Parameters.AddWithValue("CreatorId", pick.CreatorId.ToString());
cmd.Parameters.AddWithValue("TopPick", pick.TopPick.ToString());
cmd.Parameters.AddWithValue("ParcelId", pick.ParcelId.ToString());
cmd.Parameters.AddWithValue("Name", pick.Name.ToString());
cmd.Parameters.AddWithValue("Desc", pick.Desc.ToString());
cmd.Parameters.AddWithValue("SnapshotId", pick.SnapshotId.ToString());
cmd.Parameters.AddWithValue("User", pick.User.ToString());
cmd.Parameters.AddWithValue("Original", pick.OriginalName.ToString());
cmd.Parameters.AddWithValue("SimName",pick.SimName.ToString());
cmd.Parameters.AddWithValue("GlobalPos", pick.GlobalPos);
cmd.Parameters.AddWithValue("SortOrder", pick.SortOrder.ToString ());
cmd.Parameters.AddWithValue("Enabled", pick.Enabled.ToString());
cmd.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": UpdateAvatarNotes exception {0}", e.Message);
return false;
}
return true;
}
public bool DeletePicksRecord(UUID pickId)
{
string query = string.Empty;
query += "DELETE FROM userpicks WHERE ";
query += "pickuuid = :PickId";
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("PickId", pickId.ToString());
cmd.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": DeleteUserPickRecord exception {0}", e.Message);
return false;
}
return true;
}
#endregion Picks Queries
#region Avatar Notes Queries
public bool GetAvatarNotes(ref UserProfileNotes notes)
{ // WIP
string query = string.Empty;
query += "SELECT \"notes\" FROM usernotes WHERE ";
query += "useruuid = :Id AND ";
query += "targetuuid = :TargetId";
OSDArray data = new OSDArray();
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("Id", notes.UserId.ToString());
cmd.Parameters.AddWithValue("TargetId", notes.TargetId.ToString());
using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.HasRows)
{
reader.Read();
notes.Notes = OSD.FromString((string)reader["notes"]);
}
}
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": GetAvatarNotes exception {0}", e.Message);
}
return true;
}
public bool UpdateAvatarNotes(ref UserProfileNotes note, ref string result)
{
string query = string.Empty;
bool remove;
if(string.IsNullOrEmpty(note.Notes))
{
remove = true;
query += "DELETE FROM usernotes WHERE ";
query += "useruuid=:UserId AND ";
query += "targetuuid=:TargetId";
}
else
{
remove = false;
query = @"INSERT INTO usernotes VALUES ( :UserId, :TargetId, :Notes )
where not exists ( Select useruuid from usernotes where useruuid = :UserId and targetuuid = :TargetId );
update usernotes
set notes = :Notes
where useruuid = :UserId
and targetuuid = :TargetId;
";
}
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
if(!remove)
cmd.Parameters.AddWithValue("Notes", note.Notes);
cmd.Parameters.AddWithValue("TargetId", note.TargetId.ToString ());
cmd.Parameters.AddWithValue("UserId", note.UserId.ToString());
cmd.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": UpdateAvatarNotes exception {0}", e.Message);
return false;
}
return true;
}
#endregion Avatar Notes Queries
#region Avatar Properties
public bool GetAvatarProperties(ref UserProfileProperties props, ref string result)
{
string query = string.Empty;
query += "SELECT * FROM userprofile WHERE ";
query += "useruuid = :Id";
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("Id", props.UserId.ToString());
using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.HasRows)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": Getting data for {0}.", props.UserId);
reader.Read();
props.WebUrl = (string)reader["profileURL"];
UUID.TryParse((string)reader["profileImage"], out props.ImageId);
props.AboutText = (string)reader["profileAboutText"];
UUID.TryParse((string)reader["profileFirstImage"], out props.FirstLifeImageId);
props.FirstLifeText = (string)reader["profileFirstText"];
UUID.TryParse((string)reader["profilePartner"], out props.PartnerId);
props.WantToMask = (int)reader["profileWantToMask"];
props.WantToText = (string)reader["profileWantToText"];
props.SkillsMask = (int)reader["profileSkillsMask"];
props.SkillsText = (string)reader["profileSkillsText"];
props.Language = (string)reader["profileLanguages"];
}
else
{
m_log.DebugFormat("[PROFILES_DATA]" +
": No data for {0}", props.UserId);
props.WebUrl = string.Empty;
props.ImageId = UUID.Zero;
props.AboutText = string.Empty;
props.FirstLifeImageId = UUID.Zero;
props.FirstLifeText = string.Empty;
props.PartnerId = UUID.Zero;
props.WantToMask = 0;
props.WantToText = string.Empty;
props.SkillsMask = 0;
props.SkillsText = string.Empty;
props.Language = string.Empty;
props.PublishProfile = false;
props.PublishMature = false;
query = "INSERT INTO userprofile (";
query += "useruuid, ";
query += "profilePartner, ";
query += "profileAllowPublish, ";
query += "profileMaturePublish, ";
query += "profileURL, ";
query += "profileWantToMask, ";
query += "profileWantToText, ";
query += "profileSkillsMask, ";
query += "profileSkillsText, ";
query += "profileLanguages, ";
query += "profileImage, ";
query += "profileAboutText, ";
query += "profileFirstImage, ";
query += "profileFirstText) VALUES (";
query += ":userId, ";
query += ":profilePartner, ";
query += ":profileAllowPublish, ";
query += ":profileMaturePublish, ";
query += ":profileURL, ";
query += ":profileWantToMask, ";
query += ":profileWantToText, ";
query += ":profileSkillsMask, ";
query += ":profileSkillsText, ";
query += ":profileLanguages, ";
query += ":profileImage, ";
query += ":profileAboutText, ";
query += ":profileFirstImage, ";
query += ":profileFirstText)";
dbcon.Close();
dbcon.Open();
using (NpgsqlCommand put = new NpgsqlCommand(query, dbcon))
{
put.Parameters.AddWithValue("userId", props.UserId.ToString());
put.Parameters.AddWithValue("profilePartner", props.PartnerId.ToString());
put.Parameters.AddWithValue("profileAllowPublish", props.PublishProfile);
put.Parameters.AddWithValue("profileMaturePublish", props.PublishMature);
put.Parameters.AddWithValue("profileURL", props.WebUrl);
put.Parameters.AddWithValue("profileWantToMask", props.WantToMask);
put.Parameters.AddWithValue("profileWantToText", props.WantToText);
put.Parameters.AddWithValue("profileSkillsMask", props.SkillsMask);
put.Parameters.AddWithValue("profileSkillsText", props.SkillsText);
put.Parameters.AddWithValue("profileLanguages", props.Language);
put.Parameters.AddWithValue("profileImage", props.ImageId.ToString());
put.Parameters.AddWithValue("profileAboutText", props.AboutText);
put.Parameters.AddWithValue("profileFirstImage", props.FirstLifeImageId.ToString());
put.Parameters.AddWithValue("profileFirstText", props.FirstLifeText);
put.ExecuteNonQuery();
}
}
}
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": Requst properties exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool UpdateAvatarProperties(ref UserProfileProperties props, ref string result)
{
string query = string.Empty;
query += "UPDATE userprofile SET ";
query += "profileURL=:profileURL, ";
query += "profileImage=:image, ";
query += "profileAboutText=:abouttext,";
query += "profileFirstImage=:firstlifeimage,";
query += "profileFirstText=:firstlifetext ";
query += "WHERE useruuid=:uuid";
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("profileURL", props.WebUrl);
cmd.Parameters.AddWithValue("image", props.ImageId.ToString());
cmd.Parameters.AddWithValue("abouttext", props.AboutText);
cmd.Parameters.AddWithValue("firstlifeimage", props.FirstLifeImageId.ToString());
cmd.Parameters.AddWithValue("firstlifetext", props.FirstLifeText);
cmd.Parameters.AddWithValue("uuid", props.UserId.ToString());
cmd.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": AgentPropertiesUpdate exception {0}", e.Message);
return false;
}
return true;
}
#endregion Avatar Properties
#region Avatar Interests
public bool UpdateAvatarInterests(UserProfileProperties up, ref string result)
{
string query = string.Empty;
query += "UPDATE userprofile SET ";
query += "profileWantToMask=:WantMask, ";
query += "profileWantToText=:WantText,";
query += "profileSkillsMask=:SkillsMask,";
query += "profileSkillsText=:SkillsText, ";
query += "profileLanguages=:Languages ";
query += "WHERE useruuid=:uuid";
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("WantMask", up.WantToMask);
cmd.Parameters.AddWithValue("WantText", up.WantToText);
cmd.Parameters.AddWithValue("SkillsMask", up.SkillsMask);
cmd.Parameters.AddWithValue("SkillsText", up.SkillsText);
cmd.Parameters.AddWithValue("Languages", up.Language);
cmd.Parameters.AddWithValue("uuid", up.UserId.ToString());
cmd.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": AgentInterestsUpdate exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
#endregion Avatar Interests
public OSDArray GetUserImageAssets(UUID avatarId)
{
OSDArray data = new OSDArray();
string query = "SELECT \"snapshotuuid\" FROM {0} WHERE \"creatoruuid\" = :Id";
// Get classified image assets
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format (query,"\"classifieds\""), dbcon))
{
cmd.Parameters.AddWithValue("Id", avatarId.ToString());
using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.HasRows)
{
while (reader.Read())
{
data.Add(new OSDString((string)reader["snapshotuuid"].ToString ()));
}
}
}
}
dbcon.Close();
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format (query,"\"userpicks\""), dbcon))
{
cmd.Parameters.AddWithValue("Id", avatarId.ToString());
using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.HasRows)
{
while (reader.Read())
{
data.Add(new OSDString((string)reader["snapshotuuid"].ToString ()));
}
}
}
}
dbcon.Close();
dbcon.Open();
query = "SELECT \"profileImage\", \"profileFirstImage\" FROM \"userprofile\" WHERE \"useruuid\" = :Id";
using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format (query,"\"userpicks\""), dbcon))
{
cmd.Parameters.AddWithValue("Id", avatarId.ToString());
using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.HasRows)
{
while (reader.Read())
{
data.Add(new OSDString((string)reader["profileImage"].ToString ()));
data.Add(new OSDString((string)reader["profileFirstImage"].ToString ()));
}
}
}
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": GetAvatarNotes exception {0}", e.Message);
}
return data;
}
#region User Preferences
public bool GetUserPreferences(ref UserPreferences pref, ref string result)
{
string query = string.Empty;
query += "SELECT imviaemail,visible,email FROM ";
query += "usersettings WHERE ";
query += "useruuid = :Id";
OSDArray data = new OSDArray();
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("Id", pref.UserId.ToString());
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
if(reader.HasRows)
{
reader.Read();
bool.TryParse((string)reader["imviaemail"], out pref.IMViaEmail);
bool.TryParse((string)reader["visible"], out pref.Visible);
pref.EMail = (string)reader["email"];
}
else
{
using (NpgsqlCommand put = new NpgsqlCommand(query, dbcon))
{
query = "INSERT INTO usersettings VALUES ";
query += "(:Id,'false','false', '')";
put.ExecuteNonQuery();
}
}
}
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": Get preferences exception {0}", e.Message);
result = e.Message;
}
return true;
}
public bool UpdateUserPreferences(ref UserPreferences pref, ref string result)
{
string query = string.Empty;
query += "UPDATE usersettings SET ";
query += "imviaemail=:ImViaEmail, ";
query += "visible=:Visible,";
query += "WHERE useruuid=:uuid";
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("ImViaEmail", pref.IMViaEmail.ToString().ToLower ());
cmd.Parameters.AddWithValue("Visible", pref.Visible.ToString().ToLower ());
cmd.Parameters.AddWithValue("uuid", pref.UserId.ToString());
cmd.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": AgentInterestsUpdate exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
#endregion User Preferences
#region Integration
public bool GetUserAppData(ref UserAppData props, ref string result)
{
string query = string.Empty;
query += "SELECT * FROM userdata WHERE ";
query += "\"UserId\" = :Id AND ";
query += "\"TagId\" = :TagId";
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("Id", props.UserId.ToString());
cmd.Parameters.AddWithValue (":TagId", props.TagId.ToString());
using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.HasRows)
{
reader.Read();
props.DataKey = (string)reader["DataKey"];
props.DataVal = (string)reader["DataVal"];
}
else
{
query += "INSERT INTO userdata VALUES ( ";
query += ":UserId,";
query += ":TagId,";
query += ":DataKey,";
query += ":DataVal) ";
using (NpgsqlCommand put = new NpgsqlCommand(query, dbcon))
{
put.Parameters.AddWithValue("Id", props.UserId.ToString());
put.Parameters.AddWithValue("TagId", props.TagId.ToString());
put.Parameters.AddWithValue("DataKey", props.DataKey.ToString());
put.Parameters.AddWithValue("DataVal", props.DataVal.ToString());
put.ExecuteNonQuery();
}
}
}
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": Requst application data exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool SetUserAppData(UserAppData props, ref string result)
{
string query = string.Empty;
query += "UPDATE userdata SET ";
query += "\"TagId\" = :TagId, ";
query += "\"DataKey\" = :DataKey, ";
query += "\"DataVal\" = :DataVal WHERE ";
query += "\"UserId\" = :UserId AND ";
query += "\"TagId\" = :TagId";
try
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("UserId", props.UserId.ToString());
cmd.Parameters.AddWithValue("TagId", props.TagId.ToString ());
cmd.Parameters.AddWithValue("DataKey", props.DataKey.ToString ());
cmd.Parameters.AddWithValue("DataVal", props.DataKey.ToString ());
cmd.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES_DATA]" +
": SetUserData exception {0}", e.Message);
return false;
}
return true;
}
#endregion Integration
}
}
| |
// 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.Immutable;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Analyzer.Utilities;
using System.Threading;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis.Editing;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
/// <summary>
/// CA1066: Implement IEquatable when overriding Object.Equals
/// CA1067: Override Object.Equals(object) when implementing IEquatable{T}
/// </summary>
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic), Shared]
public sealed class EquatableFixer : CodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds =>
ImmutableArray.Create(EquatableAnalyzer.ImplementIEquatableRuleId, EquatableAnalyzer.OverrideObjectEqualsRuleId);
public override FixAllProvider GetFixAllProvider()
{
// See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for more information on Fix All Providers
return WellKnownFixAllProviders.BatchFixer;
}
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
SyntaxGenerator generator = SyntaxGenerator.GetGenerator(context.Document);
SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
SyntaxNode declaration = root.FindNode(context.Span);
declaration = generator.GetDeclaration(declaration);
if (declaration == null)
{
return;
}
SemanticModel model =
await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
if (!(model.GetDeclaredSymbol(declaration, context.CancellationToken) is INamedTypeSymbol type) || type.TypeKind != TypeKind.Class && type.TypeKind != TypeKind.Struct)
{
return;
}
INamedTypeSymbol? equatableType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIEquatable1);
if (equatableType == null)
{
return;
}
if (type.TypeKind == TypeKind.Struct && !TypeImplementsEquatable(type, equatableType))
{
string title = MicrosoftCodeQualityAnalyzersResources.ImplementEquatable;
context.RegisterCodeFix(new MyCodeAction(
title,
async ct =>
await ImplementEquatableInStructAsync(context.Document, declaration, type, model.Compilation,
equatableType, ct).ConfigureAwait(false),
equivalenceKey: title), context.Diagnostics);
}
if (!type.OverridesEquals())
{
string title = MicrosoftCodeQualityAnalyzersResources.OverrideEqualsOnImplementingIEquatableCodeActionTitle;
context.RegisterCodeFix(new MyCodeAction(
title,
async ct =>
await OverrideObjectEqualsAsync(context.Document, declaration, type, equatableType,
ct).ConfigureAwait(false),
equivalenceKey: title), context.Diagnostics);
}
}
private static bool TypeImplementsEquatable(INamedTypeSymbol type, INamedTypeSymbol equatableType)
{
INamedTypeSymbol constructedEquatable = equatableType.Construct(type);
INamedTypeSymbol implementation = type
.Interfaces
.FirstOrDefault(x => x.Equals(constructedEquatable));
return implementation != null;
}
private static async Task<Document> ImplementEquatableInStructAsync(Document document, SyntaxNode declaration,
INamedTypeSymbol typeSymbol, Compilation compilation, INamedTypeSymbol equatableType,
CancellationToken cancellationToken)
{
var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var generator = editor.Generator;
var equalsMethod = generator.MethodDeclaration(
WellKnownMemberNames.ObjectEquals,
new[]
{
generator.ParameterDeclaration("other", generator.TypeExpression(typeSymbol))
},
returnType: generator.TypeExpression(SpecialType.System_Boolean),
accessibility: Accessibility.Public,
statements: generator.DefaultMethodBody(compilation));
editor.AddMember(declaration, equalsMethod);
INamedTypeSymbol constructedType = equatableType.Construct(typeSymbol);
editor.AddInterfaceType(declaration, generator.TypeExpression(constructedType));
return editor.GetChangedDocument();
}
private static async Task<Document> OverrideObjectEqualsAsync(Document document, SyntaxNode declaration,
INamedTypeSymbol typeSymbol, INamedTypeSymbol equatableType, CancellationToken cancellationToken)
{
var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var generator = editor.Generator;
var argumentName = generator.IdentifierName("obj");
SyntaxNode returnStatement;
if (HasExplicitEqualsImplementation(typeSymbol, equatableType))
{
returnStatement = typeSymbol.TypeKind == TypeKind.Class
? GetReturnStatementForExplicitClass(generator, typeSymbol, argumentName, equatableType)
: GetReturnStatementForExplicitStruct(generator, typeSymbol, argumentName, equatableType);
}
else
{
returnStatement = typeSymbol.TypeKind == TypeKind.Class
? GetReturnStatementForImplicitClass(generator, typeSymbol, argumentName)
: GetReturnStatementForImplicitStruct(generator, typeSymbol, argumentName);
}
var equalsMethod = generator.MethodDeclaration(
WellKnownMemberNames.ObjectEquals,
new[]
{
generator.ParameterDeclaration(argumentName.ToString(),
generator.TypeExpression(SpecialType.System_Object))
},
returnType: generator.TypeExpression(SpecialType.System_Boolean),
accessibility: Accessibility.Public,
modifiers: DeclarationModifiers.Override,
statements: new[] { returnStatement });
editor.AddMember(declaration, equalsMethod);
return editor.GetChangedDocument();
}
private static bool HasExplicitEqualsImplementation(INamedTypeSymbol typeSymbol, INamedTypeSymbol equatableType)
{
INamedTypeSymbol constructedType = equatableType.Construct(typeSymbol);
IMethodSymbol constructedEqualsMethod = constructedType.GetMembers().OfType<IMethodSymbol>().FirstOrDefault();
foreach (IMethodSymbol method in typeSymbol.GetMembers().OfType<IMethodSymbol>())
{
foreach (IMethodSymbol explicitImplementation in method.ExplicitInterfaceImplementations)
{
if (explicitImplementation.Equals(constructedEqualsMethod))
{
return true;
}
}
}
return false;
}
private static SyntaxNode GetReturnStatementForExplicitClass(SyntaxGenerator generator,
INamedTypeSymbol typeSymbol, SyntaxNode argumentName, INamedTypeSymbol equatableType)
{
return generator.ReturnStatement(
generator.InvocationExpression(
generator.MemberAccessExpression(
generator.CastExpression(
equatableType.Construct(typeSymbol),
generator.ThisExpression()),
WellKnownMemberNames.ObjectEquals),
generator.TryCastExpression(
argumentName,
typeSymbol)));
}
private static SyntaxNode GetReturnStatementForExplicitStruct(SyntaxGenerator generator,
INamedTypeSymbol typeSymbol, SyntaxNode argumentName, INamedTypeSymbol equatableType)
{
return generator.ReturnStatement(
generator.LogicalAndExpression(
generator.IsTypeExpression(
argumentName,
typeSymbol),
generator.InvocationExpression(
generator.MemberAccessExpression(
generator.CastExpression(
equatableType.Construct(typeSymbol),
generator.ThisExpression()),
WellKnownMemberNames.ObjectEquals),
generator.CastExpression(
typeSymbol,
argumentName))));
}
private static SyntaxNode GetReturnStatementForImplicitClass(SyntaxGenerator generator,
INamedTypeSymbol typeSymbol, SyntaxNode argumentName)
{
return generator.ReturnStatement(
generator.InvocationExpression(
generator.IdentifierName(WellKnownMemberNames.ObjectEquals),
generator.Argument(
generator.TryCastExpression(
argumentName,
typeSymbol))));
}
private static SyntaxNode GetReturnStatementForImplicitStruct(SyntaxGenerator generator,
INamedTypeSymbol typeSymbol, SyntaxNode argumentName)
{
return generator.ReturnStatement(
generator.LogicalAndExpression(
generator.IsTypeExpression(
argumentName,
typeSymbol),
generator.InvocationExpression(
generator.IdentifierName(WellKnownMemberNames.ObjectEquals),
generator.CastExpression(
typeSymbol,
argumentName))));
}
// Needed for Telemetry (https://github.com/dotnet/roslyn-analyzers/issues/192)
private class MyCodeAction : DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey)
: base(title, createChangedDocument, equivalenceKey)
{
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace WebApiSample.Service.WebApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Orleans.Providers.Streams.AzureQueue;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Streams;
using TestExtensions;
using Xunit;
using Xunit.Abstractions;
using Orleans.Configuration;
using Orleans.Serialization;
namespace Tester.AzureUtils.Streaming
{
[Collection(TestEnvironmentFixture.DefaultCollection)]
[TestCategory("Azure"), TestCategory("Streaming")]
public class AzureQueueAdapterTests : AzureStorageBasicTests, IDisposable
{
private readonly ITestOutputHelper output;
private readonly TestEnvironmentFixture fixture;
private const int NumBatches = 20;
private const int NumMessagesPerBatch = 20;
public static readonly string AZURE_QUEUE_STREAM_PROVIDER_NAME = "AQAdapterTests";
private readonly ILoggerFactory loggerFactory;
private static readonly SafeRandom Random = new SafeRandom();
private static List<string> azureQueueNames = AzureQueueUtilities.GenerateQueueNames($"AzureQueueAdapterTests-{Guid.NewGuid()}", 8);
public AzureQueueAdapterTests(ITestOutputHelper output, TestEnvironmentFixture fixture)
{
this.output = output;
this.fixture = fixture;
this.loggerFactory = this.fixture.Services.GetService<ILoggerFactory>();
BufferPool.InitGlobalBufferPool(new SiloMessagingOptions());
}
public void Dispose()
{
if (!string.IsNullOrWhiteSpace(TestDefaultConfiguration.DataConnectionString))
{
AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(this.loggerFactory, azureQueueNames, TestDefaultConfiguration.DataConnectionString).Wait();
}
}
[SkippableFact, TestCategory("Functional"), TestCategory("Halo")]
public async Task SendAndReceiveFromAzureQueue()
{
var options = new AzureQueueOptions
{
ConnectionString = TestDefaultConfiguration.DataConnectionString,
MessageVisibilityTimeout = TimeSpan.FromSeconds(30),
QueueNames = azureQueueNames
};
var serializationManager = this.fixture.Services.GetService<SerializationManager>();
var clusterOptions = this.fixture.Services.GetRequiredService<IOptions<ClusterOptions>>();
var queueCacheOptions = new SimpleQueueCacheOptions();
var queueDataAdapter = new AzureQueueDataAdapterV2(serializationManager);
var adapterFactory = new AzureQueueAdapterFactory(
AZURE_QUEUE_STREAM_PROVIDER_NAME,
options,
queueCacheOptions,
queueDataAdapter,
this.fixture.Services,
clusterOptions,
serializationManager,
loggerFactory);
adapterFactory.Init();
await SendAndReceiveFromQueueAdapter(adapterFactory);
}
private async Task SendAndReceiveFromQueueAdapter(IQueueAdapterFactory adapterFactory)
{
IQueueAdapter adapter = await adapterFactory.CreateAdapter();
IQueueAdapterCache cache = adapterFactory.GetQueueAdapterCache();
// Create receiver per queue
IStreamQueueMapper mapper = adapterFactory.GetStreamQueueMapper();
Dictionary<QueueId, IQueueAdapterReceiver> receivers = mapper.GetAllQueues().ToDictionary(queueId => queueId, adapter.CreateReceiver);
Dictionary<QueueId, IQueueCache> caches = mapper.GetAllQueues().ToDictionary(queueId => queueId, cache.CreateQueueCache);
await Task.WhenAll(receivers.Values.Select(receiver => receiver.Initialize(TimeSpan.FromSeconds(5))));
// test using 2 streams
Guid streamId1 = Guid.NewGuid();
Guid streamId2 = Guid.NewGuid();
int receivedBatches = 0;
var streamsPerQueue = new ConcurrentDictionary<QueueId, HashSet<IStreamIdentity>>();
// reader threads (at most 2 active queues because only two streams)
var work = new List<Task>();
foreach( KeyValuePair<QueueId, IQueueAdapterReceiver> receiverKvp in receivers)
{
QueueId queueId = receiverKvp.Key;
var receiver = receiverKvp.Value;
var qCache = caches[queueId];
Task task = Task.Factory.StartNew(() =>
{
while (receivedBatches < NumBatches)
{
var messages = receiver.GetQueueMessagesAsync(CloudQueueMessage.MaxNumberOfMessagesToPeek).Result.ToArray();
if (!messages.Any())
{
continue;
}
foreach (IBatchContainer message in messages)
{
streamsPerQueue.AddOrUpdate(queueId,
id => new HashSet<IStreamIdentity> { new StreamIdentity(message.StreamGuid, message.StreamGuid.ToString()) },
(id, set) =>
{
set.Add(new StreamIdentity(message.StreamGuid, message.StreamGuid.ToString()));
return set;
});
this.output.WriteLine("Queue {0} received message on stream {1}", queueId,
message.StreamGuid);
Assert.Equal(NumMessagesPerBatch / 2, message.GetEvents<int>().Count()); // "Half the events were ints"
Assert.Equal(NumMessagesPerBatch / 2, message.GetEvents<string>().Count()); // "Half the events were strings"
}
Interlocked.Add(ref receivedBatches, messages.Length);
qCache.AddToCache(messages);
}
});
work.Add(task);
}
// send events
List<object> events = CreateEvents(NumMessagesPerBatch);
work.Add(Task.Factory.StartNew(() => Enumerable.Range(0, NumBatches)
.Select(i => i % 2 == 0 ? streamId1 : streamId2)
.ToList()
.ForEach(streamId =>
adapter.QueueMessageBatchAsync(streamId, streamId.ToString(),
events.Take(NumMessagesPerBatch).ToArray(), null, RequestContextExtensions.Export(this.fixture.SerializationManager)).Wait())));
await Task.WhenAll(work);
// Make sure we got back everything we sent
Assert.Equal(NumBatches, receivedBatches);
// check to see if all the events are in the cache and we can enumerate through them
StreamSequenceToken firstInCache = new EventSequenceTokenV2(0);
foreach (KeyValuePair<QueueId, HashSet<IStreamIdentity>> kvp in streamsPerQueue)
{
var receiver = receivers[kvp.Key];
var qCache = caches[kvp.Key];
foreach (IStreamIdentity streamGuid in kvp.Value)
{
// read all messages in cache for stream
IQueueCacheCursor cursor = qCache.GetCacheCursor(streamGuid, firstInCache);
int messageCount = 0;
StreamSequenceToken tenthInCache = null;
StreamSequenceToken lastToken = firstInCache;
while (cursor.MoveNext())
{
Exception ex;
messageCount++;
IBatchContainer batch = cursor.GetCurrent(out ex);
this.output.WriteLine("Token: {0}", batch.SequenceToken);
Assert.True(batch.SequenceToken.CompareTo(lastToken) >= 0, $"order check for event {messageCount}");
lastToken = batch.SequenceToken;
if (messageCount == 10)
{
tenthInCache = batch.SequenceToken;
}
}
this.output.WriteLine("On Queue {0} we received a total of {1} message on stream {2}", kvp.Key, messageCount, streamGuid);
Assert.Equal(NumBatches / 2, messageCount);
Assert.NotNull(tenthInCache);
// read all messages from the 10th
cursor = qCache.GetCacheCursor(streamGuid, tenthInCache);
messageCount = 0;
while (cursor.MoveNext())
{
messageCount++;
}
this.output.WriteLine("On Queue {0} we received a total of {1} message on stream {2}", kvp.Key, messageCount, streamGuid);
const int expected = NumBatches / 2 - 10 + 1; // all except the first 10, including the 10th (10 + 1)
Assert.Equal(expected, messageCount);
}
}
}
private List<object> CreateEvents(int count)
{
return Enumerable.Range(0, count).Select(i =>
{
if (i % 2 == 0)
{
return Random.Next(int.MaxValue) as object;
}
return Random.Next(int.MaxValue).ToString(CultureInfo.InvariantCulture);
}).ToList();
}
internal static string MakeClusterId()
{
const string DeploymentIdFormat = "cluster-{0}";
string now = DateTime.UtcNow.ToString("yyyy-MM-dd-hh-mm-ss-ffff");
return string.Format(DeploymentIdFormat, now);
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace IO.Swagger.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class Borrower : IEquatable<Borrower>
{
/// <summary>
/// Initializes a new instance of the <see cref="Borrower" /> class.
/// Initializes a new instance of the <see cref="Borrower" />class.
/// </summary>
/// <param name="Forename">Forename (required).</param>
/// <param name="MiddleName">MiddleName.</param>
/// <param name="Surname">Surname (required).</param>
/// <param name="Token">Token (required).</param>
/// <param name="Id">Id (required).</param>
public Borrower(string Forename = null, string MiddleName = null, string Surname = null, string Token = null, string Id = null)
{
// to ensure "Forename" is required (not null)
if (Forename == null)
{
throw new InvalidDataException("Forename is a required property for Borrower and cannot be null");
}
else
{
this.Forename = Forename;
}
// to ensure "Surname" is required (not null)
if (Surname == null)
{
throw new InvalidDataException("Surname is a required property for Borrower and cannot be null");
}
else
{
this.Surname = Surname;
}
// to ensure "Token" is required (not null)
if (Token == null)
{
throw new InvalidDataException("Token is a required property for Borrower and cannot be null");
}
else
{
this.Token = Token;
}
// to ensure "Id" is required (not null)
if (Id == null)
{
throw new InvalidDataException("Id is a required property for Borrower and cannot be null");
}
else
{
this.Id = Id;
}
this.MiddleName = MiddleName;
}
/// <summary>
/// Gets or Sets Forename
/// </summary>
[DataMember(Name="forename", EmitDefaultValue=false)]
public string Forename { get; set; }
/// <summary>
/// Gets or Sets MiddleName
/// </summary>
[DataMember(Name="middle_name", EmitDefaultValue=false)]
public string MiddleName { get; set; }
/// <summary>
/// Gets or Sets Surname
/// </summary>
[DataMember(Name="surname", EmitDefaultValue=false)]
public string Surname { get; set; }
/// <summary>
/// Gets or Sets Token
/// </summary>
[DataMember(Name="token", EmitDefaultValue=false)]
public string Token { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Borrower {\n");
sb.Append(" Forename: ").Append(Forename).Append("\n");
sb.Append(" MiddleName: ").Append(MiddleName).Append("\n");
sb.Append(" Surname: ").Append(Surname).Append("\n");
sb.Append(" Token: ").Append(Token).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as Borrower);
}
/// <summary>
/// Returns true if Borrower instances are equal
/// </summary>
/// <param name="other">Instance of Borrower to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Borrower other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Forename == other.Forename ||
this.Forename != null &&
this.Forename.Equals(other.Forename)
) &&
(
this.MiddleName == other.MiddleName ||
this.MiddleName != null &&
this.MiddleName.Equals(other.MiddleName)
) &&
(
this.Surname == other.Surname ||
this.Surname != null &&
this.Surname.Equals(other.Surname)
) &&
(
this.Token == other.Token ||
this.Token != null &&
this.Token.Equals(other.Token)
) &&
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Forename != null)
hash = hash * 59 + this.Forename.GetHashCode();
if (this.MiddleName != null)
hash = hash * 59 + this.MiddleName.GetHashCode();
if (this.Surname != null)
hash = hash * 59 + this.Surname.GetHashCode();
if (this.Token != null)
hash = hash * 59 + this.Token.GetHashCode();
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
return hash;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
namespace System
{
/// <summary>
/// Helper so we can call some tuple methods recursively without knowing the underlying types.
/// </summary>
internal interface ITupleInternal : ITuple
{
string ToString(StringBuilder sb);
int GetHashCode(IEqualityComparer comparer);
}
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));
}
// Note: F# compiler depends on the exact tuple hashing algorithm. Do not ever change it.
// 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]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1; // Do not rename (binary serialization)
public T1 Item1 => m_Item1;
public Tuple(T1 item1)
{
m_Item1 = item1;
}
public override bool Equals(object? obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer)
{
if (other == null) return false;
if (!(other is Tuple<T1> objTuple))
{
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1);
}
int IComparable.CompareTo(object? obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo(object? other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is Tuple<T1> objTuple))
{
throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other));
}
return comparer.Compare(m_Item1, objTuple.m_Item1);
}
public override int GetHashCode()
{
return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return comparer.GetHashCode(m_Item1!);
}
int ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('(');
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.ToString(StringBuilder sb)
{
sb.Append(m_Item1);
sb.Append(')');
return sb.ToString();
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 1;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object? ITuple.this[int index]
{
get
{
if (index != 0)
{
throw new IndexOutOfRangeException();
}
return Item1;
}
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1; // Do not rename (binary serialization)
private readonly T2 m_Item2; // Do not rename (binary serialization)
public T1 Item1 => m_Item1;
public T2 Item2 => m_Item2;
public Tuple(T1 item1, T2 item2)
{
m_Item1 = item1;
m_Item2 = item2;
}
public override bool Equals(object? obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer)
{
if (other == null) return false;
if (!(other is Tuple<T1, T2> objTuple))
{
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2);
}
int IComparable.CompareTo(object? obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo(object? other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is Tuple<T1, T2> objTuple))
{
throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other));
}
int 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);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1!), comparer.GetHashCode(m_Item2!));
}
int ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('(');
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.ToString(StringBuilder sb)
{
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(')');
return sb.ToString();
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 2;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object? ITuple.this[int index] =>
index switch
{
0 => Item1,
1 => Item2,
_ => throw new IndexOutOfRangeException(),
};
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1; // Do not rename (binary serialization)
private readonly T2 m_Item2; // Do not rename (binary serialization)
private readonly T3 m_Item3; // Do not rename (binary serialization)
public T1 Item1 => m_Item1;
public T2 Item2 => m_Item2;
public T3 Item3 => m_Item3;
public Tuple(T1 item1, T2 item2, T3 item3)
{
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
}
public override bool Equals(object? obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer)
{
if (other == null) return false;
if (!(other is Tuple<T1, T2, T3> objTuple))
{
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3);
}
int IComparable.CompareTo(object? obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo(object? other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is Tuple<T1, T2, T3> objTuple))
{
throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other));
}
int 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);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1!), comparer.GetHashCode(m_Item2!), comparer.GetHashCode(m_Item3!));
}
int ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('(');
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.ToString(StringBuilder sb)
{
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(", ");
sb.Append(m_Item3);
sb.Append(')');
return sb.ToString();
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 3;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object? ITuple.this[int index] =>
index switch
{
0 => Item1,
1 => Item2,
2 => Item3,
_ => throw new IndexOutOfRangeException(),
};
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Tuple<T1, T2, T3, T4> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1; // Do not rename (binary serialization)
private readonly T2 m_Item2; // Do not rename (binary serialization)
private readonly T3 m_Item3; // Do not rename (binary serialization)
private readonly T4 m_Item4; // Do not rename (binary serialization)
public T1 Item1 => m_Item1;
public T2 Item2 => m_Item2;
public T3 Item3 => m_Item3;
public T4 Item4 => 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 bool Equals(object? obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer)
{
if (other == null) return false;
if (!(other is Tuple<T1, T2, T3, T4> objTuple))
{
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);
}
int IComparable.CompareTo(object? obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo(object? other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is Tuple<T1, T2, T3, T4> objTuple))
{
throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other));
}
int 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);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1!), comparer.GetHashCode(m_Item2!), comparer.GetHashCode(m_Item3!), comparer.GetHashCode(m_Item4!));
}
int ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('(');
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.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();
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 4;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object? ITuple.this[int index] =>
index switch
{
0 => Item1,
1 => Item2,
2 => Item3,
3 => Item4,
_ => throw new IndexOutOfRangeException(),
};
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Tuple<T1, T2, T3, T4, T5> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1; // Do not rename (binary serialization)
private readonly T2 m_Item2; // Do not rename (binary serialization)
private readonly T3 m_Item3; // Do not rename (binary serialization)
private readonly T4 m_Item4; // Do not rename (binary serialization)
private readonly T5 m_Item5; // Do not rename (binary serialization)
public T1 Item1 => m_Item1;
public T2 Item2 => m_Item2;
public T3 Item3 => m_Item3;
public T4 Item4 => m_Item4;
public T5 Item5 => 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 bool Equals(object? obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer)
{
if (other == null) return false;
if (!(other is Tuple<T1, T2, T3, T4, T5> objTuple))
{
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);
}
int IComparable.CompareTo(object? obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo(object? other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is Tuple<T1, T2, T3, T4, T5> objTuple))
{
throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other));
}
int 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);
}
int 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!));
}
int ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('(');
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.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();
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 5;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object? ITuple.this[int index] =>
index switch
{
0 => Item1,
1 => Item2,
2 => Item3,
3 => Item4,
4 => Item5,
_ => throw new IndexOutOfRangeException(),
};
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Tuple<T1, T2, T3, T4, T5, T6> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1; // Do not rename (binary serialization)
private readonly T2 m_Item2; // Do not rename (binary serialization)
private readonly T3 m_Item3; // Do not rename (binary serialization)
private readonly T4 m_Item4; // Do not rename (binary serialization)
private readonly T5 m_Item5; // Do not rename (binary serialization)
private readonly T6 m_Item6; // Do not rename (binary serialization)
public T1 Item1 => m_Item1;
public T2 Item2 => m_Item2;
public T3 Item3 => m_Item3;
public T4 Item4 => m_Item4;
public T5 Item5 => m_Item5;
public T6 Item6 => 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 bool Equals(object? obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer)
{
if (other == null) return false;
if (!(other is Tuple<T1, T2, T3, T4, T5, T6> objTuple))
{
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);
}
int IComparable.CompareTo(object? obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo(object? other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is Tuple<T1, T2, T3, T4, T5, T6> objTuple))
{
throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other));
}
int 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);
}
int 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!));
}
int ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('(');
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.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();
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 6;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object? ITuple.this[int index] =>
index switch
{
0 => Item1,
1 => Item2,
2 => Item3,
3 => Item4,
4 => Item5,
5 => Item6,
_ => throw new IndexOutOfRangeException(),
};
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Tuple<T1, T2, T3, T4, T5, T6, T7> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1; // Do not rename (binary serialization)
private readonly T2 m_Item2; // Do not rename (binary serialization)
private readonly T3 m_Item3; // Do not rename (binary serialization)
private readonly T4 m_Item4; // Do not rename (binary serialization)
private readonly T5 m_Item5; // Do not rename (binary serialization)
private readonly T6 m_Item6; // Do not rename (binary serialization)
private readonly T7 m_Item7; // Do not rename (binary serialization)
public T1 Item1 => m_Item1;
public T2 Item2 => m_Item2;
public T3 Item3 => m_Item3;
public T4 Item4 => m_Item4;
public T5 Item5 => m_Item5;
public T6 Item6 => m_Item6;
public T7 Item7 => 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 bool Equals(object? obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer)
{
if (other == null) return false;
if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple))
{
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);
}
int IComparable.CompareTo(object? obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo(object? other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple))
{
throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other));
}
int 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);
}
int 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!));
}
int ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('(');
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.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();
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 7;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object? ITuple.this[int index] =>
index switch
{
0 => Item1,
1 => Item2,
2 => Item3,
3 => Item4,
4 => Item5,
5 => Item6,
6 => Item7,
_ => throw new IndexOutOfRangeException(),
};
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple where TRest : notnull
{
private readonly T1 m_Item1; // Do not rename (binary serialization)
private readonly T2 m_Item2; // Do not rename (binary serialization)
private readonly T3 m_Item3; // Do not rename (binary serialization)
private readonly T4 m_Item4; // Do not rename (binary serialization)
private readonly T5 m_Item5; // Do not rename (binary serialization)
private readonly T6 m_Item6; // Do not rename (binary serialization)
private readonly T7 m_Item7; // Do not rename (binary serialization)
private readonly TRest m_Rest; // Do not rename (binary serialization)
public T1 Item1 => m_Item1;
public T2 Item2 => m_Item2;
public T3 Item3 => m_Item3;
public T4 Item4 => m_Item4;
public T5 Item5 => m_Item5;
public T6 Item6 => m_Item6;
public T7 Item7 => m_Item7;
public TRest Rest => m_Rest;
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest)
{
if (!(rest is ITupleInternal))
{
throw new ArgumentException(SR.ArgumentException_TupleLastArgumentNotATuple);
}
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 bool Equals(object? obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer)
{
if (other == null) return false;
if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple))
{
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);
}
int IComparable.CompareTo(object? obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo(object? other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple))
{
throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other));
}
int 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);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
// We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
ITupleInternal t = (ITupleInternal)m_Rest;
if (t.Length >= 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.Length;
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));
}
Debug.Fail("Missed all cases for computing Tuple hash code");
return -1;
}
int ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('(');
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.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 ((ITupleInternal)m_Rest).ToString(sb);
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 7 + ((ITupleInternal)Rest).Length;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object? ITuple.this[int index] =>
index switch
{
0 => Item1,
1 => Item2,
2 => Item3,
3 => Item4,
4 => Item5,
5 => Item6,
6 => Item7,
_ => ((ITupleInternal)Rest)[index - 7],
};
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.IO.Tests
{
public class DirectoryInfo_CreateSubDirectory : FileSystemTest
{
#region UniversalTests
[Fact]
public void NullAsPath_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(null));
}
[Fact]
public void EmptyAsPath_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(string.Empty));
}
[Fact]
public void PathAlreadyExistsAsFile()
{
string path = GetTestFileName();
File.Create(Path.Combine(TestDirectory, path)).Dispose();
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path));
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.AddTrailingSlashIfNeeded(path)));
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.RemoveTrailingSlash(path)));
}
[Theory]
[InlineData(FileAttributes.Hidden)]
[InlineData(FileAttributes.ReadOnly)]
[InlineData(FileAttributes.Normal)]
public void PathAlreadyExistsAsDirectory(FileAttributes attributes)
{
string path = GetTestFileName();
DirectoryInfo testDir = Directory.CreateDirectory(Path.Combine(TestDirectory, path));
FileAttributes original = testDir.Attributes;
try
{
testDir.Attributes = attributes;
Assert.Equal(testDir.FullName, new DirectoryInfo(TestDirectory).CreateSubdirectory(path).FullName);
}
finally
{
testDir.Attributes = original;
}
}
[Fact]
public void DotIsCurrentDirectory()
{
string path = GetTestFileName();
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, "."));
Assert.Equal(IOServices.RemoveTrailingSlash(Path.Combine(TestDirectory, path)), result.FullName);
result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, ".") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(Path.Combine(TestDirectory, path)), result.FullName);
}
[Fact]
public void Conflicting_Parent_Directory()
{
string path = Path.Combine(TestDirectory, GetTestFileName(), "c");
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path));
}
[Fact]
public void DotDotIsParentDirectory()
{
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), ".."));
Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName);
result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), "..") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName);
}
[Fact]
public void SubDirectoryIsParentDirectory_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(TestDirectory, "..")));
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory + "/path").CreateSubdirectory("../../path2"));
}
[Theory,
MemberData(nameof(ValidPathComponentNames))]
public void ValidPathWithTrailingSlash(string component)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string path = IOServices.AddTrailingSlashIfNeeded(component);
DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path);
Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
[Theory,
MemberData(nameof(ValidPathComponentNames))]
public void ValidPathWithoutTrailingSlash(string component)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string path = component;
DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path);
Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
[Fact]
public void ValidPathWithMultipleSubdirectories()
{
string dirName = Path.Combine(GetTestFileName(), "Test", "Test", "Test");
DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName);
Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName));
}
[Fact]
public void AllowedSymbols()
{
string dirName = Path.GetRandomFileName() + "!@#$%^&";
DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName);
Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName));
}
#endregion
#region PlatformSpecific
[Theory,
MemberData(nameof(ControlWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // Control whitespace in path throws ArgumentException
public void WindowsControlWhiteSpace(string component)
{
// CreateSubdirectory will throw when passed a path with control whitespace e.g. "\t"
string path = IOServices.RemoveTrailingSlash(GetTestFileName());
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(component));
}
[Theory,
MemberData(nameof(SimpleWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // Simple whitespace is trimmed in path
public void WindowsSimpleWhiteSpace(string component)
{
// CreateSubdirectory trims all simple whitespace, returning us the parent directory
// that called CreateSubdirectory
string path = IOServices.RemoveTrailingSlash(GetTestFileName());
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(component);
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(TestDirectory, IOServices.RemoveTrailingSlash(result.FullName));
}
[Theory,
MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Whitespace as path allowed
public void UnixWhiteSpaceAsPath_Allowed(string path)
{
new DirectoryInfo(TestDirectory).CreateSubdirectory(path);
Assert.True(Directory.Exists(Path.Combine(TestDirectory, path)));
}
[Theory,
MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Trailing whitespace in path treated as significant
public void UnixNonSignificantTrailingWhiteSpace(string component)
{
// Unix treats trailing/prename whitespace as significant and a part of the name.
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string path = IOServices.RemoveTrailingSlash(testDir.Name) + component;
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(path);
Assert.True(Directory.Exists(result.FullName));
Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
}
[ConditionalFact(nameof(UsingNewNormalization))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // Extended windows path
public void ExtendedPathSubdirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
Assert.True(testDir.Exists);
DirectoryInfo subDir = testDir.CreateSubdirectory("Foo");
Assert.True(subDir.Exists);
Assert.StartsWith(IOInputs.ExtendedPrefix, subDir.FullName);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // UNC shares
public void UNCPathWithOnlySlashes()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Throws<ArgumentException>(() => testDir.CreateSubdirectory("//"));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using Braintree;
using Braintree.Exceptions;
namespace Braintree.Tests
{
[TestFixture]
public class MerchantAccountTest
{
private BraintreeGateway gateway;
[SetUp]
public void Setup()
{
gateway = new BraintreeGateway
{
Environment = Environment.DEVELOPMENT,
MerchantId = "integration_merchant_id",
PublicKey = "integration_public_key",
PrivateKey = "integration_private_key"
};
}
[Test]
[Category("Integration")]
public void Create_DeprecatedWithoutId()
{
var request = deprecatedCreateRequest(null);
Result<MerchantAccount> result = gateway.MerchantAccount.Create(request);
Assert.IsTrue(result.IsSuccess());
MerchantAccount merchantAccount = result.Target;
Assert.AreEqual(MerchantAccountStatus.PENDING, merchantAccount.Status);
Assert.AreEqual("sandbox_master_merchant_account", merchantAccount.MasterMerchantAccount.Id);
Assert.IsTrue(merchantAccount.IsSubMerchant);
Assert.IsFalse(merchantAccount.MasterMerchantAccount.IsSubMerchant);
Assert.IsTrue(merchantAccount.Id != null);
}
[Test]
[Category("Integration")]
public void Create_DeprecatedWithId()
{
Random random = new Random();
int randomNumber = random.Next(0, 10000);
var subMerchantAccountId = "sub_merchant_account_id_" + randomNumber;
var request = deprecatedCreateRequest(subMerchantAccountId);
Result<MerchantAccount> result = gateway.MerchantAccount.Create(request);
Assert.IsTrue(result.IsSuccess());
MerchantAccount merchantAccount = result.Target;
Assert.AreEqual(MerchantAccountStatus.PENDING, merchantAccount.Status);
Assert.AreEqual("sandbox_master_merchant_account", merchantAccount.MasterMerchantAccount.Id);
Assert.IsTrue(merchantAccount.IsSubMerchant);
Assert.IsFalse(merchantAccount.MasterMerchantAccount.IsSubMerchant);
Assert.AreEqual(subMerchantAccountId, merchantAccount.Id);
}
[Test]
[Category("Integration")]
public void Create_HandlesUnsuccessfulResults()
{
Result<MerchantAccount> result = gateway.MerchantAccount.Create(new MerchantAccountRequest());
Assert.IsFalse(result.IsSuccess());
List<ValidationError> errors = result.Errors.ForObject("merchant-account").OnField("master-merchant-account-id");
Assert.AreEqual(1, errors.Count);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_ID_IS_REQUIRED, errors[0].Code);
}
[Test]
[Category("Integration")]
public void Create_WithoutId()
{
var request = createRequest(null);
Result<MerchantAccount> result = gateway.MerchantAccount.Create(request);
Assert.IsTrue(result.IsSuccess());
MerchantAccount merchantAccount = result.Target;
Assert.AreEqual(MerchantAccountStatus.PENDING, merchantAccount.Status);
Assert.AreEqual("sandbox_master_merchant_account", merchantAccount.MasterMerchantAccount.Id);
Assert.IsTrue(merchantAccount.IsSubMerchant);
Assert.IsFalse(merchantAccount.MasterMerchantAccount.IsSubMerchant);
Assert.IsTrue(merchantAccount.Id != null);
}
[Test]
[Category("Integration")]
public void Create_WithId()
{
Random random = new Random();
int randomNumber = random.Next(0, 10000);
var subMerchantAccountId = "sub_merchant_account_id_" + randomNumber;
var request = createRequest(subMerchantAccountId);
Result<MerchantAccount> result = gateway.MerchantAccount.Create(request);
Assert.IsTrue(result.IsSuccess());
MerchantAccount merchantAccount = result.Target;
Assert.AreEqual(MerchantAccountStatus.PENDING, merchantAccount.Status);
Assert.AreEqual("sandbox_master_merchant_account", merchantAccount.MasterMerchantAccount.Id);
Assert.IsTrue(merchantAccount.IsSubMerchant);
Assert.IsFalse(merchantAccount.MasterMerchantAccount.IsSubMerchant);
Assert.AreEqual(subMerchantAccountId, merchantAccount.Id);
}
[Test]
[Category("Integration")]
public void Create_AcceptsBankFundingDestination()
{
var request = createRequest(null);
request.Funding.Destination = FundingDestination.BANK;
Result<MerchantAccount> result = gateway.MerchantAccount.Create(request);
Assert.IsTrue(result.IsSuccess());
}
[Test]
[Category("Integration")]
public void Create_AcceptsMobilePhoneFundingDestination()
{
var request = createRequest(null);
request.Funding.Destination = FundingDestination.MOBILE_PHONE;
Result<MerchantAccount> result = gateway.MerchantAccount.Create(request);
Assert.IsTrue(result.IsSuccess());
}
[Test]
[Category("Integration")]
public void Create_AcceptsEmailFundingDestination()
{
var request = createRequest(null);
request.Funding.Destination = FundingDestination.EMAIL;
Result<MerchantAccount> result = gateway.MerchantAccount.Create(request);
Assert.IsTrue(result.IsSuccess());
}
[Test]
[Category("Integration")]
public void Update_UpdatesAllFields()
{
var request = deprecatedCreateRequest(null);
Result<MerchantAccount> result = gateway.MerchantAccount.Create(request);
Assert.IsTrue(result.IsSuccess());
var updateRequest = createRequest(null);
updateRequest.TosAccepted = null;
updateRequest.MasterMerchantAccountId = null;
Result<MerchantAccount> updateResult = gateway.MerchantAccount.Update(result.Target.Id, updateRequest);
Assert.IsTrue(updateResult.IsSuccess());
MerchantAccount merchantAccount = updateResult.Target;
Assert.AreEqual("Job", merchantAccount.IndividualDetails.FirstName);
Assert.AreEqual("Leoggs", merchantAccount.IndividualDetails.LastName);
Assert.AreEqual("job@leoggs.com", merchantAccount.IndividualDetails.Email);
Assert.AreEqual("5555551212", merchantAccount.IndividualDetails.Phone);
Assert.AreEqual("1235", merchantAccount.IndividualDetails.SsnLastFour);
Assert.AreEqual("193 Credibility St.", merchantAccount.IndividualDetails.Address.StreetAddress);
Assert.AreEqual("60611", merchantAccount.IndividualDetails.Address.PostalCode);
Assert.AreEqual("Avondale", merchantAccount.IndividualDetails.Address.Locality);
Assert.AreEqual("IN", merchantAccount.IndividualDetails.Address.Region);
Assert.AreEqual("1985-09-10", merchantAccount.IndividualDetails.DateOfBirth);
Assert.AreEqual("coaterie.com", merchantAccount.BusinessDetails.LegalName);
Assert.AreEqual("Coaterie", merchantAccount.BusinessDetails.DbaName);
Assert.AreEqual("123456780", merchantAccount.BusinessDetails.TaxId);
Assert.AreEqual("135 Credibility St.", merchantAccount.BusinessDetails.Address.StreetAddress);
Assert.AreEqual("60602", merchantAccount.BusinessDetails.Address.PostalCode);
Assert.AreEqual("Gary", merchantAccount.BusinessDetails.Address.Locality);
Assert.AreEqual("OH", merchantAccount.BusinessDetails.Address.Region);
Assert.AreEqual(FundingDestination.EMAIL, merchantAccount.FundingDetails.Destination);
Assert.AreEqual("joe+funding@bloggs.com", merchantAccount.FundingDetails.Email);
Assert.AreEqual("3125551212", merchantAccount.FundingDetails.MobilePhone);
Assert.AreEqual("122100024", merchantAccount.FundingDetails.RoutingNumber);
Assert.AreEqual("8798", merchantAccount.FundingDetails.AccountNumberLast4);
Assert.AreEqual("Job Leoggs OH", merchantAccount.FundingDetails.Descriptor);
}
[Test]
[Category("Integration")]
public void Create_HandlesRequiredValidationErrors()
{
var request = new MerchantAccountRequest
{
TosAccepted = true,
MasterMerchantAccountId = "sandbox_master_merchant_account"
};
Result<MerchantAccount> result = gateway.MerchantAccount.Create(request);
Assert.IsFalse(result.IsSuccess());
ValidationErrors errors = result.Errors.ForObject("merchant-account");
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_REQUIRED,
errors.ForObject("individual").OnField("first-name")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_REQUIRED,
errors.ForObject("individual").OnField("last-name")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_REQUIRED,
errors.ForObject("individual").OnField("date-of-birth")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_REQUIRED,
errors.ForObject("individual").OnField("email")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_REQUIRED,
errors.ForObject("individual").ForObject("address").OnField("street-address")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_LOCALITY_IS_REQUIRED,
errors.ForObject("individual").ForObject("address").OnField("locality")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_REQUIRED,
errors.ForObject("individual").ForObject("address").OnField("postal-code")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_REQUIRED,
errors.ForObject("individual").ForObject("address").OnField("region")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_REQUIRED,
errors.ForObject("funding").OnField("destination")[0].Code);
}
[Test]
[Category("Integration")]
public void Create_HandlesInvalidValidationErrors()
{
var request = new MerchantAccountRequest
{
Individual = new IndividualRequest
{
FirstName = "<>",
LastName = "<>",
Email = "bad",
Phone = "999",
Address = new AddressRequest
{
StreetAddress = "nope",
PostalCode = "1",
Region = "QQ",
},
DateOfBirth = "hah",
Ssn = "12345",
},
Business = new BusinessRequest
{
LegalName = "``{}",
DbaName = "{}``",
TaxId = "bad",
Address = new AddressRequest
{
StreetAddress = "nope",
PostalCode = "1",
Region = "QQ",
},
},
Funding = new FundingRequest
{
Destination = FundingDestination.UNRECOGNIZED,
Email = "BILLFOLD",
MobilePhone = "TRIFOLD",
RoutingNumber = "LEATHER",
AccountNumber = "BACK POCKET",
},
TosAccepted = true,
MasterMerchantAccountId = "sandbox_master_merchant_account"
};
Result<MerchantAccount> result = gateway.MerchantAccount.Create(request);
Assert.IsFalse(result.IsSuccess());
ValidationErrors errors = result.Errors.ForObject("merchant-account");
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_INVALID,
errors.ForObject("individual").OnField("first-name")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_INVALID,
errors.ForObject("individual").OnField("last-name")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_INVALID,
errors.ForObject("individual").OnField("date-of-birth")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_PHONE_IS_INVALID,
errors.ForObject("individual").OnField("phone")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_SSN_IS_INVALID,
errors.ForObject("individual").OnField("ssn")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_INVALID,
errors.ForObject("individual").OnField("email")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_INVALID,
errors.ForObject("individual").ForObject("address").OnField("street-address")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_INVALID,
errors.ForObject("individual").ForObject("address").OnField("postal-code")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_INVALID,
errors.ForObject("individual").ForObject("address").OnField("region")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_DBA_NAME_IS_INVALID,
errors.ForObject("business").OnField("dba-name")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_LEGAL_NAME_IS_INVALID,
errors.ForObject("business").OnField("legal-name")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_TAX_ID_IS_INVALID,
errors.ForObject("business").OnField("tax-id")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_ADDRESS_STREET_ADDRESS_IS_INVALID,
errors.ForObject("business").ForObject("address").OnField("street-address")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_ADDRESS_POSTAL_CODE_IS_INVALID,
errors.ForObject("business").ForObject("address").OnField("postal-code")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_ADDRESS_REGION_IS_INVALID,
errors.ForObject("business").ForObject("address").OnField("region")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_INVALID,
errors.ForObject("funding").OnField("destination")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_ACCOUNT_NUMBER_IS_INVALID,
errors.ForObject("funding").OnField("account-number")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_ROUTING_NUMBER_IS_INVALID,
errors.ForObject("funding").OnField("routing-number")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_EMAIL_IS_INVALID,
errors.ForObject("funding").OnField("email")[0].Code);
Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_MOBILE_PHONE_IS_INVALID,
errors.ForObject("funding").OnField("mobile-phone")[0].Code);
}
[Test]
[Category("Integration")]
public void Find()
{
MerchantAccount merchantAccount = gateway.MerchantAccount.Create(createRequest(null)).Target;
MerchantAccount foundMerchantAccount = gateway.MerchantAccount.Find(merchantAccount.Id);
Assert.AreEqual(merchantAccount.Id, foundMerchantAccount.Id);
}
[Test]
[Category("Integration")]
public void RetrievesCurrencyIsoCode()
{
MerchantAccount foundMerchantAccount = gateway.MerchantAccount.Find("sandbox_master_merchant_account");
Assert.AreEqual("USD", foundMerchantAccount.CurrencyIsoCode);
}
[Test]
[Category("Unit")]
[ExpectedException(typeof(NotFoundException))]
public void Find_FindsErrorsOutOnWhitespaceIds()
{
gateway.MerchantAccount.Find(" ");
}
private MerchantAccountRequest deprecatedCreateRequest(string id)
{
return new MerchantAccountRequest
{
ApplicantDetails = new ApplicantDetailsRequest
{
CompanyName = "coattree.com",
FirstName = "Joe",
LastName = "Bloggs",
Email = "joe@bloggs.com",
Phone = "555-555-5555",
Address = new AddressRequest
{
StreetAddress = "123 Credibility St.",
PostalCode = "60606",
Locality = "Chicago",
Region = "IL",
},
DateOfBirth = "10/9/1980",
Ssn = "123-00-1234",
TaxId = "123456789",
RoutingNumber = "122100024",
AccountNumber = "43759348798"
},
TosAccepted = true,
Id = id,
MasterMerchantAccountId = "sandbox_master_merchant_account"
};
}
private MerchantAccountRequest createRequest(string id)
{
return new MerchantAccountRequest
{
Individual = new IndividualRequest
{
FirstName = "Job",
LastName = "Leoggs",
Email = "job@leoggs.com",
Phone = "555-555-1212",
Address = new AddressRequest
{
StreetAddress = "193 Credibility St.",
PostalCode = "60611",
Locality = "Avondale",
Region = "IN",
},
DateOfBirth = "10/9/1985",
Ssn = "123-00-1235",
},
Business = new BusinessRequest
{
LegalName = "coaterie.com",
DbaName = "Coaterie",
TaxId = "123456780",
Address = new AddressRequest
{
StreetAddress = "135 Credibility St.",
PostalCode = "60602",
Locality = "Gary",
Region = "OH",
},
},
Funding = new FundingRequest
{
Destination = FundingDestination.EMAIL,
Email = "joe+funding@bloggs.com",
MobilePhone = "3125551212",
RoutingNumber = "122100024",
AccountNumber = "43759348798",
Descriptor = "Job Leoggs OH",
},
TosAccepted = true,
Id = id,
MasterMerchantAccountId = "sandbox_master_merchant_account"
};
}
}
}
| |
/*
* 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;
namespace Apache.Geode.Client.Tests
{
using Apache.Geode.Client;
public class DeltaTestImpl
: IGeodeSerializable, IGeodeDelta
{
private static sbyte INT_MASK = 0x1;
private static sbyte STR_MASK = 0X2;
private static sbyte DOUBLE_MASK = 0x4;
private static sbyte BYTE_ARR_MASK = 0x8;
private static sbyte TEST_OBJ_MASK = 0x10;
private static Int64 toDataCount = 0;
private static Int64 fromDataCount = 0;
private static object LOCK_THIS_CLASS = new object();
private int intVar = 0;
private string str;
private double doubleVar;
private byte[] byteArr;
private TestObject1 testobj;
private sbyte deltaBits = 0x0;
private bool hasDelta = false;
private Int64 toDeltaCounter;
private Int64 fromDeltaCounter;
public DeltaTestImpl()
{
intVar = 1;
str = "test";
doubleVar = 1.1;
byte [] arr2 = new byte[1];
byteArr = arr2;
testobj = null;
hasDelta = false;
deltaBits = 0;
toDeltaCounter = 0;
fromDeltaCounter = 0;
}
public DeltaTestImpl(DeltaTestImpl rhs)
{
this.intVar = rhs.intVar;
this.str = rhs.str;
this.doubleVar=rhs.doubleVar;
this.byteArr = rhs.byteArr;
this.testobj = rhs.testobj;
this.toDeltaCounter = rhs.GetToDeltaCounter();
this.fromDeltaCounter = rhs.GetFromDeltaCounter();
}
public DeltaTestImpl(Int32 intValue, string strValue)
{
this.intVar = intValue;
this.str = strValue;
}
public DeltaTestImpl(Int32 intValue, string strValue, double doubleVal, byte[] bytes, TestObject1 testObject)
{
this.intVar = intValue;
this.str = strValue;
this.doubleVar = doubleVal;
this.byteArr = bytes;
this.testobj = testObject;
}
public UInt32 ObjectSize
{
get
{
return 0;
}
}
public UInt32 ClassId
{
get
{
return 0x1E;
}
}
public static IGeodeSerializable CreateDeserializable()
{
return new DeltaTestImpl();
}
public Int64 GetToDeltaCounter()
{
return toDeltaCounter;
}
public Int64 GetFromDeltaCounter()
{
return fromDeltaCounter;
}
public static Int64 GetToDataCount()
{
return toDataCount;
}
public static Int64 GetFromDataCount()
{
return fromDataCount;
}
public static void ResetDataCount()
{
lock (LOCK_THIS_CLASS)
{
toDataCount = 0;
fromDataCount = 0;
}
}
public void SetIntVar(Int32 value)
{
intVar = value;
deltaBits |= INT_MASK;
hasDelta = true;
}
public Int32 GetIntVar()
{
return intVar;
}
public void SetStr(string str1)
{
str = str1;
}
public string GetStr()
{
return str;
}
public void SetDoubleVar(double value)
{
doubleVar = value;
deltaBits |= DOUBLE_MASK;
hasDelta = true;
}
public double GetSetDoubleVar()
{
return doubleVar;
}
public void SetByteArr(byte[] value)
{
byteArr = value;
deltaBits |= BYTE_ARR_MASK;
hasDelta = true;
}
public byte[] GetByteArr()
{
return (byte[])byteArr;
}
public TestObject1 GetTestObj()
{
return testobj;
}
public void SetTestObj(TestObject1 testObj)
{
this.testobj = testObj;
deltaBits |= TEST_OBJ_MASK;
hasDelta = true;
}
public void SetDelta(bool value)
{
hasDelta = value;
}
public bool HasDelta()
{
return hasDelta;
}
public IGeodeSerializable FromData(DataInput input)
{
intVar = input.ReadInt32();
str = (string)input.ReadObject();
doubleVar = input.ReadDouble();
byteArr = (byte[])input.ReadObject();
testobj = (TestObject1)input.ReadObject();
lock (LOCK_THIS_CLASS)
{
fromDataCount++;
}
return this;
}
public void ToData(DataOutput output)
{
output.WriteInt32(intVar);
output.WriteObject(str);
output.WriteDouble(doubleVar);
output.WriteObject(byteArr);
output.WriteObject(testobj);
lock (LOCK_THIS_CLASS)
{
toDataCount++;
}
}
public void ToDelta(DataOutput output)
{
lock (LOCK_THIS_CLASS)
{
toDeltaCounter++;
}
output.WriteSByte(deltaBits);
if (deltaBits != 0)
{
if ((deltaBits & INT_MASK) == INT_MASK)
{
output.WriteInt32(intVar);
}
if ((deltaBits & STR_MASK) == STR_MASK)
{
output.WriteObject(str);
}
if ((deltaBits & DOUBLE_MASK) == DOUBLE_MASK)
{
output.WriteDouble(doubleVar);
}
if ((deltaBits & BYTE_ARR_MASK) == BYTE_ARR_MASK)
{
output.WriteObject(byteArr);
}
if ((deltaBits & TEST_OBJ_MASK) == TEST_OBJ_MASK)
{
output.WriteObject(testobj);
}
}
}
public void FromDelta(DataInput input)
{
lock (LOCK_THIS_CLASS)
{
fromDeltaCounter++;
}
deltaBits = input.ReadSByte();
if ((deltaBits & INT_MASK) == INT_MASK)
{
intVar = input.ReadInt32();
}
if ((deltaBits & STR_MASK) == STR_MASK)
{
str = (string)input.ReadObject();
}
if ((deltaBits & DOUBLE_MASK) == DOUBLE_MASK)
{
doubleVar = input.ReadDouble();
}
if ((deltaBits & BYTE_ARR_MASK) == BYTE_ARR_MASK)
{
byteArr = (byte[])input.ReadObject();
}
if ((deltaBits & TEST_OBJ_MASK) == TEST_OBJ_MASK)
{
testobj = (TestObject1)input.ReadObject();
}
}
public override string ToString()
{
string portStr = string.Format("DeltaTestImpl [hasDelta={0} int={1} " +
"double={2} str={3}]", hasDelta, intVar, doubleVar, str);
return portStr;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
internal abstract class AbstractChangeSignatureService : ILanguageService
{
protected SyntaxAnnotation changeSignatureFormattingAnnotation = new SyntaxAnnotation("ChangeSignatureFormatting");
/// <summary>
/// Determines the symbol on which we are invoking ReorderParameters
/// </summary>
public abstract Task<ISymbol> GetInvocationSymbolAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken);
/// <summary>
/// Given a SyntaxNode for which we want to reorder parameters/arguments, find the
/// SyntaxNode of a kind where we know how to reorder parameters/arguments.
/// </summary>
public abstract SyntaxNode FindNodeToUpdate(Document document, SyntaxNode node);
public abstract Task<ImmutableArray<SymbolAndProjectId>> DetermineCascadedSymbolsFromDelegateInvoke(
SymbolAndProjectId<IMethodSymbol> symbolAndProjectId, Document document, CancellationToken cancellationToken);
public abstract SyntaxNode ChangeSignature(
Document document,
ISymbol declarationSymbol,
SyntaxNode potentiallyUpdatedNode,
SyntaxNode originalNode,
SignatureChange signaturePermutation,
CancellationToken cancellationToken);
protected abstract IEnumerable<IFormattingRule> GetFormattingRules(Document document);
public async Task<ImmutableArray<ChangeSignatureCodeAction>> GetChangeSignatureCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var context = await GetContextAsync(document, span.Start, restrictToDeclarations: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return context.CanChangeSignature
? ImmutableArray.Create(new ChangeSignatureCodeAction(this, context))
: ImmutableArray<ChangeSignatureCodeAction>.Empty;
}
internal ChangeSignatureResult ChangeSignature(Document document, int position, Action<string, NotificationSeverity> errorHandler, CancellationToken cancellationToken)
{
var context = GetContextAsync(document, position, restrictToDeclarations: false, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
if (context.CanChangeSignature)
{
return ChangeSignatureWithContext(context, cancellationToken);
}
else
{
switch (context.CannotChangeSignatureReason)
{
case CannotChangeSignatureReason.DefinedInMetadata:
errorHandler(FeaturesResources.The_member_is_defined_in_metadata, NotificationSeverity.Error);
break;
case CannotChangeSignatureReason.IncorrectKind:
errorHandler(FeaturesResources.You_can_only_change_the_signature_of_a_constructor_indexer_method_or_delegate, NotificationSeverity.Error);
break;
case CannotChangeSignatureReason.InsufficientParameters:
errorHandler(FeaturesResources.This_signature_does_not_contain_parameters_that_can_be_changed, NotificationSeverity.Error);
break;
}
return new ChangeSignatureResult(succeeded: false);
}
}
private async Task<ChangeSignatureAnalyzedContext> GetContextAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken)
{
var symbol = await GetInvocationSymbolAsync(document, position, restrictToDeclarations, cancellationToken).ConfigureAwait(false);
// Cross-lang symbols will show as metadata, so map it to source if possible.
symbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, cancellationToken).ConfigureAwait(false) ?? symbol;
if (symbol == null)
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.IncorrectKind);
}
if (symbol is IMethodSymbol)
{
var method = symbol as IMethodSymbol;
var containingType = method.ContainingType;
if (method.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
containingType != null &&
containingType.IsDelegateType() &&
containingType.DelegateInvokeMethod != null)
{
symbol = containingType.DelegateInvokeMethod;
}
}
if (symbol is IEventSymbol)
{
symbol = (symbol as IEventSymbol).Type;
}
if (symbol is INamedTypeSymbol)
{
var typeSymbol = symbol as INamedTypeSymbol;
if (typeSymbol.IsDelegateType() && typeSymbol.DelegateInvokeMethod != null)
{
symbol = typeSymbol.DelegateInvokeMethod;
}
}
if (symbol.Locations.Any(loc => loc.IsInMetadata))
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.DefinedInMetadata);
}
if (!symbol.MatchesKind(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType))
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.IncorrectKind);
}
var parameterConfiguration = ParameterConfiguration.Create(symbol.GetParameters().ToList(), symbol is IMethodSymbol && (symbol as IMethodSymbol).IsExtensionMethod);
if (!parameterConfiguration.IsChangeable())
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.InsufficientParameters);
}
return new ChangeSignatureAnalyzedContext(
document.Project, symbol, parameterConfiguration);
}
private ChangeSignatureResult ChangeSignatureWithContext(ChangeSignatureAnalyzedContext context, CancellationToken cancellationToken)
{
var options = GetChangeSignatureOptions(context, CancellationToken.None);
if (options.IsCancelled)
{
return new ChangeSignatureResult(succeeded: false);
}
return ChangeSignatureWithContext(context, options, cancellationToken);
}
internal ChangeSignatureResult ChangeSignatureWithContext(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken)
{
Solution updatedSolution;
var succeeded = TryCreateUpdatedSolution(context, options, cancellationToken, out updatedSolution);
return new ChangeSignatureResult(succeeded, updatedSolution, context.Symbol.ToDisplayString(), context.Symbol.GetGlyph(), options.PreviewChanges);
}
internal ChangeSignatureOptionsResult GetChangeSignatureOptions(
ChangeSignatureAnalyzedContext context, CancellationToken cancellationToken)
{
var notificationService = context.Solution.Workspace.Services.GetService<INotificationService>();
var changeSignatureOptionsService = context.Solution.Workspace.Services.GetService<IChangeSignatureOptionsService>();
var isExtensionMethod = context.Symbol is IMethodSymbol && (context.Symbol as IMethodSymbol).IsExtensionMethod;
return changeSignatureOptionsService.GetChangeSignatureOptions(context.Symbol, context.ParameterConfiguration, notificationService);
}
private static async Task<ImmutableArray<ReferencedSymbol>> FindChangeSignatureReferencesAsync(
SymbolAndProjectId symbolAndProjectId,
Solution solution,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.FindReference_ChangeSignature, cancellationToken))
{
var streamingProgress = new StreamingProgressCollector(
StreamingFindReferencesProgress.Instance);
IImmutableSet<Document> documents = null;
var engine = new FindReferencesSearchEngine(
solution,
documents,
ReferenceFinders.DefaultReferenceFinders.Add(DelegateInvokeMethodReferenceFinder.DelegateInvokeMethod),
streamingProgress,
cancellationToken);
await engine.FindReferencesAsync(symbolAndProjectId).ConfigureAwait(false);
return streamingProgress.GetReferencedSymbols();
}
}
private bool TryCreateUpdatedSolution(
ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken, out Solution updatedSolution)
{
updatedSolution = context.Solution;
var declaredSymbol = context.Symbol;
var nodesToUpdate = new Dictionary<DocumentId, List<SyntaxNode>>();
var definitionToUse = new Dictionary<SyntaxNode, ISymbol>();
bool hasLocationsInMetadata = false;
var symbols = FindChangeSignatureReferencesAsync(
SymbolAndProjectId.Create(declaredSymbol, context.Project.Id),
context.Solution, cancellationToken).WaitAndGetResult(cancellationToken);
foreach (var symbol in symbols)
{
if (symbol.Definition.Kind == SymbolKind.Method &&
((symbol.Definition as IMethodSymbol).MethodKind == MethodKind.PropertyGet || (symbol.Definition as IMethodSymbol).MethodKind == MethodKind.PropertySet))
{
continue;
}
if (symbol.Definition.Kind == SymbolKind.NamedType)
{
continue;
}
if (symbol.Definition.Locations.Any(loc => loc.IsInMetadata))
{
hasLocationsInMetadata = true;
continue;
}
var symbolWithSyntacticParameters = symbol.Definition;
var symbolWithSemanticParameters = symbol.Definition;
var includeDefinitionLocations = true;
if (symbol.Definition.Kind == SymbolKind.Field)
{
includeDefinitionLocations = false;
}
if (symbolWithSyntacticParameters.Kind == SymbolKind.Event)
{
var eventSymbol = symbolWithSyntacticParameters as IEventSymbol;
var type = eventSymbol.Type as INamedTypeSymbol;
if (type != null && type.DelegateInvokeMethod != null)
{
symbolWithSemanticParameters = type.DelegateInvokeMethod;
}
else
{
continue;
}
}
if (symbolWithSyntacticParameters.Kind == SymbolKind.Method)
{
var methodSymbol = symbolWithSyntacticParameters as IMethodSymbol;
if (methodSymbol.MethodKind == MethodKind.DelegateInvoke)
{
symbolWithSyntacticParameters = methodSymbol.ContainingType;
}
if (methodSymbol.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
methodSymbol.ContainingType != null &&
methodSymbol.ContainingType.IsDelegateType())
{
includeDefinitionLocations = false;
}
}
// Find and annotate all the relevant definitions
if (includeDefinitionLocations)
{
foreach (var def in symbolWithSyntacticParameters.Locations)
{
DocumentId documentId;
SyntaxNode nodeToUpdate;
if (!TryGetNodeWithEditableSignatureOrAttributes(def, updatedSolution, out nodeToUpdate, out documentId))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId))
{
nodesToUpdate.Add(documentId, new List<SyntaxNode>());
}
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId, nodeToUpdate, definitionToUse, symbolWithSemanticParameters);
}
}
// Find and annotate all the relevant references
foreach (var location in symbol.Locations)
{
if (location.Location.IsInMetadata)
{
hasLocationsInMetadata = true;
continue;
}
DocumentId documentId2;
SyntaxNode nodeToUpdate2;
if (!TryGetNodeWithEditableSignatureOrAttributes(location.Location, updatedSolution, out nodeToUpdate2, out documentId2))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId2))
{
nodesToUpdate.Add(documentId2, new List<SyntaxNode>());
}
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId2, nodeToUpdate2, definitionToUse, symbolWithSemanticParameters);
}
}
if (hasLocationsInMetadata)
{
var notificationService = context.Solution.Workspace.Services.GetService<INotificationService>();
if (!notificationService.ConfirmMessageBox(FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue, severity: NotificationSeverity.Warning))
{
return false;
}
}
// Construct all the relevant syntax trees from the base solution
var updatedRoots = new Dictionary<DocumentId, SyntaxNode>();
foreach (var docId in nodesToUpdate.Keys)
{
var doc = updatedSolution.GetDocument(docId);
var updater = doc.Project.LanguageServices.GetService<AbstractChangeSignatureService>();
var root = doc.GetSyntaxRootSynchronously(CancellationToken.None);
var nodes = nodesToUpdate[docId];
var newRoot = root.ReplaceNodes(nodes, (originalNode, potentiallyUpdatedNode) =>
{
return updater.ChangeSignature(doc, definitionToUse[originalNode], potentiallyUpdatedNode, originalNode, CreateCompensatingSignatureChange(definitionToUse[originalNode], options.UpdatedSignature), cancellationToken);
});
var annotatedNodes = newRoot.GetAnnotatedNodes<SyntaxNode>(syntaxAnnotation: changeSignatureFormattingAnnotation);
var formattedRoot = Formatter.FormatAsync(
newRoot,
changeSignatureFormattingAnnotation,
doc.Project.Solution.Workspace,
options: null,
rules: GetFormattingRules(doc),
cancellationToken: CancellationToken.None).WaitAndGetResult(CancellationToken.None);
updatedRoots[docId] = formattedRoot;
}
// Update the documents using the updated syntax trees
foreach (var docId in nodesToUpdate.Keys)
{
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(docId, updatedRoots[docId]);
}
return true;
}
private void AddUpdatableNodeToDictionaries(Dictionary<DocumentId, List<SyntaxNode>> nodesToUpdate, DocumentId documentId, SyntaxNode nodeToUpdate, Dictionary<SyntaxNode, ISymbol> definitionToUse, ISymbol symbolWithSemanticParameters)
{
nodesToUpdate[documentId].Add(nodeToUpdate);
ISymbol sym;
if (definitionToUse.TryGetValue(nodeToUpdate, out sym) && sym != symbolWithSemanticParameters)
{
Debug.Assert(false, "Change Signature: Attempted to modify node twice with different semantic parameters.");
}
definitionToUse[nodeToUpdate] = symbolWithSemanticParameters;
}
private bool TryGetNodeWithEditableSignatureOrAttributes(Location location, Solution solution, out SyntaxNode nodeToUpdate, out DocumentId documentId)
{
var tree = location.SourceTree;
documentId = solution.GetDocumentId(tree);
var document = solution.GetDocument(documentId);
var root = tree.GetRoot();
SyntaxNode node = root.FindNode(location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true);
var updater = document.Project.LanguageServices.GetService<AbstractChangeSignatureService>();
nodeToUpdate = updater.FindNodeToUpdate(document, node);
return nodeToUpdate != null;
}
protected static List<IUnifiedArgumentSyntax> PermuteArguments(
Document document,
ISymbol declarationSymbol,
List<IUnifiedArgumentSyntax> arguments,
SignatureChange updatedSignature,
bool isReducedExtensionMethod = false)
{
// 1. Determine which parameters are permutable
var declarationParameters = declarationSymbol.GetParameters().ToList();
var declarationParametersToPermute = GetParametersToPermute(arguments, declarationParameters, isReducedExtensionMethod);
var argumentsToPermute = arguments.Take(declarationParametersToPermute.Count).ToList();
// 2. Create an argument to parameter map, and a parameter to index map for the sort.
var argumentToParameterMap = new Dictionary<IUnifiedArgumentSyntax, IParameterSymbol>();
var parameterToIndexMap = new Dictionary<IParameterSymbol, int>();
for (int i = 0; i < declarationParametersToPermute.Count; i++)
{
var decl = declarationParametersToPermute[i];
var arg = argumentsToPermute[i];
argumentToParameterMap[arg] = decl;
var originalIndex = declarationParameters.IndexOf(decl);
var updatedIndex = updatedSignature.GetUpdatedIndex(originalIndex);
// If there's no value, then we may be handling a method with more parameters than the original symbol (like BeginInvoke).
parameterToIndexMap[decl] = updatedIndex.HasValue ? updatedIndex.Value : -1;
}
// 3. Sort the arguments that need to be reordered
argumentsToPermute.Sort((a1, a2) => { return parameterToIndexMap[argumentToParameterMap[a1]].CompareTo(parameterToIndexMap[argumentToParameterMap[a2]]); });
// 4. Add names to arguments where necessary.
var newArguments = new List<IUnifiedArgumentSyntax>();
int expectedIndex = 0 + (isReducedExtensionMethod ? 1 : 0);
bool seenNamedArgument = false;
foreach (var argument in argumentsToPermute)
{
var param = argumentToParameterMap[argument];
var actualIndex = updatedSignature.GetUpdatedIndex(declarationParameters.IndexOf(param));
if (!actualIndex.HasValue)
{
continue;
}
if ((seenNamedArgument || actualIndex != expectedIndex) && !argument.IsNamed)
{
newArguments.Add(argument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation));
seenNamedArgument = true;
}
else
{
newArguments.Add(argument);
}
seenNamedArgument |= argument.IsNamed;
expectedIndex++;
}
// 5. Add the remaining arguments. These will already have names or be params arguments, but may have been removed.
bool removedParams = updatedSignature.OriginalConfiguration.ParamsParameter != null && updatedSignature.UpdatedConfiguration.ParamsParameter == null;
for (int i = declarationParametersToPermute.Count; i < arguments.Count; i++)
{
if (!arguments[i].IsNamed && removedParams && i >= updatedSignature.UpdatedConfiguration.ToListOfParameters().Count)
{
break;
}
if (!arguments[i].IsNamed || updatedSignature.UpdatedConfiguration.ToListOfParameters().Any(p => p.Name == arguments[i].GetName()))
{
newArguments.Add(arguments[i]);
}
}
return newArguments;
}
private static SignatureChange CreateCompensatingSignatureChange(ISymbol declarationSymbol, SignatureChange updatedSignature)
{
if (declarationSymbol.GetParameters().Length > updatedSignature.OriginalConfiguration.ToListOfParameters().Count)
{
var origStuff = updatedSignature.OriginalConfiguration.ToListOfParameters();
var newStuff = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var realStuff = declarationSymbol.GetParameters();
var bonusParameters = realStuff.Skip(origStuff.Count);
origStuff.AddRange(bonusParameters);
newStuff.AddRange(bonusParameters);
var newOrigParams = ParameterConfiguration.Create(origStuff, updatedSignature.OriginalConfiguration.ThisParameter != null);
var newUpdatedParams = ParameterConfiguration.Create(newStuff, updatedSignature.OriginalConfiguration.ThisParameter != null);
updatedSignature = new SignatureChange(newOrigParams, newUpdatedParams);
}
return updatedSignature;
}
private static List<IParameterSymbol> GetParametersToPermute(
List<IUnifiedArgumentSyntax> arguments,
List<IParameterSymbol> originalParameters,
bool isReducedExtensionMethod)
{
int position = -1 + (isReducedExtensionMethod ? 1 : 0);
var parametersToPermute = new List<IParameterSymbol>();
foreach (var argument in arguments)
{
if (argument.IsNamed)
{
var name = argument.GetName();
// TODO: file bug for var match = originalParameters.FirstOrDefault(p => p.Name == <ISymbol here>);
var match = originalParameters.FirstOrDefault(p => p.Name == name);
if (match == null || originalParameters.IndexOf(match) <= position)
{
break;
}
else
{
position = originalParameters.IndexOf(match);
parametersToPermute.Add(match);
}
}
else
{
position++;
if (position >= originalParameters.Count)
{
break;
}
parametersToPermute.Add(originalParameters[position]);
}
}
return parametersToPermute;
}
}
}
| |
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
namespace Amazon.EC2.Model
{
/// <summary>
/// Details for an import instance volume item.
/// </summary>
[XmlRootAttribute(IsNullable = false)]
public class ImportInstanceVolumeDetailItemType
{
private Decimal? bytesConvertedField;
private string availabilityZoneField;
private DiskImageDescriptionType imageField;
private string descriptionField;
private DiskImageVolumeDescriptionType volumeField;
private string statusField;
private string statusMessageField;
/// <summary>
/// Number of bytes converted so far.
/// </summary>
[XmlElementAttribute(ElementName = "BytesConverted")]
public Decimal BytesConverted
{
get { return this.bytesConvertedField.GetValueOrDefault(); }
set { this.bytesConvertedField = value; }
}
/// <summary>
/// Sets the number of bytes converted so far.
/// </summary>
/// <param name="bytesConverted">Number of bytes converted so far.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ImportInstanceVolumeDetailItemType WithBytesConverted(Decimal bytesConverted)
{
this.bytesConvertedField = bytesConverted;
return this;
}
/// <summary>
/// Checks if BytesConverted property is set
/// </summary>
/// <returns>true if BytesConverted property is set</returns>
public bool IsSetBytesConverted()
{
return this.bytesConvertedField.HasValue;
}
/// <summary>
/// The Availability Zone where the resulting instance will reside.
/// </summary>
[XmlElementAttribute(ElementName = "AvailabilityZone")]
public string AvailabilityZone
{
get { return this.availabilityZoneField; }
set { this.availabilityZoneField = value; }
}
/// <summary>
/// Sets the Availability Zone where the resulting instance will reside.
/// </summary>
/// <param name="availabilityZone">The Availability Zone where the resulting instance will reside.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ImportInstanceVolumeDetailItemType WithAvailabilityZone(string availabilityZone)
{
this.availabilityZoneField = availabilityZone;
return this;
}
/// <summary>
/// Checks if AvailabilityZone property is set
/// </summary>
/// <returns>true if AvailabilityZone property is set</returns>
public bool IsSetAvailabilityZone()
{
return this.availabilityZoneField != null;
}
/// <summary>
/// Information about the image.
/// </summary>
[XmlElementAttribute(ElementName = "Image")]
public DiskImageDescriptionType Image
{
get { return this.imageField; }
set { this.imageField = value; }
}
/// <summary>
/// Sets the information about the image.
/// </summary>
/// <param name="image">Information about the image.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ImportInstanceVolumeDetailItemType WithImage(DiskImageDescriptionType image)
{
this.imageField = image;
return this;
}
/// <summary>
/// Checks if Image property is set
/// </summary>
/// <returns>true if Image property is set</returns>
public bool IsSetImage()
{
return this.imageField != null;
}
/// <summary>
/// Description provided when starting the import instance task.
/// </summary>
[XmlElementAttribute(ElementName = "Description")]
public string Description
{
get { return this.descriptionField; }
set { this.descriptionField = value; }
}
/// <summary>
/// Sets the description.
/// </summary>
/// <param name="description">Description you provided when starting the import instance task.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ImportInstanceVolumeDetailItemType WithDescription(string description)
{
this.descriptionField = description;
return this;
}
/// <summary>
/// Checks if Description property is set
/// </summary>
/// <returns>true if Description property is set</returns>
public bool IsSetDescription()
{
return this.descriptionField != null;
}
/// <summary>
/// Information about the volume.
/// </summary>
[XmlElementAttribute(ElementName = "Volume")]
public DiskImageVolumeDescriptionType Volume
{
get { return this.volumeField; }
set { this.volumeField = value; }
}
/// <summary>
/// Sets the information about the volume.
/// </summary>
/// <param name="volume">Information about the volume.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ImportInstanceVolumeDetailItemType WithVolume(DiskImageVolumeDescriptionType volume)
{
this.volumeField = volume;
return this;
}
/// <summary>
/// Checks if Volume property is set
/// </summary>
/// <returns>true if Volume property is set</returns>
public bool IsSetVolume()
{
return this.volumeField != null;
}
/// <summary>
/// Status of the import of this particular disk image.
/// </summary>
[XmlElementAttribute(ElementName = "Status")]
public string Status
{
get { return this.statusField; }
set { this.statusField = value; }
}
/// <summary>
/// Sets the status of the import of this particular disk image.
/// </summary>
/// <param name="status">Status of the import of this particular disk image.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ImportInstanceVolumeDetailItemType WithStatus(string status)
{
this.statusField = status;
return this;
}
/// <summary>
/// Checks if Status property is set
/// </summary>
/// <returns>true if Status property is set</returns>
public bool IsSetStatus()
{
return this.statusField != null;
}
/// <summary>
/// Status information or errors related to the disk image.
/// </summary>
[XmlElementAttribute(ElementName = "StatusMessage")]
public string StatusMessage
{
get { return this.statusMessageField; }
set { this.statusMessageField = value; }
}
/// <summary>
/// Sets the status information or errors related to the disk image.
/// </summary>
/// <param name="statusMessage">Status information or errors related to the disk image.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ImportInstanceVolumeDetailItemType WithStatusMessage(string statusMessage)
{
this.statusMessageField = statusMessage;
return this;
}
/// <summary>
/// Checks if StatusMessage property is set
/// </summary>
/// <returns>true if StatusMessage property is set</returns>
public bool IsSetStatusMessage()
{
return this.statusMessageField != null;
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.ResponseHandling;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using IdentityServer4.Validation;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Http;
using System;
using System.Net.Http;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Builder extension methods for registering additional services
/// </summary>
public static class IdentityServerBuilderExtensionsAdditional
{
/// <summary>
/// Adds the extension grant validator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddExtensionGrantValidator<T>(this IIdentityServerBuilder builder)
where T : class, IExtensionGrantValidator
{
builder.Services.AddTransient<IExtensionGrantValidator, T>();
return builder;
}
/// <summary>
/// Adds a redirect URI validator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddRedirectUriValidator<T>(this IIdentityServerBuilder builder)
where T : class, IRedirectUriValidator
{
builder.Services.AddTransient<IRedirectUriValidator, T>();
return builder;
}
/// <summary>
/// Adds a an "AppAuth" (OAuth 2.0 for Native Apps) compliant redirect URI validator (does strict validation but also allows http://127.0.0.1 with random port)
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddAppAuthRedirectUriValidator(this IIdentityServerBuilder builder)
{
return builder.AddRedirectUriValidator<StrictRedirectUriValidatorAppAuth>();
}
/// <summary>
/// Adds the resource owner validator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddResourceOwnerValidator<T>(this IIdentityServerBuilder builder)
where T : class, IResourceOwnerPasswordValidator
{
builder.Services.AddTransient<IResourceOwnerPasswordValidator, T>();
return builder;
}
/// <summary>
/// Adds the profile service.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddProfileService<T>(this IIdentityServerBuilder builder)
where T : class, IProfileService
{
builder.Services.AddTransient<IProfileService, T>();
return builder;
}
/// <summary>
/// Adds a client store.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddClientStore<T>(this IIdentityServerBuilder builder)
where T : class, IClientStore
{
builder.Services.TryAddTransient(typeof(T));
builder.Services.AddTransient<IClientStore, ValidatingClientStore<T>>();
return builder;
}
/// <summary>
/// Adds a resource store.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddResourceStore<T>(this IIdentityServerBuilder builder)
where T : class, IResourceStore
{
builder.Services.AddTransient<IResourceStore, T>();
return builder;
}
/// <summary>
/// Adds a device flow store.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
public static IIdentityServerBuilder AddDeviceFlowStore<T>(this IIdentityServerBuilder builder)
where T : class, IDeviceFlowStore
{
builder.Services.AddTransient<IDeviceFlowStore, T>();
return builder;
}
/// <summary>
/// Adds a persisted grant store.
/// </summary>
/// <typeparam name="T">The type of the concrete grant store that is registered in DI.</typeparam>
/// <param name="builder">The builder.</param>
/// <returns>The builder.</returns>
public static IIdentityServerBuilder AddPersistedGrantStore<T>(this IIdentityServerBuilder builder)
where T : class, IPersistedGrantStore
{
builder.Services.AddTransient<IPersistedGrantStore, T>();
return builder;
}
/// <summary>
/// Adds a CORS policy service.
/// </summary>
/// <typeparam name="T">The type of the concrete scope store class that is registered in DI.</typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddCorsPolicyService<T>(this IIdentityServerBuilder builder)
where T : class, ICorsPolicyService
{
builder.Services.AddTransient<ICorsPolicyService, T>();
return builder;
}
/// <summary>
/// Adds a CORS policy service cache.
/// </summary>
/// <typeparam name="T">The type of the concrete CORS policy service that is registered in DI.</typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddCorsPolicyCache<T>(this IIdentityServerBuilder builder)
where T : class, ICorsPolicyService
{
builder.Services.TryAddTransient(typeof(T));
builder.Services.AddTransient<ICorsPolicyService, CachingCorsPolicyService<T>>();
return builder;
}
/// <summary>
/// Adds the secret parser.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddSecretParser<T>(this IIdentityServerBuilder builder)
where T : class, ISecretParser
{
builder.Services.AddTransient<ISecretParser, T>();
return builder;
}
/// <summary>
/// Adds the secret validator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddSecretValidator<T>(this IIdentityServerBuilder builder)
where T : class, ISecretValidator
{
builder.Services.AddTransient<ISecretValidator, T>();
return builder;
}
/// <summary>
/// Adds the client store cache.
/// </summary>
/// <typeparam name="T">The type of the concrete client store class that is registered in DI.</typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddClientStoreCache<T>(this IIdentityServerBuilder builder)
where T : IClientStore
{
builder.Services.TryAddTransient(typeof(T));
builder.Services.AddTransient<ValidatingClientStore<T>>();
builder.Services.AddTransient<IClientStore, CachingClientStore<ValidatingClientStore<T>>>();
return builder;
}
/// <summary>
/// Adds the client store cache.
/// </summary>
/// <typeparam name="T">The type of the concrete scope store class that is registered in DI.</typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddResourceStoreCache<T>(this IIdentityServerBuilder builder)
where T : IResourceStore
{
builder.Services.TryAddTransient(typeof(T));
builder.Services.AddTransient<IResourceStore, CachingResourceStore<T>>();
return builder;
}
/// <summary>
/// Adds the authorize interaction response generator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddAuthorizeInteractionResponseGenerator<T>(this IIdentityServerBuilder builder)
where T : class, IAuthorizeInteractionResponseGenerator
{
builder.Services.AddTransient<IAuthorizeInteractionResponseGenerator, T>();
return builder;
}
/// <summary>
/// Adds the custom authorize request validator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddCustomAuthorizeRequestValidator<T>(this IIdentityServerBuilder builder)
where T : class, ICustomAuthorizeRequestValidator
{
builder.Services.AddTransient<ICustomAuthorizeRequestValidator, T>();
return builder;
}
/// <summary>
/// Adds the custom authorize request validator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddCustomTokenRequestValidator<T>(this IIdentityServerBuilder builder)
where T : class, ICustomTokenRequestValidator
{
builder.Services.AddTransient<ICustomTokenRequestValidator, T>();
return builder;
}
/// <summary>
/// Adds support for client authentication using JWT bearer assertions.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddJwtBearerClientAuthentication(this IIdentityServerBuilder builder)
{
builder.AddSecretParser<JwtBearerClientAssertionSecretParser>();
builder.AddSecretValidator<PrivateKeyJwtSecretValidator>();
return builder;
}
/// <summary>
/// Adds a client configuration validator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddClientConfigurationValidator<T>(this IIdentityServerBuilder builder)
where T : class, IClientConfigurationValidator
{
builder.Services.AddTransient<IClientConfigurationValidator, T>();
return builder;
}
/// <summary>
/// Adds the X509 secret validators for mutual TLS.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddMutualTlsSecretValidators(this IIdentityServerBuilder builder)
{
builder.AddSecretParser<MutualTlsSecretParser>();
builder.AddSecretValidator<X509ThumbprintSecretValidator>();
builder.AddSecretValidator<X509NameSecretValidator>();
return builder;
}
/// <summary>
/// Adds a custom back-channel logout service.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddBackChannelLogoutService<T>(this IIdentityServerBuilder builder)
where T : class, IBackChannelLogoutService
{
builder.Services.AddTransient<IBackChannelLogoutService, T>();
return builder;
}
// todo: check with later previews of ASP.NET Core if this is still required
/// <summary>
/// Adds configuration for the HttpClient used for back-channel logout notifications.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="configureClient">The configruation callback.</param>
/// <returns></returns>
public static IHttpClientBuilder AddBackChannelLogoutHttpClient(this IIdentityServerBuilder builder, Action<HttpClient> configureClient = null)
{
var name = typeof(BackChannelLogoutHttpClient).Name;
IHttpClientBuilder httpBuilder;
if (configureClient != null)
{
httpBuilder = builder.Services.AddHttpClient(name, configureClient);
}
else
{
httpBuilder = builder.Services.AddHttpClient(name);
}
httpBuilder.Services.AddTransient<BackChannelLogoutHttpClient>(s =>
{
var httpClientFactory = s.GetRequiredService<IHttpClientFactory>();
var httpClient = httpClientFactory.CreateClient(name);
var typedClientFactory = s.GetRequiredService<ITypedHttpClientFactory<BackChannelLogoutHttpClient>>();
return typedClientFactory.CreateClient(httpClient);
});
return httpBuilder;
}
// todo: check with later previews of ASP.NET Core if this is still required
/// <summary>
/// Adds configuration for the HttpClient used for JWT request_uri requests.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="configureClient">The configruation callback.</param>
/// <returns></returns>
public static IHttpClientBuilder AddJwtRequestUriHttpClient(this IIdentityServerBuilder builder, Action<HttpClient> configureClient = null)
{
var name = typeof(JwtRequestUriHttpClient).Name;
IHttpClientBuilder httpBuilder;
if (configureClient != null)
{
httpBuilder = builder.Services.AddHttpClient(name, configureClient);
}
else
{
httpBuilder = builder.Services.AddHttpClient(name);
}
httpBuilder.Services.AddTransient<JwtRequestUriHttpClient>(s =>
{
var httpClientFactory = s.GetRequiredService<IHttpClientFactory>();
var httpClient = httpClientFactory.CreateClient(name);
var typedClientFactory = s.GetRequiredService<ITypedHttpClientFactory<JwtRequestUriHttpClient>>();
return typedClientFactory.CreateClient(httpClient);
});
return httpBuilder;
}
/// <summary>
/// Adds a custom authorization request parameter store.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddAuthorizationParametersMessageStore<T>(this IIdentityServerBuilder builder)
where T : class, IAuthorizationParametersMessageStore
{
builder.Services.AddTransient<IAuthorizationParametersMessageStore, T>();
return builder;
}
}
}
| |
namespace Petstore
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// UsageOperations operations.
/// </summary>
internal partial class UsageOperations : IServiceOperations<StorageManagementClient>, IUsageOperations
{
/// <summary>
/// Initializes a new instance of the UsageOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal UsageOperations(StorageManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the StorageManagementClient
/// </summary>
public StorageManagementClient Client { get; private set; }
/// <summary>
/// Gets the current usage count and the limit for the resources under the
/// subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<Usage>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Storage/usages").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<Usage>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<Usage>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute.Models
{
/// <summary>
/// The List Disks operation response.
/// </summary>
public partial class VirtualMachineDiskListResponse : OperationResponse, IEnumerable<VirtualMachineDiskListResponse.VirtualMachineDisk>
{
private IList<VirtualMachineDiskListResponse.VirtualMachineDisk> _disks;
/// <summary>
/// Optional. The virtual machine disks associated with your
/// subscription.
/// </summary>
public IList<VirtualMachineDiskListResponse.VirtualMachineDisk> Disks
{
get { return this._disks; }
set { this._disks = value; }
}
/// <summary>
/// Initializes a new instance of the VirtualMachineDiskListResponse
/// class.
/// </summary>
public VirtualMachineDiskListResponse()
{
this.Disks = new LazyList<VirtualMachineDiskListResponse.VirtualMachineDisk>();
}
/// <summary>
/// Gets the sequence of Disks.
/// </summary>
public IEnumerator<VirtualMachineDiskListResponse.VirtualMachineDisk> GetEnumerator()
{
return this.Disks.GetEnumerator();
}
/// <summary>
/// Gets the sequence of Disks.
/// </summary>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// A virtual machine disk associated with your subscription.
/// </summary>
public partial class VirtualMachineDisk
{
private string _affinityGroup;
/// <summary>
/// Optional. The affinity group in which the disk is located. The
/// AffinityGroup value is derived from storage account that
/// contains the blob in which the media is located. If the
/// storage account does not belong to an affinity group the value
/// is NULL.
/// </summary>
public string AffinityGroup
{
get { return this._affinityGroup; }
set { this._affinityGroup = value; }
}
private string _iOType;
/// <summary>
/// Optional. Gets or sets the IO type.
/// </summary>
public string IOType
{
get { return this._iOType; }
set { this._iOType = value; }
}
private bool? _isCorrupted;
/// <summary>
/// Optional. Specifies thether the disk is known to be corrupt.
/// </summary>
public bool? IsCorrupted
{
get { return this._isCorrupted; }
set { this._isCorrupted = value; }
}
private bool? _isPremium;
/// <summary>
/// Optional. Specifies whether or not the disk contains a premium
/// virtual machine image.
/// </summary>
public bool? IsPremium
{
get { return this._isPremium; }
set { this._isPremium = value; }
}
private string _label;
/// <summary>
/// Optional. The friendly name of the disk.
/// </summary>
public string Label
{
get { return this._label; }
set { this._label = value; }
}
private string _location;
/// <summary>
/// Optional. The geo-location in which the disk is located. The
/// Location value is derived from storage account that contains
/// the blob in which the disk is located. If the storage account
/// belongs to an affinity group the value is NULL.
/// </summary>
public string Location
{
get { return this._location; }
set { this._location = value; }
}
private int _logicalSizeInGB;
/// <summary>
/// Optional. The size, in GB, of the disk.
/// </summary>
public int LogicalSizeInGB
{
get { return this._logicalSizeInGB; }
set { this._logicalSizeInGB = value; }
}
private Uri _mediaLinkUri;
/// <summary>
/// Optional. The location of the blob in the blob store in which
/// the media for the disk is located. The blob location belongs
/// to a storage account in the subscription specified by the
/// SubscriptionId value in the operation call. Example:
/// http://example.blob.core.windows.net/disks/mydisk.vhd.
/// </summary>
public Uri MediaLinkUri
{
get { return this._mediaLinkUri; }
set { this._mediaLinkUri = value; }
}
private string _name;
/// <summary>
/// Optional. The name of the disk. This is the name that is used
/// when creating one or more virtual machines using the disk.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private string _operatingSystemType;
/// <summary>
/// Optional. The operating system type of the OS image. Possible
/// Values are: Linux, Windows, or NULL.
/// </summary>
public string OperatingSystemType
{
get { return this._operatingSystemType; }
set { this._operatingSystemType = value; }
}
private string _sourceImageName;
/// <summary>
/// Optional. The name of the OS Image from which the disk was
/// created. This property is populated automatically when a disk
/// is created from an OS image by calling the Add Role, Create
/// Deployment, or Provision Disk operations.
/// </summary>
public string SourceImageName
{
get { return this._sourceImageName; }
set { this._sourceImageName = value; }
}
private VirtualMachineDiskListResponse.VirtualMachineDiskUsageDetails _usageDetails;
/// <summary>
/// Optional. Contains properties that specify a virtual machine
/// that currently using the disk. A disk cannot be deleted as
/// long as it is attached to a virtual machine.
/// </summary>
public VirtualMachineDiskListResponse.VirtualMachineDiskUsageDetails UsageDetails
{
get { return this._usageDetails; }
set { this._usageDetails = value; }
}
/// <summary>
/// Initializes a new instance of the VirtualMachineDisk class.
/// </summary>
public VirtualMachineDisk()
{
}
}
/// <summary>
/// Contains properties that specify a virtual machine that currently
/// using the disk. A disk cannot be deleted as long as it is attached
/// to a virtual machine.
/// </summary>
public partial class VirtualMachineDiskUsageDetails
{
private string _deploymentName;
/// <summary>
/// Optional. The deployment in which the disk is being used.
/// </summary>
public string DeploymentName
{
get { return this._deploymentName; }
set { this._deploymentName = value; }
}
private string _hostedServiceName;
/// <summary>
/// Optional. The hosted service in which the disk is being used.
/// </summary>
public string HostedServiceName
{
get { return this._hostedServiceName; }
set { this._hostedServiceName = value; }
}
private string _roleName;
/// <summary>
/// Optional. The virtual machine that the disk is attached to.
/// </summary>
public string RoleName
{
get { return this._roleName; }
set { this._roleName = value; }
}
/// <summary>
/// Initializes a new instance of the
/// VirtualMachineDiskUsageDetails class.
/// </summary>
public VirtualMachineDiskUsageDetails()
{
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
using Microsoft.Xunit.Performance;
[assembly: OptimizeForBenchmarks]
namespace Span
{
public class SpanBench
{
#if DEBUG
const int BubbleSortIterations = 1;
const int QuickSortIterations = 1;
const int FillAllIterations = 1;
const int BaseIterations = 1;
#else
// Appropriately-scaled iteration counts for the various benchmarks
const int BubbleSortIterations = 100;
const int QuickSortIterations = 1000;
const int FillAllIterations = 100000;
const int BaseIterations = 10000000;
#endif
// Default length for arrays of mock input data
const int DefaultLength = 1024;
// Helpers
#region Helpers
[StructLayout(LayoutKind.Sequential)]
private sealed class TestClass<T>
{
private double _d;
public T[] C0;
}
// Copying the result of a computation to Sink<T>.Instance is a way
// to prevent the jit from considering the computation dead and removing it.
private sealed class Sink<T>
{
public T Data;
public static Sink<T> Instance = new Sink<T>();
}
// Use statics to smuggle some information from Main to Invoke when running tests
// from the command line.
static bool IsXunitInvocation = true; // xunit-perf leaves this true; command line Main sets to false
static int CommandLineInnerIterationCount = 0; // used to communicate iteration count from BenchmarkAttribute
// (xunit-perf exposes the same in static property Benchmark.InnerIterationCount)
static bool DoWarmUp; // Main sets this when calling a new benchmark routine
// Invoke routine to abstract away the difference between running under xunit-perf vs running from the
// command line. Inner loop to be measured is taken as an Action<int>, and invoked passing the number
// of iterations that the inner loop should execute.
static void Invoke(Action<int> innerLoop, string nameFormat, params object[] nameArgs)
{
if (IsXunitInvocation)
{
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
innerLoop((int)Benchmark.InnerIterationCount);
}
else
{
if (DoWarmUp)
{
// Run some warm-up iterations before measuring
innerLoop(CommandLineInnerIterationCount);
// Clear the flag since we're now warmed up (caller will
// reset it before calling new code)
DoWarmUp = false;
}
// Now do the timed run of the inner loop.
Stopwatch sw = Stopwatch.StartNew();
innerLoop(CommandLineInnerIterationCount);
sw.Stop();
// Print result.
string name = String.Format(nameFormat, nameArgs);
double timeInMs = sw.Elapsed.TotalMilliseconds;
Console.WriteLine("{0}: {1}ms", name, timeInMs);
}
}
// Helper for the sort tests to get some pseudo-random input
static int[] GetUnsortedData(int length)
{
int[] unsortedData = new int[length];
Random r = new Random(42);
for (int i = 0; i < unsortedData.Length; ++i)
{
unsortedData[i] = r.Next();
}
return unsortedData;
}
#endregion // helpers
// Tests that implement some vary basic algorithms (fill/sort) over spans and arrays
#region Algorithm tests
#region TestFillAllSpan
[Benchmark(InnerIterationCount = FillAllIterations)]
[InlineData(DefaultLength)]
public static void FillAllSpan(int length)
{
byte[] a = new byte[length];
Invoke((int innerIterationCount) =>
{
Span<byte> s = new Span<byte>(a);
for (int i = 0; i < innerIterationCount; ++i)
{
TestFillAllSpan(s);
}
},
"TestFillAllSpan({0})", length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestFillAllSpan(Span<byte> span)
{
for (int i = 0; i < span.Length; ++i)
{
span[i] = unchecked((byte)i);
}
}
#endregion
#region TestFillAllArray
[Benchmark(InnerIterationCount = FillAllIterations)]
[InlineData(DefaultLength)]
public static void FillAllArray(int length)
{
byte[] a = new byte[length];
Invoke((int innerIterationCount) =>
{
for (int i = 0; i < innerIterationCount; ++i)
{
TestFillAllArray(a);
}
},
"TestFillArray({0})", length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestFillAllArray(byte[] data)
{
for (int i = 0; i < data.Length; ++i)
{
data[i] = unchecked((byte)i);
}
}
#endregion
#region TestFillAllReverseSpan
[Benchmark(InnerIterationCount = FillAllIterations)]
[InlineData(DefaultLength)]
public static void FillAllReverseSpan(int length)
{
byte[] a = new byte[length];
Invoke((int innerIterationCount) =>
{
Span<byte> s = new Span<byte>(a);
for (int i = 0; i < innerIterationCount; ++i)
{
TestFillAllReverseSpan(s);
}
},
"TestFillAllReverseSpan({0})", length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestFillAllReverseSpan(Span<byte> span)
{
for (int i = span.Length; --i >= 0;)
{
span[i] = unchecked((byte)i);
}
}
#endregion
#region TestFillAllReverseArray
[Benchmark(InnerIterationCount = FillAllIterations)]
[InlineData(DefaultLength)]
public static void FillAllReverseArray(int length)
{
byte[] a = new byte[length];
Invoke((int innerIterationCount) =>
{
for (int i = 0; i < innerIterationCount; ++i)
{
TestFillAllReverseArray(a);
}
},
"TestFillAllReverseArray({0})", length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestFillAllReverseArray(byte[] data)
{
for (int i = data.Length; --i >= 0;)
{
data[i] = unchecked((byte)i);
}
}
#endregion
#region TestQuickSortSpan
[Benchmark(InnerIterationCount = QuickSortIterations)]
[InlineData(DefaultLength)]
public static void QuickSortSpan(int length)
{
int[] data = new int[length];
int[] unsortedData = GetUnsortedData(length);
Invoke((int innerIterationCount) =>
{
Span<int> span = new Span<int>(data);
for (int i = 0; i < innerIterationCount; ++i)
{
Array.Copy(unsortedData, data, length);
TestQuickSortSpan(span);
}
},
"TestQuickSortSpan({0})", length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestQuickSortSpan(Span<int> data)
{
if (data.Length <= 1)
{
return;
}
int lo = 0;
int hi = data.Length - 1;
int i, j;
int pivot, temp;
for (i = lo, j = hi, pivot = data[hi]; i < j;)
{
while (i < j && data[i] <= pivot)
{
++i;
}
while (j > i && data[j] >= pivot)
{
--j;
}
if (i < j)
{
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
if (i != hi)
{
temp = data[i];
data[i] = pivot;
data[hi] = temp;
}
TestQuickSortSpan(data.Slice(0, i));
TestQuickSortSpan(data.Slice(i + 1));
}
#endregion
#region TestBubbleSortSpan
[Benchmark(InnerIterationCount = BubbleSortIterations)]
[InlineData(DefaultLength)]
public static void BubbleSortSpan(int length)
{
int[] data = new int[length];
int[] unsortedData = GetUnsortedData(length);
Invoke((int innerIterationCount) =>
{
Span<int> span = new Span<int>(data);
for (int i = 0; i < innerIterationCount; i++)
{
Array.Copy(unsortedData, data, length);
TestBubbleSortSpan(span);
}
},
"TestBubbleSortSpan({0})", length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestBubbleSortSpan(Span<int> span)
{
bool swap;
int temp;
int n = span.Length - 1;
do
{
swap = false;
for (int i = 0; i < n; i++)
{
if (span[i] > span[i + 1])
{
temp = span[i];
span[i] = span[i + 1];
span[i + 1] = temp;
swap = true;
}
}
--n;
}
while (swap);
}
#endregion
#region TestQuickSortArray
[Benchmark(InnerIterationCount = QuickSortIterations)]
[InlineData(DefaultLength)]
public static void QuickSortArray(int length)
{
int[] data = new int[length];
int[] unsortedData = GetUnsortedData(length);
Invoke((int innerIterationCount) =>
{
for (int i = 0; i < innerIterationCount; i++)
{
Array.Copy(unsortedData, data, length);
TestQuickSortArray(data, 0, data.Length - 1);
}
},
"TestQuickSortArray({0})", length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestQuickSortArray(int[] data, int lo, int hi)
{
if (lo >= hi)
{
return;
}
int i, j;
int pivot, temp;
for (i = lo, j = hi, pivot = data[hi]; i < j;)
{
while (i < j && data[i] <= pivot)
{
++i;
}
while (j > i && data[j] >= pivot)
{
--j;
}
if (i < j)
{
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
if (i != hi)
{
temp = data[i];
data[i] = pivot;
data[hi] = temp;
}
TestQuickSortArray(data, lo, i - 1);
TestQuickSortArray(data, i + 1, hi);
}
#endregion
#region TestBubbleSortArray
[Benchmark(InnerIterationCount = BubbleSortIterations)]
[InlineData(DefaultLength)]
public static void BubbleSortArray(int length)
{
int[] data = new int[length];
int[] unsortedData = GetUnsortedData(length);
Invoke((int innerIterationCount) =>
{
for (int i = 0; i < innerIterationCount; i++)
{
Array.Copy(unsortedData, data, length);
TestBubbleSortArray(data);
}
},
"TestBubbleSortArray({0})", length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestBubbleSortArray(int[] data)
{
bool swap;
int temp;
int n = data.Length - 1;
do
{
swap = false;
for (int i = 0; i < n; i++)
{
if (data[i] > data[i + 1])
{
temp = data[i];
data[i] = data[i + 1];
data[i + 1] = temp;
swap = true;
}
}
--n;
}
while (swap);
}
#endregion
#endregion // Algorithm tests
// TestSpanAPIs (For comparison with Array and Slow Span)
#region TestSpanAPIs
#region TestSpanConstructor<T>
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestSpanConstructorByte(int length)
{
InvokeTestSpanConstructor<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations / 100)]
[InlineData(100)]
public static void TestSpanConstructorString(int length)
{
InvokeTestSpanConstructor<string>(length);
}
static void InvokeTestSpanConstructor<T>(int length)
{
var array = new T[length];
Invoke((int innerIterationCount) => TestSpanConstructor<T>(array, innerIterationCount, false),
"TestSpanConstructor<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestSpanConstructor<T>(T[] array, int iterationCount, bool untrue)
{
var sink = Sink<T>.Instance;
for (int i = 0; i < iterationCount; i++)
{
var span = new Span<T>(array);
// Under a condition that we know is false but the jit doesn't,
// add a read from 'span' to make sure it's not dead, and an assignment
// to 'array' so the constructor call won't get hoisted.
if (untrue) { sink.Data = span[0]; array = new T[iterationCount]; }
}
}
#endregion
#if false // netcoreapp specific API https://github.com/dotnet/coreclr/issues/16126
#region TestSpanCreate<T>
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestSpanCreateByte(int length)
{
InvokeTestSpanCreate<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestSpanCreateString(int length)
{
InvokeTestSpanCreate<string>(length);
}
static void InvokeTestSpanCreate<T>(int length)
{
TestClass<T> testClass = new TestClass<T>();
testClass.C0 = new T[length];
Invoke((int innerIterationCount) => TestSpanCreate<T>(testClass, innerIterationCount, false),
"TestSpanCreate<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestSpanCreate<T>(TestClass<T> testClass, int iterationCount, bool untrue)
{
var sink = Sink<T>.Instance;
for (int i = 0; i < iterationCount; i++)
{
var span = MemoryMarshal.CreateSpan<T>(ref testClass.C0[0], testClass.C0.Length);
// Under a condition that we know is false but the jit doesn't,
// add a read from 'span' to make sure it's not dead, and an assignment
// to 'testClass' so the Create call won't get hoisted.
if (untrue) { sink.Data = span[0]; testClass = new TestClass<T>(); }
}
}
#endregion
#endif
#region TestMemoryMarshalGetReference<T>
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestMemoryMarshalGetReferenceByte(int length)
{
InvokeTestMemoryMarshalGetReference<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestMemoryMarshalGetReferenceString(int length)
{
InvokeTestMemoryMarshalGetReference<string>(length);
}
static void InvokeTestMemoryMarshalGetReference<T>(int length)
{
var array = new T[length];
Invoke((int innerIterationCount) => TestMemoryMarshalGetReference<T>(array, innerIterationCount),
"TestMemoryMarshalGetReference<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestMemoryMarshalGetReference<T>(T[] array, int iterationCount)
{
var sink = Sink<T>.Instance;
var span = new Span<T>(array);
for (int i = 0; i < iterationCount; i++)
{
ref T temp = ref MemoryMarshal.GetReference(span);
sink.Data = temp;
}
}
#endregion
#region TestSpanIndexHoistable<T>
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestSpanIndexHoistableByte(int length)
{
InvokeTestSpanIndexHoistable<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestSpanIndexHoistableString(int length)
{
InvokeTestSpanIndexHoistable<string>(length);
}
static void InvokeTestSpanIndexHoistable<T>(int length)
{
var array = new T[length];
Invoke((int innerIterationCount) => TestSpanIndexHoistable<T>(array, length, innerIterationCount),
"TestSpanIndexHoistable<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestSpanIndexHoistable<T>(T[] array, int length, int iterationCount)
{
var sink = Sink<T>.Instance;
var span = new Span<T>(array);
for (int i = 0; i < iterationCount; i++)
sink.Data = span[length/2];
}
#endregion
#region TestArrayIndexHoistable<T>
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestArrayIndexHoistableByte(int length)
{
InvokeTestArrayIndexHoistable<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestArrayIndexHoistableString(int length)
{
InvokeTestArrayIndexHoistable<string>(length);
}
static void InvokeTestArrayIndexHoistable<T>(int length)
{
var array = new T[length];
Invoke((int innerIterationCount) => TestArrayIndexHoistable<T>(array, length, innerIterationCount),
"TestArrayIndexHoistable<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestArrayIndexHoistable<T>(T[] array, int length, int iterationCount)
{
var sink = Sink<T>.Instance;
for (int i = 0; i < iterationCount; i++)
sink.Data = array[length / 2];
}
#endregion
#region TestSpanIndexVariant<T>
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestSpanIndexVariantByte(int length)
{
InvokeTestSpanIndexVariant<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestSpanIndexVariantString(int length)
{
InvokeTestSpanIndexVariant<string>(length);
}
static void InvokeTestSpanIndexVariant<T>(int length)
{
var array = new T[length];
Invoke((int innerIterationCount) => TestSpanIndexVariant<T>(array, length, innerIterationCount),
"TestSpanIndexVariant<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestSpanIndexVariant<T>(T[] array, int length, int iterationCount)
{
var sink = Sink<T>.Instance;
var span = new Span<T>(array);
int mask = (length < 2 ? 0 : (length < 8 ? 1 : 7));
for (int i = 0; i < iterationCount; i++)
sink.Data = span[i & mask];
}
#endregion
#region TestArrayIndexVariant<T>
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestArrayIndexVariantByte(int length)
{
InvokeTestArrayIndexVariant<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestArrayIndexVariantString(int length)
{
InvokeTestArrayIndexVariant<string>(length);
}
static void InvokeTestArrayIndexVariant<T>(int length)
{
var array = new T[length];
Invoke((int innerIterationCount) => TestArrayIndexVariant<T>(array, length, innerIterationCount),
"TestArrayIndexVariant<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestArrayIndexVariant<T>(T[] array, int length, int iterationCount)
{
var sink = Sink<T>.Instance;
int mask = (length < 2 ? 0 : (length < 8 ? 1 : 7));
for (int i = 0; i < iterationCount; i++)
{
sink.Data = array[i & mask];
}
}
#endregion
#region TestSpanSlice<T>
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestSpanSliceByte(int length)
{
InvokeTestSpanSlice<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestSpanSliceString(int length)
{
InvokeTestSpanSlice<string>(length);
}
static void InvokeTestSpanSlice<T>(int length)
{
var array = new T[length];
Invoke((int innerIterationCount) => TestSpanSlice<T>(array, length, innerIterationCount, false),
"TestSpanSlice<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestSpanSlice<T>(T[] array, int length, int iterationCount, bool untrue)
{
var span = new Span<T>(array);
var sink = Sink<T>.Instance;
for (int i = 0; i < iterationCount; i++)
{
var slice = span.Slice(length / 2);
// Under a condition that we know is false but the jit doesn't,
// add a read from 'span' to make sure it's not dead, and an assignment
// to 'array' so the slice call won't get hoisted.
if (untrue) { sink.Data = slice[0]; array = new T[iterationCount]; }
}
}
#endregion
#region TestSpanToArray<T>
[Benchmark(InnerIterationCount = BaseIterations / 100)]
[InlineData(100)]
public static void TestSpanToArrayByte(int length)
{
InvokeTestSpanToArray<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations / 100)]
[InlineData(100)]
public static void TestSpanToArrayString(int length)
{
InvokeTestSpanToArray<string>(length);
}
static void InvokeTestSpanToArray<T>(int length)
{
var array = new T[length];
Invoke((int innerIterationCount) => TestSpanToArray<T>(array, length, innerIterationCount),
"TestSpanToArray<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestSpanToArray<T>(T[] array, int length, int iterationCount)
{
var span = new Span<T>(array);
var sink = Sink<T[]>.Instance;
for (int i = 0; i < iterationCount; i++)
sink.Data = span.ToArray();
}
#endregion
#region TestSpanCopyTo<T>
[Benchmark(InnerIterationCount = BaseIterations / 10)]
[InlineData(100)]
public static void TestSpanCopyToByte(int length)
{
InvokeTestSpanCopyTo<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations / 100)]
[InlineData(100)]
public static void TestSpanCopyToString(int length)
{
InvokeTestSpanCopyTo<string>(length);
}
static void InvokeTestSpanCopyTo<T>(int length)
{
var array = new T[length];
var destArray = new T[array.Length];
Invoke((int innerIterationCount) => TestSpanCopyTo<T>(array, destArray, innerIterationCount),
"TestSpanCopyTo<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestSpanCopyTo<T>(T[] array, T[] destArray, int iterationCount)
{
var span = new Span<T>(array);
var destination = new Span<T>(destArray);
for (int i = 0; i < iterationCount; i++)
span.CopyTo(destination);
}
#endregion
#region TestArrayCopyTo<T>
[Benchmark(InnerIterationCount = BaseIterations / 10)]
[InlineData(100)]
public static void TestArrayCopyToByte(int length)
{
InvokeTestArrayCopyTo<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations / 100)]
[InlineData(100)]
public static void TestArrayCopyToString(int length)
{
InvokeTestArrayCopyTo<string>(length);
}
static void InvokeTestArrayCopyTo<T>(int length)
{
var array = new T[length];
var destination = new T[array.Length];
Invoke((int innerIterationCount) => TestArrayCopyTo<T>(array, destination, innerIterationCount),
"TestArrayCopyTo<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestArrayCopyTo<T>(T[] array, T[] destination, int iterationCount)
{
for (int i = 0; i < iterationCount; i++)
array.CopyTo(destination, 0);
}
#endregion
#region TestSpanFill<T>
[Benchmark(InnerIterationCount = BaseIterations * 10)]
[InlineData(100)]
public static void TestSpanFillByte(int length)
{
InvokeTestSpanFill<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations / 100)]
[InlineData(100)]
public static void TestSpanFillString(int length)
{
InvokeTestSpanFill<string>(length);
}
static void InvokeTestSpanFill<T>(int length)
{
var array = new T[length];
Invoke((int innerIterationCount) => TestSpanFill<T>(array, innerIterationCount),
"TestSpanFill<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestSpanFill<T>(T[] array, int iterationCount)
{
var span = new Span<T>(array);
for (int i = 0; i < iterationCount; i++)
span.Fill(default(T));
}
#endregion
#region TestSpanClear<T>
[Benchmark(InnerIterationCount = BaseIterations / 10)]
[InlineData(100)]
public static void TestSpanClearByte(int length)
{
InvokeTestSpanClear<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations / 10)]
[InlineData(100)]
public static void TestSpanClearString(int length)
{
InvokeTestSpanClear<string>(length);
}
static void InvokeTestSpanClear<T>(int length)
{
var array = new T[length];
Invoke((int innerIterationCount) => TestSpanClear<T>(array, innerIterationCount),
"TestSpanClear<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestSpanClear<T>(T[] array, int iterationCount)
{
var span = new Span<T>(array);
for (int i = 0; i < iterationCount; i++)
span.Clear();
}
#endregion
#region TestArrayClear<T>
[Benchmark(InnerIterationCount = BaseIterations / 10)]
[InlineData(100)]
public static void TestArrayClearByte(int length)
{
InvokeTestArrayClear<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations / 10)]
[InlineData(100)]
public static void TestArrayClearString(int length)
{
InvokeTestArrayClear<string>(length);
}
static void InvokeTestArrayClear<T>(int length)
{
var array = new T[length];
Invoke((int innerIterationCount) => TestArrayClear<T>(array, length, innerIterationCount),
"TestArrayClear<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestArrayClear<T>(T[] array, int length, int iterationCount)
{
for (int i = 0; i < iterationCount; i++)
Array.Clear(array, 0, length);
}
#endregion
#region TestSpanAsBytes<T>
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestSpanAsBytesByte(int length)
{
InvokeTestSpanAsBytes<byte>(length);
}
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestSpanAsBytesInt(int length)
{
InvokeTestSpanAsBytes<int>(length);
}
static void InvokeTestSpanAsBytes<T>(int length)
where T : struct
{
var array = new T[length];
Invoke((int innerIterationCount) => TestSpanAsBytes<T>(array, innerIterationCount, false),
"TestSpanAsBytes<{0}>({1})", typeof(T).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestSpanAsBytes<T>(T[] array, int iterationCount, bool untrue)
where T : struct
{
var sink = Sink<byte>.Instance;
var span = new Span<T>(array);
for (int i = 0; i < iterationCount; i++)
{
var byteSpan = span.AsBytes();
// Under a condition that we know is false but the jit doesn't,
// add a read from 'byteSpan' to make sure it's not dead, and an assignment
// to 'span' so the AsBytes call won't get hoisted.
if (untrue) { sink.Data = byteSpan[0]; span = new Span<T>(); }
}
}
#endregion
#region TestSpanCast<T>
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestSpanCastFromByteToInt(int length)
{
InvokeTestSpanCast<byte, int>(length);
}
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestSpanCastFromIntToByte(int length)
{
InvokeTestSpanCast<int, byte>(length);
}
static void InvokeTestSpanCast<From, To>(int length)
where From : struct
where To : struct
{
var array = new From[length];
Invoke((int innerIterationCount) => TestSpanCast<From, To>(array, innerIterationCount, false),
"TestSpanCast<{0}, {1}>({2})", typeof(From).Name, typeof(To).Name, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestSpanCast<From, To>(From[] array, int iterationCount, bool untrue)
where From : struct
where To : struct
{
var sink = Sink<To>.Instance;
var span = new Span<From>(array);
for (int i = 0; i < iterationCount; i++)
{
var toSpan = MemoryMarshal.Cast<From, To>(span);
// Under a condition that we know is false but the jit doesn't,
// add a read from 'toSpan' to make sure it's not dead, and an assignment
// to 'span' so the AsBytes call won't get hoisted.
if (untrue) { sink.Data = toSpan[0]; span = new Span<From>(); }
}
}
#endregion
#region TestSpanAsSpanStringChar<T>
[Benchmark(InnerIterationCount = BaseIterations)]
[InlineData(100)]
public static void TestSpanAsSpanStringCharWrapper(int length)
{
StringBuilder sb = new StringBuilder();
Random rand = new Random(42);
char[] c = new char[1];
for (int i = 0; i < length; i++)
{
c[0] = (char)rand.Next(32, 126);
sb.Append(new string(c));
}
string s = sb.ToString();
Invoke((int innerIterationCount) => TestSpanAsSpanStringChar(s, innerIterationCount, false),
"TestSpanAsSpanStringChar({0})", length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void TestSpanAsSpanStringChar(string s, int iterationCount, bool untrue)
{
var sink = Sink<char>.Instance;
for (int i = 0; i < iterationCount; i++)
{
var charSpan = s.AsSpan();
// Under a condition that we know is false but the jit doesn't,
// add a read from 'charSpan' to make sure it's not dead, and an assignment
// to 's' so the AsBytes call won't get hoisted.
if (untrue) { sink.Data = charSpan[0]; s = "block hoisting the call to AsSpan()"; }
}
}
#endregion
#endregion // TestSpanAPIs
public static int Main(string[] args)
{
// When we call into Invoke, it'll need to know this isn't xunit-perf running
IsXunitInvocation = false;
// Now simulate xunit-perf's benchmark discovery so we know what tests to invoke
TypeInfo t = typeof(SpanBench).GetTypeInfo();
foreach(MethodInfo m in t.DeclaredMethods)
{
BenchmarkAttribute benchAttr = m.GetCustomAttribute<BenchmarkAttribute>();
if (benchAttr != null)
{
// All benchmark methods in this test set the InnerIterationCount on their BenchmarkAttribute.
// Take max of specified count and 1 since some tests use expressions for their count that
// evaluate to 0 under DEBUG.
CommandLineInnerIterationCount = Math.Max((int)benchAttr.InnerIterationCount, 1);
// Request a warm-up iteration before measuring this benchmark method.
DoWarmUp = true;
// Get the benchmark to measure as a delegate taking the number of inner-loop iterations to run
var invokeMethod = m.CreateDelegate(typeof(Action<int>)) as Action<int>;
// All the benchmarks methods in this test use [InlineData] to specify how many times and with
// what arguments they should be run.
foreach (InlineDataAttribute dataAttr in m.GetCustomAttributes<InlineDataAttribute>())
{
foreach (object[] data in dataAttr.GetData(m))
{
// All the benchmark methods in this test take a single int parameter
invokeMethod((int)data[0]);
}
}
}
}
// The only failure modes are crash/exception.
return 100;
}
}
}
| |
using NUnit.Framework;
namespace Lucene.Net.Index
{
/*
* 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 Codec = Lucene.Net.Codecs.Codec;
using TestUtil = Lucene.Net.Util.TestUtil;
/// <summary>
/// Tests the codec configuration defined by LuceneTestCase randomly
/// (typically a mix across different fields).
/// </summary>
[SuppressCodecs("Lucene3x")]
public class TestDocValuesFormat : BaseDocValuesFormatTestCase
{
protected override Codec Codec
{
get
{
return Codec.Default;
}
}
protected internal override bool CodecAcceptsHugeBinaryValues(string field)
{
return TestUtil.FieldSupportsHugeBinaryDocValues(field);
}
#region BaseDocValuesFormatTestCase
// LUCENENET NOTE: Tests in an abstract base class are not pulled into the correct
// context in Visual Studio. This fixes that with the minimum amount of code necessary
// to run them in the correct context without duplicating all of the tests.
[Test]
public override void TestOneNumber()
{
base.TestOneNumber();
}
[Test]
public override void TestOneFloat()
{
base.TestOneFloat();
}
[Test]
public override void TestTwoNumbers()
{
base.TestTwoNumbers();
}
[Test]
public override void TestTwoBinaryValues()
{
base.TestTwoBinaryValues();
}
[Test]
public override void TestTwoFieldsMixed()
{
base.TestTwoFieldsMixed();
}
[Test]
public override void TestThreeFieldsMixed()
{
base.TestThreeFieldsMixed();
}
[Test]
public override void TestThreeFieldsMixed2()
{
base.TestThreeFieldsMixed2();
}
[Test]
public override void TestTwoDocumentsNumeric()
{
base.TestTwoDocumentsNumeric();
}
[Test]
public override void TestTwoDocumentsMerged()
{
base.TestTwoDocumentsMerged();
}
[Test]
public override void TestBigNumericRange()
{
base.TestBigNumericRange();
}
[Test]
public override void TestBigNumericRange2()
{
base.TestBigNumericRange2();
}
[Test]
public override void TestBytes()
{
base.TestBytes();
}
[Test]
public override void TestBytesTwoDocumentsMerged()
{
base.TestBytesTwoDocumentsMerged();
}
[Test]
public override void TestSortedBytes()
{
base.TestSortedBytes();
}
[Test]
public override void TestSortedBytesTwoDocuments()
{
base.TestSortedBytesTwoDocuments();
}
[Test]
public override void TestSortedBytesThreeDocuments()
{
base.TestSortedBytesThreeDocuments();
}
[Test]
public override void TestSortedBytesTwoDocumentsMerged()
{
base.TestSortedBytesTwoDocumentsMerged();
}
[Test]
public override void TestSortedMergeAwayAllValues()
{
base.TestSortedMergeAwayAllValues();
}
[Test]
public override void TestBytesWithNewline()
{
base.TestBytesWithNewline();
}
[Test]
public override void TestMissingSortedBytes()
{
base.TestMissingSortedBytes();
}
[Test]
public override void TestSortedTermsEnum()
{
base.TestSortedTermsEnum();
}
[Test]
public override void TestEmptySortedBytes()
{
base.TestEmptySortedBytes();
}
[Test]
public override void TestEmptyBytes()
{
base.TestEmptyBytes();
}
[Test]
public override void TestVeryLargeButLegalBytes()
{
base.TestVeryLargeButLegalBytes();
}
[Test]
public override void TestVeryLargeButLegalSortedBytes()
{
base.TestVeryLargeButLegalSortedBytes();
}
[Test]
public override void TestCodecUsesOwnBytes()
{
base.TestCodecUsesOwnBytes();
}
[Test]
public override void TestCodecUsesOwnSortedBytes()
{
base.TestCodecUsesOwnSortedBytes();
}
[Test]
public override void TestCodecUsesOwnBytesEachTime()
{
base.TestCodecUsesOwnBytesEachTime();
}
[Test]
public override void TestCodecUsesOwnSortedBytesEachTime()
{
base.TestCodecUsesOwnSortedBytesEachTime();
}
/*
* Simple test case to show how to use the API
*/
[Test]
public override void TestDocValuesSimple()
{
base.TestDocValuesSimple();
}
[Test]
public override void TestRandomSortedBytes()
{
base.TestRandomSortedBytes();
}
[Test]
public override void TestBooleanNumericsVsStoredFields()
{
base.TestBooleanNumericsVsStoredFields();
}
[Test]
public override void TestByteNumericsVsStoredFields()
{
base.TestByteNumericsVsStoredFields();
}
[Test]
public override void TestByteMissingVsFieldCache()
{
base.TestByteMissingVsFieldCache();
}
[Test]
public override void TestShortNumericsVsStoredFields()
{
base.TestShortNumericsVsStoredFields();
}
[Test]
public override void TestShortMissingVsFieldCache()
{
base.TestShortMissingVsFieldCache();
}
[Test]
public override void TestIntNumericsVsStoredFields()
{
base.TestIntNumericsVsStoredFields();
}
[Test]
public override void TestIntMissingVsFieldCache()
{
base.TestIntMissingVsFieldCache();
}
[Test]
public override void TestLongNumericsVsStoredFields()
{
base.TestLongNumericsVsStoredFields();
}
[Test]
public override void TestLongMissingVsFieldCache()
{
base.TestLongMissingVsFieldCache();
}
[Test]
public override void TestBinaryFixedLengthVsStoredFields()
{
base.TestBinaryFixedLengthVsStoredFields();
}
[Test]
public override void TestBinaryVariableLengthVsStoredFields()
{
base.TestBinaryVariableLengthVsStoredFields();
}
[Test]
public override void TestSortedFixedLengthVsStoredFields()
{
base.TestSortedFixedLengthVsStoredFields();
}
[Test]
public override void TestSortedFixedLengthVsFieldCache()
{
base.TestSortedFixedLengthVsFieldCache();
}
[Test]
public override void TestSortedVariableLengthVsFieldCache()
{
base.TestSortedVariableLengthVsFieldCache();
}
[Test]
public override void TestSortedVariableLengthVsStoredFields()
{
base.TestSortedVariableLengthVsStoredFields();
}
[Test]
public override void TestSortedSetOneValue()
{
base.TestSortedSetOneValue();
}
[Test]
public override void TestSortedSetTwoFields()
{
base.TestSortedSetTwoFields();
}
[Test]
public override void TestSortedSetTwoDocumentsMerged()
{
base.TestSortedSetTwoDocumentsMerged();
}
[Test]
public override void TestSortedSetTwoValues()
{
base.TestSortedSetTwoValues();
}
[Test]
public override void TestSortedSetTwoValuesUnordered()
{
base.TestSortedSetTwoValuesUnordered();
}
[Test]
public override void TestSortedSetThreeValuesTwoDocs()
{
base.TestSortedSetThreeValuesTwoDocs();
}
[Test]
public override void TestSortedSetTwoDocumentsLastMissing()
{
base.TestSortedSetTwoDocumentsLastMissing();
}
[Test]
public override void TestSortedSetTwoDocumentsLastMissingMerge()
{
base.TestSortedSetTwoDocumentsLastMissingMerge();
}
[Test]
public override void TestSortedSetTwoDocumentsFirstMissing()
{
base.TestSortedSetTwoDocumentsFirstMissing();
}
[Test]
public override void TestSortedSetTwoDocumentsFirstMissingMerge()
{
base.TestSortedSetTwoDocumentsFirstMissingMerge();
}
[Test]
public override void TestSortedSetMergeAwayAllValues()
{
base.TestSortedSetMergeAwayAllValues();
}
[Test]
public override void TestSortedSetTermsEnum()
{
base.TestSortedSetTermsEnum();
}
[Test]
public override void TestSortedSetFixedLengthVsStoredFields()
{
base.TestSortedSetFixedLengthVsStoredFields();
}
[Test]
public override void TestSortedSetVariableLengthVsStoredFields()
{
base.TestSortedSetVariableLengthVsStoredFields();
}
[Test]
public override void TestSortedSetFixedLengthSingleValuedVsStoredFields()
{
base.TestSortedSetFixedLengthSingleValuedVsStoredFields();
}
[Test]
public override void TestSortedSetVariableLengthSingleValuedVsStoredFields()
{
base.TestSortedSetVariableLengthSingleValuedVsStoredFields();
}
[Test]
public override void TestSortedSetFixedLengthVsUninvertedField()
{
base.TestSortedSetFixedLengthVsUninvertedField();
}
[Test]
public override void TestSortedSetVariableLengthVsUninvertedField()
{
base.TestSortedSetVariableLengthVsUninvertedField();
}
[Test]
public override void TestGCDCompression()
{
base.TestGCDCompression();
}
[Test]
public override void TestZeros()
{
base.TestZeros();
}
[Test]
public override void TestZeroOrMin()
{
base.TestZeroOrMin();
}
[Test]
public override void TestTwoNumbersOneMissing()
{
base.TestTwoNumbersOneMissing();
}
[Test]
public override void TestTwoNumbersOneMissingWithMerging()
{
base.TestTwoNumbersOneMissingWithMerging();
}
[Test]
public override void TestThreeNumbersOneMissingWithMerging()
{
base.TestThreeNumbersOneMissingWithMerging();
}
[Test]
public override void TestTwoBytesOneMissing()
{
base.TestTwoBytesOneMissing();
}
[Test]
public override void TestTwoBytesOneMissingWithMerging()
{
base.TestTwoBytesOneMissingWithMerging();
}
[Test]
public override void TestThreeBytesOneMissingWithMerging()
{
base.TestThreeBytesOneMissingWithMerging();
}
// LUCENE-4853
[Test]
public override void TestHugeBinaryValues()
{
base.TestHugeBinaryValues();
}
// TODO: get this out of here and into the deprecated codecs (4.0, 4.2)
[Test]
public override void TestHugeBinaryValueLimit()
{
base.TestHugeBinaryValueLimit();
}
/// <summary>
/// Tests dv against stored fields with threads (binary/numeric/sorted, no missing)
/// </summary>
[Test]
public override void TestThreads()
{
base.TestThreads();
}
/// <summary>
/// Tests dv against stored fields with threads (all types + missing)
/// </summary>
[Test]
public override void TestThreads2()
{
base.TestThreads2();
}
// LUCENE-5218
[Test]
public override void TestEmptyBinaryValueOnPageSizes()
{
base.TestEmptyBinaryValueOnPageSizes();
}
#endregion
#region BaseIndexFileFormatTestCase
// LUCENENET NOTE: Tests in an abstract base class are not pulled into the correct
// context in Visual Studio. This fixes that with the minimum amount of code necessary
// to run them in the correct context without duplicating all of the tests.
[Test]
public override void TestMergeStability()
{
base.TestMergeStability();
}
#endregion
}
}
| |
using System;
using System.Linq;
using ZendeskApi_v2.Models;
using ZendeskApi_v2.Models.Groups;
using ZendeskApi_v2.Models.Organizations;
#if ASYNC
using System.Threading.Tasks;
#endif
using ZendeskApi_v2.Models.Search;
using ZendeskApi_v2.Models.Tickets;
using ZendeskApi_v2.Models.Users;
namespace ZendeskApi_v2.Requests
{
public interface ISearch : ICore
{
#if SYNC
/// <summary>
///
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
SearchResults SearchFor(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null);
/// <summary>
///
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
SearchResults<T> SearchFor<T>(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null) where T : ISearchable;
/// <summary>
/// This resource behaves the same as SearchFor, but allows anonymous users to search public forums
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
SearchResults AnonymousSearchFor(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null);
/// <summary>
/// This resource behaves the same as SearchFor, but allows anonymous users to search public forums
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
SearchResults<T> AnonymousSearchFor<T>(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null) where T : ISearchable;
#endif
#if ASYNC
/// <summary>
///
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
Task<SearchResults> SearchForAsync(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null);
/// <summary>
///
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
Task<SearchResults<T>> SearchForAsync<T>(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null) where T : ISearchable;
/// <summary>
/// This resource behaves the same as SearchFor, but allows anonymous users to search public forums
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
Task<SearchResults> AnonymousSearchForAsync(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null);
/// <summary>
/// This resource behaves the same as SearchFor, but allows anonymous users to search public forums
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
Task<SearchResults<T>> AnonymousSearchForAsync<T>(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null) where T : ISearchable;
#endif
}
/// <summary>
/// The search API is a unified search API that returns tickets, users, organizations, and forum topics.
/// Define filters to narrow your search results according to result type, date attributes, and object attributes such as ticket requester or tag.
/// </summary>
public class Search : Core, ISearch
{
public Search(string yourZendeskUrl, string user, string password, string apiToken, string p_OAuthToken)
: base(yourZendeskUrl, user, password, apiToken, p_OAuthToken)
{
}
#if SYNC
/// <summary>
///
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
public SearchResults SearchFor(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null)
{
var resource = string.Format("search.json?query={0}", searchTerm);
return GenericPagedSortedGet<SearchResults>(resource, perPage, page, sortBy, SortOrderAscending(sortOrder));
}
/// <summary>
///
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
public SearchResults<T> SearchFor<T>(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null) where T : ISearchable
{
var resource = string.Format("search.json?query={0}", AddTypeToSearchTerm<T>(searchTerm));
return GenericPagedSortedGet<SearchResults<T>>(resource, perPage, page, sortBy, SortOrderAscending(sortOrder));
}
/// <summary>
/// This resource behaves the same as SearchFor, but allows anonymous users to search public forums
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
public SearchResults AnonymousSearchFor(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null)
{
var resource = string.Format("portal/search.json?query={0}", searchTerm);
return GenericPagedSortedGet<SearchResults>(resource, perPage, page, sortBy, SortOrderAscending(sortOrder));
}
/// <summary>
/// This resource behaves the same as SearchFor, but allows anonymous users to search public forums
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
public SearchResults<T> AnonymousSearchFor<T>(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null) where T : ISearchable
{
var resource = string.Format("portal/search.json?query={0}", AddTypeToSearchTerm<T>(searchTerm));
return GenericPagedSortedGet<SearchResults<T>>(resource, perPage, page, sortBy, SortOrderAscending(sortOrder));
}
#endif
#if ASYNC
/// <summary>
///
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
public async Task<SearchResults> SearchForAsync(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null)
{
var resource = string.Format("search.json?query={0}", searchTerm);
return await GenericPagedSortedGetAsync<SearchResults>(resource, perPage, page, sortBy, SortOrderAscending(sortOrder));
}
/// <summary>
///
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
public async Task<SearchResults<T>> SearchForAsync<T>(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null) where T : ISearchable
{
var resource = string.Format("search.json?query={0}", AddTypeToSearchTerm<T>(searchTerm));
return await GenericPagedSortedGetAsync<SearchResults<T>>(resource, perPage, page, sortBy, SortOrderAscending(sortOrder));
}
/// <summary>
/// This resource behaves the same as SearchFor, but allows anonymous users to search public forums
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
public async Task<SearchResults> AnonymousSearchForAsync(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null)
{
var resource = string.Format("portal/search.json?query={0}", searchTerm);
return await GenericPagedSortedGetAsync<SearchResults>(resource, perPage, page, sortBy, SortOrderAscending(sortOrder));
}
/// <summary>
/// This resource behaves the same as SearchFor, but allows anonymous users to search public forums
/// </summary>
/// <param name="searchTerm"></param>
/// <param name="page">Returns specified {page} - pagination</param>
/// <param name="sortBy">Possible values are 'updated_at', 'created_at', 'priority', 'status', and 'ticket_type</param>
/// <param name="sortOrder">Possible values are 'relevance', 'asc', 'desc'. Defaults to 'relevance' when no 'order' criteria is requested.</param>
/// <returns></returns>
public async Task<SearchResults<T>> AnonymousSearchForAsync<T>(string searchTerm, string sortBy = "", string sortOrder = "", int page = 1, int? perPage = null) where T : ISearchable
{
var resource = string.Format("portal/search.json?query={0}", AddTypeToSearchTerm<T>(searchTerm));
return await GenericPagedSortedGetAsync<SearchResults<T>>(resource, perPage, page, sortBy, SortOrderAscending(sortOrder));
}
#endif
public string AddTypeToSearchTerm<T>(string searchTerm = "")
{
string typeName = typeof(T).Name;
return "type:" + typeName + (!(string.IsNullOrEmpty(searchTerm.Trim())) ? " " : "") + searchTerm.Trim();
}
public bool SortOrderAscending(string sortOrder)
{
return (sortOrder ?? "ascending").ToLower() == "ascending";
}
}
}
| |
#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;
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0
using System.Numerics;
#endif
using System.Text;
using Newtonsoft.Json.Converters;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
using TestCase = Xunit.InlineDataAttribute;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Linq;
using System.IO;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
using Newtonsoft.Json.Utilities;
#endif
namespace Newtonsoft.Json.Tests.Linq
{
[TestFixture]
public class JTokenTests : TestFixtureBase
{
[Test]
public void DeepEqualsObjectOrder()
{
string ob1 = @"{""key1"":""1"",""key2"":""2""}";
string ob2 = @"{""key2"":""2"",""key1"":""1""}";
JObject j1 = JObject.Parse(ob1);
JObject j2 = JObject.Parse(ob2);
Assert.IsTrue(j1.DeepEquals(j2));
}
[Test]
public void ReadFrom()
{
JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(new StringReader("{'pie':true}")));
Assert.AreEqual(true, (bool)o["pie"]);
JArray a = (JArray)JToken.ReadFrom(new JsonTextReader(new StringReader("[1,2,3]")));
Assert.AreEqual(1, (int)a[0]);
Assert.AreEqual(2, (int)a[1]);
Assert.AreEqual(3, (int)a[2]);
JsonReader reader = new JsonTextReader(new StringReader("{'pie':true}"));
reader.Read();
reader.Read();
JProperty p = (JProperty)JToken.ReadFrom(reader);
Assert.AreEqual("pie", p.Name);
Assert.AreEqual(true, (bool)p.Value);
JConstructor c = (JConstructor)JToken.ReadFrom(new JsonTextReader(new StringReader("new Date(1)")));
Assert.AreEqual("Date", c.Name);
Assert.IsTrue(JToken.DeepEquals(new JValue(1), c.Values().ElementAt(0)));
JValue v;
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"""stringvalue""")));
Assert.AreEqual("stringvalue", (string)v);
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1")));
Assert.AreEqual(1, (int)v);
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1.1")));
Assert.AreEqual(1.1, (double)v);
#if !NET20
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"""1970-01-01T00:00:00+12:31"""))
{
DateParseHandling = DateParseHandling.DateTimeOffset
});
Assert.AreEqual(typeof(DateTimeOffset), v.Value.GetType());
Assert.AreEqual(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, new TimeSpan(12, 31, 0)), v.Value);
#endif
}
[Test]
public void Load()
{
JObject o = (JObject)JToken.Load(new JsonTextReader(new StringReader("{'pie':true}")));
Assert.AreEqual(true, (bool)o["pie"]);
}
[Test]
public void Parse()
{
JObject o = (JObject)JToken.Parse("{'pie':true}");
Assert.AreEqual(true, (bool)o["pie"]);
}
[Test]
public void Parent()
{
JArray v = new JArray(new JConstructor("TestConstructor"), new JValue(new DateTime(2000, 12, 20)));
Assert.AreEqual(null, v.Parent);
JObject o =
new JObject(
new JProperty("Test1", v),
new JProperty("Test2", "Test2Value"),
new JProperty("Test3", "Test3Value"),
new JProperty("Test4", null)
);
Assert.AreEqual(o.Property("Test1"), v.Parent);
JProperty p = new JProperty("NewProperty", v);
// existing value should still have same parent
Assert.AreEqual(o.Property("Test1"), v.Parent);
// new value should be cloned
Assert.AreNotSame(p.Value, v);
Assert.AreEqual((DateTime)((JValue)p.Value[1]).Value, (DateTime)((JValue)v[1]).Value);
Assert.AreEqual(v, o["Test1"]);
Assert.AreEqual(null, o.Parent);
JProperty o1 = new JProperty("O1", o);
Assert.AreEqual(o, o1.Value);
Assert.AreNotEqual(null, o.Parent);
JProperty o2 = new JProperty("O2", o);
Assert.AreNotSame(o1.Value, o2.Value);
Assert.AreEqual(o1.Value.Children().Count(), o2.Value.Children().Count());
Assert.AreEqual(false, JToken.DeepEquals(o1, o2));
Assert.AreEqual(true, JToken.DeepEquals(o1.Value, o2.Value));
}
[Test]
public void Next()
{
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
JToken next = a[0].Next;
Assert.AreEqual(6, (int)next);
next = next.Next;
Assert.IsTrue(JToken.DeepEquals(new JArray(7, 8), next));
next = next.Next;
Assert.IsTrue(JToken.DeepEquals(new JArray(9, 10), next));
next = next.Next;
Assert.IsNull(next);
}
[Test]
public void Previous()
{
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
JToken previous = a[3].Previous;
Assert.IsTrue(JToken.DeepEquals(new JArray(7, 8), previous));
previous = previous.Previous;
Assert.AreEqual(6, (int)previous);
previous = previous.Previous;
Assert.AreEqual(5, (int)previous);
previous = previous.Previous;
Assert.IsNull(previous);
}
[Test]
public void Children()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
Assert.AreEqual(4, a.Count());
Assert.AreEqual(3, a.Children<JArray>().Count());
}
[Test]
public void BeforeAfter()
{
JArray a =
new JArray(
5,
new JArray(1, 2, 3),
new JArray(1, 2, 3),
new JArray(1, 2, 3)
);
Assert.AreEqual(5, (int)a[1].Previous);
Assert.AreEqual(2, a[2].BeforeSelf().Count());
}
[Test]
public void BeforeSelf_NoParent_ReturnEmpty()
{
JObject o = new JObject();
List<JToken> result = o.BeforeSelf().ToList();
Assert.AreEqual(0, result.Count);
}
[Test]
public void BeforeSelf_OnlyChild_ReturnEmpty()
{
JArray a = new JArray();
JObject o = new JObject();
a.Add(o);
List<JToken> result = o.BeforeSelf().ToList();
Assert.AreEqual(0, result.Count);
}
#nullable enable
[Test]
public void Casting()
{
Assert.AreEqual(1L, (long)(new JValue(1)));
Assert.AreEqual(2L, (long)new JArray(1, 2, 3)[1]);
Assert.AreEqual(new DateTime(2000, 12, 20), (DateTime)new JValue(new DateTime(2000, 12, 20)));
#if !NET20
Assert.AreEqual(new DateTimeOffset(2000, 12, 20, 0, 0, 0, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTime(2000, 12, 20, 0, 0, 0, DateTimeKind.Utc)));
Assert.AreEqual(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)));
Assert.AreEqual(null, (DateTimeOffset?)new JValue((DateTimeOffset?)null));
Assert.AreEqual(null, (DateTimeOffset?)(JValue?)null);
#endif
Assert.AreEqual(true, (bool)new JValue(true));
Assert.AreEqual(true, (bool?)new JValue(true));
Assert.AreEqual(null, (bool?)((JValue?)null));
Assert.AreEqual(null, (bool?)JValue.CreateNull());
Assert.AreEqual(10, (long)new JValue(10));
Assert.AreEqual(null, (long?)new JValue((long?)null));
Assert.AreEqual(null, (long?)(JValue?)null);
Assert.AreEqual(null, (int?)new JValue((int?)null));
Assert.AreEqual(null, (int?)(JValue?)null);
Assert.AreEqual(null, (DateTime?)new JValue((DateTime?)null));
Assert.AreEqual(null, (DateTime?)(JValue?)null);
Assert.AreEqual(null, (short?)new JValue((short?)null));
Assert.AreEqual(null, (short?)(JValue?)null);
Assert.AreEqual(null, (float?)new JValue((float?)null));
Assert.AreEqual(null, (float?)(JValue?)null);
Assert.AreEqual(null, (double?)new JValue((double?)null));
Assert.AreEqual(null, (double?)(JValue?)null);
Assert.AreEqual(null, (decimal?)new JValue((decimal?)null));
Assert.AreEqual(null, (decimal?)(JValue?)null);
Assert.AreEqual(null, (uint?)new JValue((uint?)null));
Assert.AreEqual(null, (uint?)(JValue?)null);
Assert.AreEqual(null, (sbyte?)new JValue((sbyte?)null));
Assert.AreEqual(null, (sbyte?)(JValue?)null);
Assert.AreEqual(null, (byte?)new JValue((byte?)null));
Assert.AreEqual(null, (byte?)(JValue?)null);
Assert.AreEqual(null, (ulong?)new JValue((ulong?)null));
Assert.AreEqual(null, (ulong?)(JValue?)null);
Assert.AreEqual(null, (uint?)new JValue((uint?)null));
Assert.AreEqual(null, (uint?)(JValue?)null);
Assert.AreEqual(11.1f, (float)new JValue(11.1));
Assert.AreEqual(float.MinValue, (float)new JValue(float.MinValue));
Assert.AreEqual(1.1, (double)new JValue(1.1));
Assert.AreEqual(uint.MaxValue, (uint)new JValue(uint.MaxValue));
Assert.AreEqual(ulong.MaxValue, (ulong)new JValue(ulong.MaxValue));
Assert.AreEqual(ulong.MaxValue, (ulong)new JProperty("Test", new JValue(ulong.MaxValue)));
Assert.AreEqual(null, (string?)new JValue((string?)null));
Assert.AreEqual(5m, (decimal)(new JValue(5L)));
Assert.AreEqual(5m, (decimal?)(new JValue(5L)));
Assert.AreEqual(5f, (float)(new JValue(5L)));
Assert.AreEqual(5f, (float)(new JValue(5m)));
Assert.AreEqual(5f, (float?)(new JValue(5m)));
Assert.AreEqual(5, (byte)(new JValue(5)));
Assert.AreEqual(SByte.MinValue, (sbyte?)(new JValue(SByte.MinValue)));
Assert.AreEqual(SByte.MinValue, (sbyte)(new JValue(SByte.MinValue)));
Assert.AreEqual(null, (sbyte?)JValue.CreateNull());
Assert.AreEqual("1", (string?)(new JValue(1)));
Assert.AreEqual("1", (string?)(new JValue(1.0)));
Assert.AreEqual("1.0", (string?)(new JValue(1.0m)));
Assert.AreEqual("True", (string?)(new JValue(true)));
Assert.AreEqual(null, (string?)(JValue.CreateNull()));
Assert.AreEqual(null, (string?)(JValue?)null);
Assert.AreEqual("12/12/2000 12:12:12", (string?)(new JValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc))));
#if !NET20
Assert.AreEqual("12/12/2000 12:12:12 +00:00", (string?)(new JValue(new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero))));
#endif
Assert.AreEqual(true, (bool)(new JValue(1)));
Assert.AreEqual(true, (bool)(new JValue(1.0)));
Assert.AreEqual(true, (bool)(new JValue("true")));
Assert.AreEqual(true, (bool)(new JValue(true)));
Assert.AreEqual(true, (bool)(new JValue(2)));
Assert.AreEqual(false, (bool)(new JValue(0)));
Assert.AreEqual(1, (int)(new JValue(1)));
Assert.AreEqual(1, (int)(new JValue(1.0)));
Assert.AreEqual(1, (int)(new JValue("1")));
Assert.AreEqual(1, (int)(new JValue(true)));
Assert.AreEqual(1m, (decimal)(new JValue(1)));
Assert.AreEqual(1m, (decimal)(new JValue(1.0)));
Assert.AreEqual(1m, (decimal)(new JValue("1")));
Assert.AreEqual(1m, (decimal)(new JValue(true)));
Assert.AreEqual(TimeSpan.FromMinutes(1), (TimeSpan)(new JValue(TimeSpan.FromMinutes(1))));
Assert.AreEqual("00:01:00", (string?)(new JValue(TimeSpan.FromMinutes(1))));
Assert.AreEqual(TimeSpan.FromMinutes(1), (TimeSpan)(new JValue("00:01:00")));
Assert.AreEqual("46efe013-b56a-4e83-99e4-4dce7678a5bc", (string?)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"))));
Assert.AreEqual("http://www.google.com/", (string?)(new JValue(new Uri("http://www.google.com"))));
Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")));
Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"))));
Assert.AreEqual(new Uri("http://www.google.com"), (Uri?)(new JValue("http://www.google.com")));
Assert.AreEqual(new Uri("http://www.google.com"), (Uri?)(new JValue(new Uri("http://www.google.com"))));
Assert.AreEqual(null, (Uri?)(JValue.CreateNull()));
Assert.AreEqual(Convert.ToBase64String(Encoding.UTF8.GetBytes("hi")), (string?)(new JValue(Encoding.UTF8.GetBytes("hi"))));
CollectionAssert.AreEquivalent((byte[])Encoding.UTF8.GetBytes("hi"), (byte[]?)(new JValue(Convert.ToBase64String(Encoding.UTF8.GetBytes("hi")))));
Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC").ToByteArray())));
Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid?)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC").ToByteArray())));
Assert.AreEqual((sbyte?)1, (sbyte?)(new JValue((short?)1)));
Assert.AreEqual(null, (Uri?)(JValue?)null);
Assert.AreEqual(null, (int?)(JValue?)null);
Assert.AreEqual(null, (uint?)(JValue?)null);
Assert.AreEqual(null, (Guid?)(JValue?)null);
Assert.AreEqual(null, (TimeSpan?)(JValue?)null);
Assert.AreEqual(null, (byte[]?)(JValue?)null);
Assert.AreEqual(null, (bool?)(JValue?)null);
Assert.AreEqual(null, (char?)(JValue?)null);
Assert.AreEqual(null, (DateTime?)(JValue?)null);
#if !NET20
Assert.AreEqual(null, (DateTimeOffset?)(JValue?)null);
#endif
Assert.AreEqual(null, (short?)(JValue?)null);
Assert.AreEqual(null, (ushort?)(JValue?)null);
Assert.AreEqual(null, (byte?)(JValue?)null);
Assert.AreEqual(null, (byte?)(JValue?)null);
Assert.AreEqual(null, (sbyte?)(JValue?)null);
Assert.AreEqual(null, (sbyte?)(JValue?)null);
Assert.AreEqual(null, (long?)(JValue?)null);
Assert.AreEqual(null, (ulong?)(JValue?)null);
Assert.AreEqual(null, (double?)(JValue?)null);
Assert.AreEqual(null, (float?)(JValue?)null);
byte[] data = new byte[0];
Assert.AreEqual(data, (byte[]?)(new JValue(data)));
Assert.AreEqual(5, (int)(new JValue(StringComparison.OrdinalIgnoreCase)));
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0
string bigIntegerText = "1234567899999999999999999999999999999999999999999999999999999999999990";
Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(BigInteger.Parse(bigIntegerText))).Value);
Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(bigIntegerText)).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(long.MaxValue), (new JValue(long.MaxValue)).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(4.5d), (new JValue((4.5d))).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(4.5f), (new JValue((4.5f))).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(byte.MaxValue), (new JValue(byte.MaxValue)).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(123), (new JValue(123)).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(123), (new JValue(123)).ToObject<BigInteger?>());
Assert.AreEqual(null, (JValue.CreateNull()).ToObject<BigInteger?>());
byte[]? intData = BigInteger.Parse(bigIntegerText).ToByteArray();
Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(intData)).ToObject<BigInteger>());
Assert.AreEqual(4.0d, (double)(new JValue(new BigInteger(4.5d))));
Assert.AreEqual(true, (bool)(new JValue(new BigInteger(1))));
Assert.AreEqual(long.MaxValue, (long)(new JValue(new BigInteger(long.MaxValue))));
Assert.AreEqual(long.MaxValue, (long)(new JValue(new BigInteger(new byte[] { 255, 255, 255, 255, 255, 255, 255, 127 }))));
Assert.AreEqual("9223372036854775807", (string?)(new JValue(new BigInteger(long.MaxValue))));
intData = (byte[]?)new JValue(new BigInteger(long.MaxValue));
CollectionAssert.AreEqual(new byte[] { 255, 255, 255, 255, 255, 255, 255, 127 }, intData);
#endif
}
#nullable disable
[Test]
public void FailedCasting()
{
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(true); }, "Can not convert Boolean to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1); }, "Can not convert Integer to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1.1); }, "Can not convert Float to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1.1m); }, "Can not convert Float to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(TimeSpan.Zero); }, "Can not convert TimeSpan to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)JValue.CreateNull(); }, "Can not convert Null to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(Guid.NewGuid()); }, "Can not convert Guid to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(true); }, "Can not convert Boolean to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1); }, "Can not convert Integer to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1.1); }, "Can not convert Float to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1.1m); }, "Can not convert Float to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(TimeSpan.Zero); }, "Can not convert TimeSpan to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(Guid.NewGuid()); }, "Can not convert Guid to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(DateTime.Now); }, "Can not convert Date to Uri.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(DateTimeOffset.Now); }, "Can not convert Date to Uri.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(true); }, "Can not convert Boolean to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1); }, "Can not convert Integer to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1.1); }, "Can not convert Float to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1.1m); }, "Can not convert Float to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)JValue.CreateNull(); }, "Can not convert Null to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(Guid.NewGuid()); }, "Can not convert Guid to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(DateTime.Now); }, "Can not convert Date to TimeSpan.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(DateTimeOffset.Now); }, "Can not convert Date to TimeSpan.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(true); }, "Can not convert Boolean to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1); }, "Can not convert Integer to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1.1); }, "Can not convert Float to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1.1m); }, "Can not convert Float to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)JValue.CreateNull(); }, "Can not convert Null to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(DateTime.Now); }, "Can not convert Date to Guid.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(DateTimeOffset.Now); }, "Can not convert Date to Guid.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(TimeSpan.FromMinutes(1)); }, "Can not convert TimeSpan to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to Guid.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTimeOffset)new JValue(true); }, "Can not convert Boolean to DateTimeOffset.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(true); }, "Can not convert Boolean to Uri.");
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(new Uri("http://www.google.com"))).ToObject<BigInteger>(); }, "Can not convert Uri to BigInteger.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (JValue.CreateNull()).ToObject<BigInteger>(); }, "Can not convert Null to BigInteger.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger>(); }, "Can not convert Guid to BigInteger.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger?>(); }, "Can not convert Guid to BigInteger.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (sbyte?)new JValue(DateTime.Now); }, "Can not convert Date to SByte.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (sbyte)new JValue(DateTime.Now); }, "Can not convert Date to SByte.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue("Ordinal1")).ToObject<StringComparison>(); }, "Could not convert 'Ordinal1' to StringComparison.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue("Ordinal1")).ToObject<StringComparison?>(); }, "Could not convert 'Ordinal1' to StringComparison.");
}
[Test]
public void ToObject()
{
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0
Assert.AreEqual((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger))));
Assert.AreEqual((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger?))));
Assert.AreEqual((BigInteger?)null, (JValue.CreateNull().ToObject(typeof(BigInteger?))));
#endif
Assert.AreEqual((ushort)1, (new JValue(1).ToObject(typeof(ushort))));
Assert.AreEqual((ushort)1, (new JValue(1).ToObject(typeof(ushort?))));
Assert.AreEqual((uint)1L, (new JValue(1).ToObject(typeof(uint))));
Assert.AreEqual((uint)1L, (new JValue(1).ToObject(typeof(uint?))));
Assert.AreEqual((ulong)1L, (new JValue(1).ToObject(typeof(ulong))));
Assert.AreEqual((ulong)1L, (new JValue(1).ToObject(typeof(ulong?))));
Assert.AreEqual((sbyte)1L, (new JValue(1).ToObject(typeof(sbyte))));
Assert.AreEqual((sbyte)1L, (new JValue(1).ToObject(typeof(sbyte?))));
Assert.AreEqual(null, (JValue.CreateNull().ToObject(typeof(sbyte?))));
Assert.AreEqual((byte)1L, (new JValue(1).ToObject(typeof(byte))));
Assert.AreEqual((byte)1L, (new JValue(1).ToObject(typeof(byte?))));
Assert.AreEqual((short)1L, (new JValue(1).ToObject(typeof(short))));
Assert.AreEqual((short)1L, (new JValue(1).ToObject(typeof(short?))));
Assert.AreEqual(1, (new JValue(1).ToObject(typeof(int))));
Assert.AreEqual(1, (new JValue(1).ToObject(typeof(int?))));
Assert.AreEqual(1L, (new JValue(1).ToObject(typeof(long))));
Assert.AreEqual(1L, (new JValue(1).ToObject(typeof(long?))));
Assert.AreEqual((float)1, (new JValue(1.0).ToObject(typeof(float))));
Assert.AreEqual((float)1, (new JValue(1.0).ToObject(typeof(float?))));
Assert.AreEqual((double)1, (new JValue(1.0).ToObject(typeof(double))));
Assert.AreEqual((double)1, (new JValue(1.0).ToObject(typeof(double?))));
Assert.AreEqual(1m, (new JValue(1).ToObject(typeof(decimal))));
Assert.AreEqual(1m, (new JValue(1).ToObject(typeof(decimal?))));
Assert.AreEqual(true, (new JValue(true).ToObject(typeof(bool))));
Assert.AreEqual(true, (new JValue(true).ToObject(typeof(bool?))));
Assert.AreEqual('b', (new JValue('b').ToObject(typeof(char))));
Assert.AreEqual('b', (new JValue('b').ToObject(typeof(char?))));
Assert.AreEqual(TimeSpan.MaxValue, (new JValue(TimeSpan.MaxValue).ToObject(typeof(TimeSpan))));
Assert.AreEqual(TimeSpan.MaxValue, (new JValue(TimeSpan.MaxValue).ToObject(typeof(TimeSpan?))));
Assert.AreEqual(DateTime.MaxValue, (new JValue(DateTime.MaxValue).ToObject(typeof(DateTime))));
Assert.AreEqual(DateTime.MaxValue, (new JValue(DateTime.MaxValue).ToObject(typeof(DateTime?))));
#if !NET20
Assert.AreEqual(DateTimeOffset.MaxValue, (new JValue(DateTimeOffset.MaxValue).ToObject(typeof(DateTimeOffset))));
Assert.AreEqual(DateTimeOffset.MaxValue, (new JValue(DateTimeOffset.MaxValue).ToObject(typeof(DateTimeOffset?))));
#endif
Assert.AreEqual("b", (new JValue("b").ToObject(typeof(string))));
Assert.AreEqual(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C"), (new JValue(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C")).ToObject(typeof(Guid))));
Assert.AreEqual(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C"), (new JValue(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C")).ToObject(typeof(Guid?))));
Assert.AreEqual(new Uri("http://www.google.com/"), (new JValue(new Uri("http://www.google.com/")).ToObject(typeof(Uri))));
Assert.AreEqual(StringComparison.Ordinal, (new JValue("Ordinal").ToObject(typeof(StringComparison))));
Assert.AreEqual(StringComparison.Ordinal, (new JValue("Ordinal").ToObject(typeof(StringComparison?))));
Assert.AreEqual(null, (JValue.CreateNull().ToObject(typeof(StringComparison?))));
}
#nullable enable
[Test]
public void ImplicitCastingTo()
{
Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTime(2000, 12, 20)), (JValue)new DateTime(2000, 12, 20)));
#if !NET20
Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)), (JValue)new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)));
Assert.IsTrue(JToken.DeepEquals(new JValue((DateTimeOffset?)null), (JValue)(DateTimeOffset?)null));
#endif
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0
// had to remove implicit casting to avoid user reference to System.Numerics.dll
Assert.IsTrue(JToken.DeepEquals(new JValue(new BigInteger(1)), new JValue(new BigInteger(1))));
Assert.IsTrue(JToken.DeepEquals(new JValue((BigInteger?)null), new JValue((BigInteger?)null)));
#endif
Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)true));
Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)true));
Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)(bool?)true));
Assert.IsTrue(JToken.DeepEquals(new JValue((bool?)null), (JValue)(bool?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(10), (JValue)10));
Assert.IsTrue(JToken.DeepEquals(new JValue((long?)null), (JValue)(long?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(long.MaxValue), (JValue)long.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue((int?)null), (JValue)(int?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((short?)null), (JValue)(short?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((double?)null), (JValue)(double?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((uint?)null), (JValue)(uint?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((decimal?)null), (JValue)(decimal?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((ulong?)null), (JValue)(ulong?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((sbyte?)null), (JValue)(sbyte?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((sbyte)1), (JValue)(sbyte)1));
Assert.IsTrue(JToken.DeepEquals(new JValue((byte?)null), (JValue)(byte?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((byte)1), (JValue)(byte)1));
Assert.IsTrue(JToken.DeepEquals(new JValue((ushort?)null), (JValue)(ushort?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(short.MaxValue), (JValue)short.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(ushort.MaxValue), (JValue)ushort.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(11.1f), (JValue)11.1f));
Assert.IsTrue(JToken.DeepEquals(new JValue(float.MinValue), (JValue)float.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(double.MinValue), (JValue)double.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(uint.MaxValue), (JValue)uint.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MaxValue), (JValue)ulong.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MinValue), (JValue)ulong.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue((string?)null), (JValue)(string?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)decimal.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)(decimal?)decimal.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MinValue), (JValue)decimal.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(float.MaxValue), (JValue)(float?)float.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(double.MaxValue), (JValue)(double?)double.MaxValue));
Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(double?)null));
Assert.IsFalse(JToken.DeepEquals(new JValue(true), (JValue)(bool?)null));
Assert.IsFalse(JToken.DeepEquals(JValue.CreateNull(), (JValue?)(object?)null));
byte[] emptyData = new byte[0];
Assert.IsTrue(JToken.DeepEquals(new JValue(emptyData), (JValue)emptyData));
Assert.IsFalse(JToken.DeepEquals(new JValue(emptyData), (JValue)new byte[1]));
Assert.IsTrue(JToken.DeepEquals(new JValue(Encoding.UTF8.GetBytes("Hi")), (JValue)Encoding.UTF8.GetBytes("Hi")));
Assert.IsTrue(JToken.DeepEquals(new JValue(TimeSpan.FromMinutes(1)), (JValue)TimeSpan.FromMinutes(1)));
Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(TimeSpan?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(TimeSpan.FromMinutes(1)), (JValue)(TimeSpan?)TimeSpan.FromMinutes(1)));
Assert.IsTrue(JToken.DeepEquals(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")), (JValue)new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")));
Assert.IsTrue(JToken.DeepEquals(new JValue(new Uri("http://www.google.com")), (JValue)new Uri("http://www.google.com")));
Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(Uri?)null));
Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(Guid?)null));
}
#nullable disable
[Test]
public void Root()
{
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
Assert.AreEqual(a, a.Root);
Assert.AreEqual(a, a[0].Root);
Assert.AreEqual(a, ((JArray)a[2])[0].Root);
}
[Test]
public void Remove()
{
JToken t;
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
a[0].Remove();
Assert.AreEqual(6, (int)a[0]);
a[1].Remove();
Assert.AreEqual(6, (int)a[0]);
Assert.IsTrue(JToken.DeepEquals(new JArray(9, 10), a[1]));
Assert.AreEqual(2, a.Count());
t = a[1];
t.Remove();
Assert.AreEqual(6, (int)a[0]);
Assert.IsNull(t.Next);
Assert.IsNull(t.Previous);
Assert.IsNull(t.Parent);
t = a[0];
t.Remove();
Assert.AreEqual(0, a.Count());
Assert.IsNull(t.Next);
Assert.IsNull(t.Previous);
Assert.IsNull(t.Parent);
}
[Test]
public void AfterSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken t = a[1];
List<JToken> afterTokens = t.AfterSelf().ToList();
Assert.AreEqual(2, afterTokens.Count);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2), afterTokens[0]));
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), afterTokens[1]));
}
[Test]
public void BeforeSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken t = a[2];
List<JToken> beforeTokens = t.BeforeSelf().ToList();
Assert.AreEqual(2, beforeTokens.Count);
Assert.IsTrue(JToken.DeepEquals(new JValue(5), beforeTokens[0]));
Assert.IsTrue(JToken.DeepEquals(new JArray(1), beforeTokens[1]));
}
[Test]
public void HasValues()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
Assert.IsTrue(a.HasValues);
}
[Test]
public void Ancestors()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken t = a[1][0];
List<JToken> ancestors = t.Ancestors().ToList();
Assert.AreEqual(2, ancestors.Count());
Assert.AreEqual(a[1], ancestors[0]);
Assert.AreEqual(a, ancestors[1]);
}
[Test]
public void AncestorsAndSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken t = a[1][0];
List<JToken> ancestors = t.AncestorsAndSelf().ToList();
Assert.AreEqual(3, ancestors.Count());
Assert.AreEqual(t, ancestors[0]);
Assert.AreEqual(a[1], ancestors[1]);
Assert.AreEqual(a, ancestors[2]);
}
[Test]
public void AncestorsAndSelf_Many()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JObject o = new JObject
{
{ "prop1", "value1" }
};
JToken t1 = a[1][0];
JToken t2 = o["prop1"];
List<JToken> source = new List<JToken> { t1, t2 };
List<JToken> ancestors = source.AncestorsAndSelf().ToList();
Assert.AreEqual(6, ancestors.Count());
Assert.AreEqual(t1, ancestors[0]);
Assert.AreEqual(a[1], ancestors[1]);
Assert.AreEqual(a, ancestors[2]);
Assert.AreEqual(t2, ancestors[3]);
Assert.AreEqual(o.Property("prop1"), ancestors[4]);
Assert.AreEqual(o, ancestors[5]);
}
[Test]
public void Ancestors_Many()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JObject o = new JObject
{
{ "prop1", "value1" }
};
JToken t1 = a[1][0];
JToken t2 = o["prop1"];
List<JToken> source = new List<JToken> { t1, t2 };
List<JToken> ancestors = source.Ancestors().ToList();
Assert.AreEqual(4, ancestors.Count());
Assert.AreEqual(a[1], ancestors[0]);
Assert.AreEqual(a, ancestors[1]);
Assert.AreEqual(o.Property("prop1"), ancestors[2]);
Assert.AreEqual(o, ancestors[3]);
}
[Test]
public void Descendants()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
List<JToken> descendants = a.Descendants().ToList();
Assert.AreEqual(10, descendants.Count());
Assert.AreEqual(5, (int)descendants[0]);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendants[descendants.Count - 4]));
Assert.AreEqual(1, (int)descendants[descendants.Count - 3]);
Assert.AreEqual(2, (int)descendants[descendants.Count - 2]);
Assert.AreEqual(3, (int)descendants[descendants.Count - 1]);
}
[Test]
public void Descendants_Many()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JObject o = new JObject
{
{ "prop1", "value1" }
};
List<JContainer> source = new List<JContainer> { a, o };
List<JToken> descendants = source.Descendants().ToList();
Assert.AreEqual(12, descendants.Count());
Assert.AreEqual(5, (int)descendants[0]);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendants[descendants.Count - 6]));
Assert.AreEqual(1, (int)descendants[descendants.Count - 5]);
Assert.AreEqual(2, (int)descendants[descendants.Count - 4]);
Assert.AreEqual(3, (int)descendants[descendants.Count - 3]);
Assert.AreEqual(o.Property("prop1"), descendants[descendants.Count - 2]);
Assert.AreEqual(o["prop1"], descendants[descendants.Count - 1]);
}
[Test]
public void DescendantsAndSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
List<JToken> descendantsAndSelf = a.DescendantsAndSelf().ToList();
Assert.AreEqual(11, descendantsAndSelf.Count());
Assert.AreEqual(a, descendantsAndSelf[0]);
Assert.AreEqual(5, (int)descendantsAndSelf[1]);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendantsAndSelf[descendantsAndSelf.Count - 4]));
Assert.AreEqual(1, (int)descendantsAndSelf[descendantsAndSelf.Count - 3]);
Assert.AreEqual(2, (int)descendantsAndSelf[descendantsAndSelf.Count - 2]);
Assert.AreEqual(3, (int)descendantsAndSelf[descendantsAndSelf.Count - 1]);
}
[Test]
public void DescendantsAndSelf_Many()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JObject o = new JObject
{
{ "prop1", "value1" }
};
List<JContainer> source = new List<JContainer> { a, o };
List<JToken> descendantsAndSelf = source.DescendantsAndSelf().ToList();
Assert.AreEqual(14, descendantsAndSelf.Count());
Assert.AreEqual(a, descendantsAndSelf[0]);
Assert.AreEqual(5, (int)descendantsAndSelf[1]);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendantsAndSelf[descendantsAndSelf.Count - 7]));
Assert.AreEqual(1, (int)descendantsAndSelf[descendantsAndSelf.Count - 6]);
Assert.AreEqual(2, (int)descendantsAndSelf[descendantsAndSelf.Count - 5]);
Assert.AreEqual(3, (int)descendantsAndSelf[descendantsAndSelf.Count - 4]);
Assert.AreEqual(o, descendantsAndSelf[descendantsAndSelf.Count - 3]);
Assert.AreEqual(o.Property("prop1"), descendantsAndSelf[descendantsAndSelf.Count - 2]);
Assert.AreEqual(o["prop1"], descendantsAndSelf[descendantsAndSelf.Count - 1]);
}
[Test]
public void CreateWriter()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JsonWriter writer = a.CreateWriter();
Assert.IsNotNull(writer);
Assert.AreEqual(4, a.Count());
writer.WriteValue("String");
Assert.AreEqual(5, a.Count());
Assert.AreEqual("String", (string)a[4]);
writer.WriteStartObject();
writer.WritePropertyName("Property");
writer.WriteValue("PropertyValue");
writer.WriteEnd();
Assert.AreEqual(6, a.Count());
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("Property", "PropertyValue")), a[5]));
}
[Test]
public void AddFirst()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a.AddFirst("First");
Assert.AreEqual("First", (string)a[0]);
Assert.AreEqual(a, a[0].Parent);
Assert.AreEqual(a[1], a[0].Next);
Assert.AreEqual(5, a.Count());
a.AddFirst("NewFirst");
Assert.AreEqual("NewFirst", (string)a[0]);
Assert.AreEqual(a, a[0].Parent);
Assert.AreEqual(a[1], a[0].Next);
Assert.AreEqual(6, a.Count());
Assert.AreEqual(a[0], a[0].Next.Previous);
}
[Test]
public void RemoveAll()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken first = a.First;
Assert.AreEqual(5, (int)first);
a.RemoveAll();
Assert.AreEqual(0, a.Count());
Assert.IsNull(first.Parent);
Assert.IsNull(first.Next);
}
[Test]
public void AddPropertyToArray()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JArray a = new JArray();
a.Add(new JProperty("PropertyName"));
}, "Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray.");
}
[Test]
public void AddValueToObject()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
o.Add(5);
}, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
public void Replace()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a[0].Replace(new JValue(int.MaxValue));
Assert.AreEqual(int.MaxValue, (int)a[0]);
Assert.AreEqual(4, a.Count());
a[1][0].Replace(new JValue("Test"));
Assert.AreEqual("Test", (string)a[1][0]);
a[2].Replace(new JValue(int.MaxValue));
Assert.AreEqual(int.MaxValue, (int)a[2]);
Assert.AreEqual(4, a.Count());
Assert.IsTrue(JToken.DeepEquals(new JArray(int.MaxValue, new JArray("Test"), int.MaxValue, new JArray(1, 2, 3)), a));
}
[Test]
public void ToStringWithConverters()
{
JArray a =
new JArray(
new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc))
);
string json = a.ToString(Formatting.Indented, new IsoDateTimeConverter());
StringAssert.AreEqual(@"[
""2009-02-15T00:00:00Z""
]", json);
json = JsonConvert.SerializeObject(a, new IsoDateTimeConverter());
Assert.AreEqual(@"[""2009-02-15T00:00:00Z""]", json);
}
[Test]
public void ToStringWithNoIndenting()
{
JArray a =
new JArray(
new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc))
);
string json = a.ToString(Formatting.None, new IsoDateTimeConverter());
Assert.AreEqual(@"[""2009-02-15T00:00:00Z""]", json);
}
[Test]
public void AddAfterSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a[1].AddAfterSelf("pie");
Assert.AreEqual(5, (int)a[0]);
Assert.AreEqual(1, a[1].Count());
Assert.AreEqual("pie", (string)a[2]);
Assert.AreEqual(5, a.Count());
a[4].AddAfterSelf("lastpie");
Assert.AreEqual("lastpie", (string)a[5]);
Assert.AreEqual("lastpie", (string)a.Last);
}
[Test]
public void AddBeforeSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a[1].AddBeforeSelf("pie");
Assert.AreEqual(5, (int)a[0]);
Assert.AreEqual("pie", (string)a[1]);
Assert.AreEqual(a, a[1].Parent);
Assert.AreEqual(a[2], a[1].Next);
Assert.AreEqual(5, a.Count());
a[0].AddBeforeSelf("firstpie");
Assert.AreEqual("firstpie", (string)a[0]);
Assert.AreEqual(5, (int)a[1]);
Assert.AreEqual("pie", (string)a[2]);
Assert.AreEqual(a, a[0].Parent);
Assert.AreEqual(a[1], a[0].Next);
Assert.AreEqual(6, a.Count());
a.Last.AddBeforeSelf("secondlastpie");
Assert.AreEqual("secondlastpie", (string)a[5]);
Assert.AreEqual(7, a.Count());
}
[Test]
public void DeepClone()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3),
new JObject(
new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))),
new JProperty("Second", 1),
new JProperty("Third", null),
new JProperty("Fourth", new JConstructor("Date", 12345)),
new JProperty("Fifth", double.PositiveInfinity),
new JProperty("Sixth", double.NaN)
)
);
JArray a2 = (JArray)a.DeepClone();
StringAssert.AreEqual(@"[
5,
[
1
],
[
1,
2
],
[
1,
2,
3
],
{
""First"": ""SGk="",
""Second"": 1,
""Third"": null,
""Fourth"": new Date(
12345
),
""Fifth"": ""Infinity"",
""Sixth"": ""NaN""
}
]", a2.ToString(Formatting.Indented));
Assert.IsTrue(a.DeepEquals(a2));
}
#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0
[Test]
public void Clone()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3),
new JObject(
new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))),
new JProperty("Second", 1),
new JProperty("Third", null),
new JProperty("Fourth", new JConstructor("Date", 12345)),
new JProperty("Fifth", double.PositiveInfinity),
new JProperty("Sixth", double.NaN)
)
);
ICloneable c = a;
JArray a2 = (JArray)c.Clone();
Assert.IsTrue(a.DeepEquals(a2));
}
#endif
[Test]
public void DoubleDeepEquals()
{
JArray a =
new JArray(
double.NaN,
double.PositiveInfinity,
double.NegativeInfinity
);
JArray a2 = (JArray)a.DeepClone();
Assert.IsTrue(a.DeepEquals(a2));
double d = 1 + 0.1 + 0.1 + 0.1;
JValue v1 = new JValue(d);
JValue v2 = new JValue(1.3);
Assert.IsTrue(v1.DeepEquals(v2));
}
[Test]
public void ParseAdditionalContent()
{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string json = @"[
""Small"",
""Medium"",
""Large""
],";
JToken.Parse(json);
}, "Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 1.");
}
[Test]
public void Path()
{
JObject o =
new JObject(
new JProperty("Test1", new JArray(1, 2, 3)),
new JProperty("Test2", "Test2Value"),
new JProperty("Test3", new JObject(new JProperty("Test1", new JArray(1, new JObject(new JProperty("Test1", 1)), 3)))),
new JProperty("Test4", new JConstructor("Date", new JArray(1, 2, 3)))
);
JToken t = o.SelectToken("Test1[0]");
Assert.AreEqual("Test1[0]", t.Path);
t = o.SelectToken("Test2");
Assert.AreEqual("Test2", t.Path);
t = o.SelectToken("");
Assert.AreEqual("", t.Path);
t = o.SelectToken("Test4[0][0]");
Assert.AreEqual("Test4[0][0]", t.Path);
t = o.SelectToken("Test4[0]");
Assert.AreEqual("Test4[0]", t.Path);
t = t.DeepClone();
Assert.AreEqual("", t.Path);
t = o.SelectToken("Test3.Test1[1].Test1");
Assert.AreEqual("Test3.Test1[1].Test1", t.Path);
JArray a = new JArray(1);
Assert.AreEqual("", a.Path);
Assert.AreEqual("[0]", a[0].Path);
}
[Test]
public void Parse_NoComments()
{
string json = "{'prop':[1,2/*comment*/,3]}";
JToken o = JToken.Parse(json, new JsonLoadSettings
{
CommentHandling = CommentHandling.Ignore
});
Assert.AreEqual(3, o["prop"].Count());
Assert.AreEqual(1, (int)o["prop"][0]);
Assert.AreEqual(2, (int)o["prop"][1]);
Assert.AreEqual(3, (int)o["prop"][2]);
}
[Test]
public void Parse_ExcessiveContentJustComments()
{
string json = @"{'prop':[1,2,3]}/*comment*/
//Another comment.";
JToken o = JToken.Parse(json);
Assert.AreEqual(3, o["prop"].Count());
Assert.AreEqual(1, (int)o["prop"][0]);
Assert.AreEqual(2, (int)o["prop"][1]);
Assert.AreEqual(3, (int)o["prop"][2]);
}
[Test]
public void Parse_ExcessiveContent()
{
string json = @"{'prop':[1,2,3]}/*comment*/
//Another comment.
{}";
ExceptionAssert.Throws<JsonReaderException>(() => JToken.Parse(json),
"Additional text encountered after finished reading JSON content: {. Path '', line 3, position 0.");
}
#if DNXCORE50
[Theory]
#endif
[TestCase("test customer", "['test customer']")]
[TestCase("test customer's", "['test customer\\'s']")]
[TestCase("testcustomer's", "['testcustomer\\'s']")]
[TestCase("testcustomer", "testcustomer")]
[TestCase("test.customer", "['test.customer']")]
[TestCase("test\rcustomer", "['test\\rcustomer']")]
[TestCase("test\ncustomer", "['test\\ncustomer']")]
[TestCase("test\tcustomer", "['test\\tcustomer']")]
[TestCase("test\bcustomer", "['test\\bcustomer']")]
[TestCase("test\fcustomer", "['test\\fcustomer']")]
[TestCase("test/customer", "['test/customer']")]
[TestCase("test\\customer", "['test\\\\customer']")]
[TestCase("\"test\"customer", "['\"test\"customer']")]
public void PathEscapingTest(string name, string expectedPath)
{
JValue v = new JValue("12345");
JObject o = new JObject
{
[name] = v
};
string path = v.Path;
Assert.AreEqual(expectedPath, path);
JToken token = o.SelectToken(path);
Assert.AreEqual(v, token);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLoption = Interop.Http.CURLoption;
using CurlProtocols = Interop.Http.CurlProtocols;
using CURLProxyType = Interop.Http.curl_proxytype;
using SafeCurlHandle = Interop.Http.SafeCurlHandle;
using SafeCurlSListHandle = Interop.Http.SafeCurlSListHandle;
using SafeCallbackHandle = Interop.Http.SafeCallbackHandle;
using SeekCallback = Interop.Http.SeekCallback;
using ReadWriteCallback = Interop.Http.ReadWriteCallback;
using ReadWriteFunction = Interop.Http.ReadWriteFunction;
using SslCtxCallback = Interop.Http.SslCtxCallback;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
private sealed class EasyRequest : TaskCompletionSource<HttpResponseMessage>
{
internal readonly CurlHandler _handler;
internal readonly HttpRequestMessage _requestMessage;
internal readonly CurlResponseMessage _responseMessage;
internal readonly CancellationToken _cancellationToken;
internal readonly HttpContentAsyncStream _requestContentStream;
internal SafeCurlHandle _easyHandle;
private SafeCurlSListHandle _requestHeaders;
internal NetworkCredential _networkCredential;
internal MultiAgent _associatedMultiAgent;
internal SendTransferState _sendTransferState;
internal bool _isRedirect = false;
internal Uri _targetUri;
private SafeCallbackHandle _callbackHandle;
public EasyRequest(CurlHandler handler, HttpRequestMessage requestMessage, CancellationToken cancellationToken) :
base(TaskCreationOptions.RunContinuationsAsynchronously)
{
_handler = handler;
_requestMessage = requestMessage;
_cancellationToken = cancellationToken;
if (requestMessage.Content != null)
{
_requestContentStream = new HttpContentAsyncStream(requestMessage.Content);
}
_responseMessage = new CurlResponseMessage(this);
_targetUri = requestMessage.RequestUri;
}
/// <summary>
/// Initialize the underlying libcurl support for this EasyRequest.
/// This is separated out of the constructor so that we can take into account
/// any additional configuration needed based on the request message
/// after the EasyRequest is configured and so that error handling
/// can be better handled in the caller.
/// </summary>
internal void InitializeCurl()
{
// Create the underlying easy handle
SafeCurlHandle easyHandle = Interop.Http.EasyCreate();
if (easyHandle.IsInvalid)
{
throw new OutOfMemoryException();
}
_easyHandle = easyHandle;
// Configure the handle
SetUrl();
SetDebugging();
SetMultithreading();
SetRedirection();
SetVerb();
SetVersion();
SetDecompressionOptions();
SetProxyOptions(_requestMessage.RequestUri);
SetCredentialsOptions(_handler.GetNetworkCredentials(_handler._serverCredentials, _requestMessage.RequestUri));
SetCookieOption(_requestMessage.RequestUri);
SetRequestHeaders();
SetSslOptions();
}
public void EnsureResponseMessagePublished()
{
bool result = TrySetResult(_responseMessage);
Debug.Assert(result || Task.Status == TaskStatus.RanToCompletion,
"If the task was already completed, it should have been completed succesfully; " +
"we shouldn't be completing as successful after already completing as failed.");
}
public void FailRequest(Exception error)
{
Debug.Assert(error != null, "Expected non-null exception");
var oce = error as OperationCanceledException;
if (oce != null)
{
TrySetCanceled(oce.CancellationToken);
}
else
{
if (error is IOException || error is CurlException || error == null)
{
error = CreateHttpRequestException(error);
}
TrySetException(error);
}
// There's not much we can reasonably assert here about the result of TrySet*.
// It's possible that the task wasn't yet completed (e.g. a failure while initiating the request),
// it's possible that the task was already completed as success (e.g. a failure sending back the response),
// and it's possible that the task was already completed as failure (e.g. we handled the exception and
// faulted the task, but then tried to fault it again while finishing processing in the main loop).
// Make sure the exception is available on the response stream so that it's propagated
// from any attempts to read from the stream.
_responseMessage.ResponseStream.SignalComplete(error);
}
public void Cleanup() // not called Dispose because the request may still be in use after it's cleaned up
{
_responseMessage.ResponseStream.SignalComplete(); // No more callbacks so no more data
// Don't dispose of the ResponseMessage.ResponseStream as it may still be in use
// by code reading data stored in the stream.
// Dispose of the input content stream if there was one. Nothing should be using it any more.
if (_requestContentStream != null)
_requestContentStream.Dispose();
// Dispose of the underlying easy handle. We're no longer processing it.
if (_easyHandle != null)
_easyHandle.Dispose();
// Dispose of the request headers if we had any. We had to keep this handle
// alive as long as the easy handle was using it. We didn't need to do any
// ref counting on the safe handle, though, as the only processing happens
// in Process, which ensures the handle will be rooted while libcurl is
// doing any processing that assumes it's valid.
if (_requestHeaders != null)
_requestHeaders.Dispose();
if (_callbackHandle != null)
_callbackHandle.Dispose();
}
private void SetUrl()
{
VerboseTrace(_requestMessage.RequestUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_URL, _requestMessage.RequestUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_PROTOCOLS, (long)(CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS));
}
[Conditional(VerboseDebuggingConditional)]
private void SetDebugging()
{
SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L);
// In addition to CURLOPT_VERBOSE, CURLOPT_DEBUGFUNCTION could be used here in the future to:
// - Route the verbose output to somewhere other than stderr
// - Dump additional data related to CURLINFO_DATA_* and CURLINFO_SSL_DATA_*
}
private void SetMultithreading()
{
SetCurlOption(CURLoption.CURLOPT_NOSIGNAL, 1L);
}
private void SetRedirection()
{
if (!_handler._automaticRedirection)
{
return;
}
VerboseTrace(_handler._maxAutomaticRedirections.ToString());
SetCurlOption(CURLoption.CURLOPT_FOLLOWLOCATION, 1L);
CurlProtocols redirectProtocols = string.Equals(_requestMessage.RequestUri.Scheme, UriSchemeHttps, StringComparison.OrdinalIgnoreCase) ?
CurlProtocols.CURLPROTO_HTTPS : // redirect only to another https
CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS; // redirect to http or to https
SetCurlOption(CURLoption.CURLOPT_REDIR_PROTOCOLS, (long)redirectProtocols);
SetCurlOption(CURLoption.CURLOPT_MAXREDIRS, _handler._maxAutomaticRedirections);
}
private void SetVerb()
{
VerboseTrace(_requestMessage.Method.Method);
if (_requestMessage.Method == HttpMethod.Put)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
if (_requestMessage.Content == null)
{
SetCurlOption(CURLoption.CURLOPT_INFILESIZE, 0L);
}
}
else if (_requestMessage.Method == HttpMethod.Head)
{
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else if (_requestMessage.Method == HttpMethod.Post)
{
SetCurlOption(CURLoption.CURLOPT_POST, 1L);
if (_requestMessage.Content == null)
{
SetCurlOption(CURLoption.CURLOPT_POSTFIELDSIZE, 0L);
SetCurlOption(CURLoption.CURLOPT_COPYPOSTFIELDS, string.Empty);
}
}
else if (_requestMessage.Method == HttpMethod.Trace)
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
if (_requestMessage.Content != null)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
}
}
}
private void SetVersion()
{
Version v = _requestMessage.Version;
if (v != null)
{
// Try to use the requested version, if a known version was explicitly requested.
// If an unknown version was requested, we simply use libcurl's default.
var curlVersion =
(v.Major == 1 && v.Minor == 1) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_1 :
(v.Major == 1 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_0 :
(v.Major == 2 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_2_0 :
Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE;
if (curlVersion != Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE)
{
// Ask libcurl to use the specified version if possible.
CURLcode c = Interop.Http.EasySetOptionLong(_easyHandle, CURLoption.CURLOPT_HTTP_VERSION, (long)curlVersion);
if (c == CURLcode.CURLE_OK)
{
// Success. The requested version will be used.
VerboseTrace("Set HTTP version to " + v);
}
else if (c == CURLcode.CURLE_UNSUPPORTED_PROTOCOL)
{
// The requested version is unsupported. Fall back to using the default version chosen by libcurl.
VerboseTrace("Unsupported protocol.");
}
else
{
// Some other error. Fail.
ThrowIfCURLEError(c);
}
}
}
}
private void SetDecompressionOptions()
{
if (!_handler.SupportsAutomaticDecompression)
{
return;
}
DecompressionMethods autoDecompression = _handler.AutomaticDecompression;
bool gzip = (autoDecompression & DecompressionMethods.GZip) != 0;
bool deflate = (autoDecompression & DecompressionMethods.Deflate) != 0;
if (gzip || deflate)
{
string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate :
gzip ? EncodingNameGzip :
EncodingNameDeflate;
SetCurlOption(CURLoption.CURLOPT_ACCEPT_ENCODING, encoding);
VerboseTrace(encoding);
}
}
internal void SetProxyOptions(Uri requestUri)
{
if (_handler._proxyPolicy == ProxyUsePolicy.DoNotUseProxy)
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
VerboseTrace("No proxy");
return;
}
if ((_handler._proxyPolicy == ProxyUsePolicy.UseDefaultProxy) ||
(_handler.Proxy == null))
{
VerboseTrace("Default proxy");
return;
}
Debug.Assert(_handler.Proxy != null, "proxy is null");
Debug.Assert(_handler._proxyPolicy == ProxyUsePolicy.UseCustomProxy, "_proxyPolicy is not UseCustomProxy");
if (_handler.Proxy.IsBypassed(requestUri))
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
VerboseTrace("Bypassed proxy");
return;
}
var proxyUri = _handler.Proxy.GetProxy(requestUri);
if (proxyUri == null)
{
VerboseTrace("No proxy URI");
return;
}
SetCurlOption(CURLoption.CURLOPT_PROXYTYPE, (long)CURLProxyType.CURLPROXY_HTTP);
SetCurlOption(CURLoption.CURLOPT_PROXY, proxyUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_PROXYPORT, proxyUri.Port);
VerboseTrace("Set proxy: " + proxyUri.ToString());
KeyValuePair<NetworkCredential, CURLAUTH> credentialScheme = GetCredentials(_handler.Proxy.Credentials, _requestMessage.RequestUri);
NetworkCredential credentials = credentialScheme.Key;
if (credentials != null && // no credentials to set
credentials != CredentialCache.DefaultCredentials) // no "default credentials" on Unix; nop just like UseDefaultCredentials
{
if (string.IsNullOrEmpty(credentials.UserName))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "UserName");
}
string credentialText = string.IsNullOrEmpty(credentials.Domain) ?
string.Format("{0}:{1}", credentials.UserName, credentials.Password) :
string.Format("{2}\\{0}:{1}", credentials.UserName, credentials.Password, credentials.Domain);
SetCurlOption(CURLoption.CURLOPT_PROXYUSERPWD, credentialText);
VerboseTrace("Set proxy credentials");
}
}
internal void SetCredentialsOptions(KeyValuePair<NetworkCredential, CURLAUTH> credentialSchemePair)
{
if (credentialSchemePair.Key == null)
{
_networkCredential = null;
return;
}
NetworkCredential credentials = credentialSchemePair.Key;
CURLAUTH authScheme = credentialSchemePair.Value;
string userName = string.IsNullOrEmpty(credentials.Domain) ?
credentials.UserName :
string.Format("{0}\\{1}", credentials.Domain, credentials.UserName);
SetCurlOption(CURLoption.CURLOPT_USERNAME, userName);
SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, (long)authScheme);
if (credentials.Password != null)
{
SetCurlOption(CURLoption.CURLOPT_PASSWORD, credentials.Password);
}
_networkCredential = credentials;
VerboseTrace("Set credentials options");
}
internal void SetCookieOption(Uri uri)
{
if (!_handler._useCookie)
{
return;
}
string cookieValues = _handler.CookieContainer.GetCookieHeader(uri);
if (!string.IsNullOrEmpty(cookieValues))
{
SetCurlOption(CURLoption.CURLOPT_COOKIE, cookieValues);
VerboseTrace("Set cookies");
}
}
internal void SetRequestHeaders()
{
HttpContentHeaders contentHeaders = null;
if (_requestMessage.Content != null)
{
SetChunkedModeForSend(_requestMessage);
// TODO: Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (_requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = _requestMessage.Content.Headers.ContentLength.Value;
_requestMessage.Content.Headers.ContentLength = null;
_requestMessage.Content.Headers.ContentLength = contentLength;
}
contentHeaders = _requestMessage.Content.Headers;
}
var slist = new SafeCurlSListHandle();
// Add request and content request headers
if (_requestMessage.Headers != null)
{
AddRequestHeaders(_requestMessage.Headers, slist);
}
if (contentHeaders != null)
{
AddRequestHeaders(contentHeaders, slist);
if (contentHeaders.ContentType == null)
{
if (!Interop.Http.SListAppend(slist, NoContentType))
{
throw CreateHttpRequestException();
}
}
}
// Since libcurl always adds a Transfer-Encoding header, we need to explicitly block
// it if caller specifically does not want to set the header
if (_requestMessage.Headers.TransferEncodingChunked.HasValue &&
!_requestMessage.Headers.TransferEncodingChunked.Value)
{
if (!Interop.Http.SListAppend(slist, NoTransferEncoding))
{
throw CreateHttpRequestException();
}
}
if (!slist.IsInvalid)
{
_requestHeaders = slist;
SetCurlOption(CURLoption.CURLOPT_HTTPHEADER, slist);
VerboseTrace("Set headers");
}
else
{
slist.Dispose();
}
}
private void SetSslOptions()
{
// SSL Options should be set regardless of the type of the original request,
// in case an http->https redirection occurs.
//
// While this does slow down the theoretical best path of the request the code
// to decide that we need to register the callback is more complicated than, and
// potentially more expensive than, just always setting the callback.
SslProvider.SetSslOptions(this, _handler.ClientCertificateOptions);
}
internal void SetCurlCallbacks(
IntPtr easyGCHandle,
ReadWriteCallback receiveHeadersCallback,
ReadWriteCallback sendCallback,
SeekCallback seekCallback,
ReadWriteCallback receiveBodyCallback)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
// Add callback for processing headers
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Header,
receiveHeadersCallback,
easyGCHandle,
ref _callbackHandle);
// If we're sending data as part of the request, add callbacks for sending request data
if (_requestMessage.Content != null)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Read,
sendCallback,
easyGCHandle,
ref _callbackHandle);
Interop.Http.RegisterSeekCallback(
_easyHandle,
seekCallback,
easyGCHandle,
ref _callbackHandle);
}
// If we're expecting any data in response, add a callback for receiving body data
if (_requestMessage.Method != HttpMethod.Head)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Write,
receiveBodyCallback,
easyGCHandle,
ref _callbackHandle);
}
}
internal CURLcode SetSslCtxCallback(SslCtxCallback callback, IntPtr userPointer)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
CURLcode result = Interop.Http.RegisterSslCtxCallback(_easyHandle, callback, userPointer, ref _callbackHandle);
return result;
}
private static void AddRequestHeaders(HttpHeaders headers, SafeCurlSListHandle handle)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
{
string headerValue = headers.GetHeaderString(header.Key);
string headerKeyAndValue = string.IsNullOrEmpty(headerValue) ?
header.Key + ";" : // semicolon used by libcurl to denote empty value that should be sent
header.Key + ": " + headerValue;
if (!Interop.Http.SListAppend(handle, headerKeyAndValue))
{
throw CreateHttpRequestException();
}
}
}
internal void SetCurlOption(CURLoption option, string value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionString(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, long value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionLong(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, IntPtr value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, SafeHandle value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
internal sealed class SendTransferState
{
internal readonly byte[] _buffer = new byte[RequestBufferSize]; // PERF TODO: Determine if this should be optimized to start smaller and grow
internal int _offset;
internal int _count;
internal Task<int> _task;
internal void SetTaskOffsetCount(Task<int> task, int offset, int count)
{
Debug.Assert(offset >= 0, "Offset should never be negative");
Debug.Assert(count >= 0, "Count should never be negative");
Debug.Assert(offset <= count, "Offset should never be greater than count");
_task = task;
_offset = offset;
_count = count;
}
}
internal void SetRedirectUri(Uri redirectUri)
{
_targetUri = _requestMessage.RequestUri;
_requestMessage.RequestUri = redirectUri;
}
[Conditional(VerboseDebuggingConditional)]
private void VerboseTrace(string text = null, [CallerMemberName] string memberName = null)
{
CurlHandler.VerboseTrace(text, memberName, easy: this, agent: null);
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Tar
{
internal struct TarHeaderView
{
private readonly byte[] _buffer;
private readonly int _offset;
public readonly Dictionary<string, string> PaxAttributes;
public TarHeaderView(byte[] buffer, int offset, Dictionary<string, string> paxAttributes)
{
_buffer = buffer;
_offset = offset;
PaxAttributes = paxAttributes;
}
public ArraySegment<byte> Field(TarHeader.HeaderField field)
{
return new ArraySegment<byte>(_buffer, _offset + field.Offset, field.Length);
}
public byte this[int i]
{
get { return _buffer[_offset + i]; }
set { _buffer[_offset + i] = value; }
}
public void PutBytes(ArraySegment<byte> bytes, TarHeader.HeaderField field)
{
int i;
for (i = 0; i < bytes.Count && i < field.Length; i++)
{
this[field.Offset + i] = bytes.Array[bytes.Offset + i];
}
PutNul(field.Offset + i, field.Length - i);
}
public bool TryPutString(string str, TarHeader.HeaderField field)
{
if (str == null)
{
PutNul(field);
return true;
}
if (TarCommon.IsASCII(str))
{
if (str.Length <= field.Length)
{
for (int i = 0; i < str.Length; i++)
{
this[field.Offset + i] = (byte)str[i];
}
PutNul(field.Offset + str.Length, field.Length - str.Length);
return true;
}
}
if (field.PaxAttribute != null && PaxAttributes != null)
{
PaxAttributes[field.PaxAttribute] = str;
}
PutNul(field);
return false;
}
public bool TryPutOctal(long value, TarHeader.HeaderField field)
{
if (value >= 0)
{
var str = Convert.ToString(value, 8);
if (str.Length < field.Length)
{
int leadingZeroes =field.Length - str.Length - 1;
for (int i = 0; i < leadingZeroes; i++)
{
this[field.Offset + i] = (byte)'0';
}
for (int i = 0; i < str.Length; i++)
{
this[field.Offset + leadingZeroes + i] = (byte)str[i];
}
this[field.Offset + field.Length - 1] = 0;
return true;
}
}
if (field.PaxAttribute != null && PaxAttributes != null)
{
PaxAttributes[field.PaxAttribute] = value.ToString();
}
PutNul(field);
return false;
}
public bool TryPutTime(DateTime time, TarHeader.HeaderField field)
{
uint nanoseconds = 0;
long unixTime = 0;
if (time.Ticks != 0)
{
unixTime = TarTime.ToUnixTime(time, out nanoseconds);
}
if (TryPutOctal(unixTime, field.WithoutPax) && nanoseconds == 0)
{
return true;
}
if (field.PaxAttribute != null && PaxAttributes != null)
{
PaxAttributes[field.PaxAttribute] = TarTime.ToPaxTime(time);
}
return false;
}
private void PutNul(int offset, int n)
{
for (int i = 0; i < n; i++)
{
this[offset + i] = 0;
}
}
public void PutNul(TarHeader.HeaderField field)
{
PutNul(field.Offset, field.Length);
}
public string GetPaxValue(string paxKey)
{
string paxValue;
if (paxKey != null && PaxAttributes != null && PaxAttributes.TryGetValue(paxKey, out paxValue))
{
return paxValue;
}
return null;
}
public string GetString(TarHeader.HeaderField field)
{
string paxValue = GetPaxValue(field.PaxAttribute);
if (paxValue != null)
{
return paxValue;
}
int i;
for (i = 0; i < field.Length; i++)
{
var b = this[field.Offset + i];
if (b == 0)
{
break;
}
}
// Assume UTF-8 encoding. This may not be correct always, but only PAX rigorously
// defines the encoding of strings.
return TarCommon.UTF8.GetString(_buffer, _offset + field.Offset, i);
}
private static readonly char[] nulAndSpace = new char[] { ' ', '\x00' };
public long GetOctalLong(TarHeader.HeaderField field)
{
string paxValue = GetPaxValue(field.PaxAttribute);
if (paxValue != null)
{
return Convert.ToInt64(paxValue);
}
var firstByte = this[field.Offset];
if ((firstByte & 0x80) != 0)
{
// Tar extension: value is encoded as MSB (ignoring the high bit of the first byte).
if ((firstByte & 0x40) == 0)
{
// The result is positive, so clear the sign bit.
firstByte &= 0x7f;
}
long result = (sbyte)firstByte;
for (int i = 1; i < field.Length; i++)
{
result <<= 8;
result |= this[field.Offset + i];
}
return result;
}
else
{
var str = GetString(field.WithoutPax).Trim(nulAndSpace);
if (str.Length == 0)
{
return 0;
}
return Convert.ToInt64(str, 8);
}
}
public int GetOctal(TarHeader.HeaderField field)
{
long value = GetOctalLong(field);
if ((int)value != value)
{
throw new TarParseException("value too large");
}
return (int)value;
}
public DateTime GetTime(TarHeader.HeaderField field)
{
string paxValue = GetPaxValue(field.PaxAttribute);
if (paxValue != null)
{
return TarTime.FromPaxTime(paxValue);
}
long unixTime = GetOctalLong(field.WithoutPax);
if (unixTime < TarTime.MinUnixTime)
{
unixTime = TarTime.MinUnixTime;
}
else if (unixTime > TarTime.MaxUnixTime)
{
unixTime = TarTime.MaxUnixTime;
}
return TarTime.FromUnixTime(unixTime, 0);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Resources;
using System.ComponentModel;
using System.Globalization;
using System.Text;
using System.Threading;
namespace System.Management.Automation
{
/// <summary>
/// EventLogLogProvider is a class to implement Msh Provider interface using EventLog technology.
///
/// EventLogLogProvider will be the provider to use if Monad is running in early windows releases
/// from 2000 to 2003.
///
/// EventLogLogProvider will be packaged in the same dll as Msh Log Engine since EventLog should
/// always be available.
/// </summary>
internal class EventLogLogProvider : LogProvider
{
/// <summary>
/// Constructor.
/// </summary>
/// <returns></returns>
internal EventLogLogProvider(string shellId)
{
string source = SetupEventSource(shellId);
_eventLog = new EventLog();
_eventLog.Source = source;
_resourceManager = new ResourceManager("System.Management.Automation.resources.Logging", System.Reflection.Assembly.GetExecutingAssembly());
}
internal string SetupEventSource(string shellId)
{
string source;
// In case shellId == null, use the "Default" source.
if (string.IsNullOrEmpty(shellId))
{
source = "Default";
}
else
{
int index = shellId.LastIndexOf('.');
if (index < 0)
source = shellId;
else
source = shellId.Substring(index + 1);
// There may be a situation where ShellId ends with a '.'.
// In that case, use the default source.
if (string.IsNullOrEmpty(source))
source = "Default";
}
if (EventLog.SourceExists(source))
{
return source;
}
string message = string.Format(Thread.CurrentThread.CurrentCulture, "Event source '{0}' is not registered", source);
throw new InvalidOperationException(message);
}
/// <summary>
/// This represent a handle to EventLog.
/// </summary>
private EventLog _eventLog;
private ResourceManager _resourceManager;
#region Log Provider Api
private const int EngineHealthCategoryId = 1;
private const int CommandHealthCategoryId = 2;
private const int ProviderHealthCategoryId = 3;
private const int EngineLifecycleCategoryId = 4;
private const int CommandLifecycleCategoryId = 5;
private const int ProviderLifecycleCategoryId = 6;
private const int SettingsCategoryId = 7;
private const int PipelineExecutionDetailCategoryId = 8;
/// <summary>
/// Log engine health event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="eventId"></param>
/// <param name="exception"></param>
/// <param name="additionalInfo"></param>
internal override void LogEngineHealthEvent(LogContext logContext, int eventId, Exception exception, Dictionary<string, string> additionalInfo)
{
Hashtable mapArgs = new Hashtable();
IContainsErrorRecord icer = exception as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
{
mapArgs["ExceptionClass"] = exception.GetType().Name;
mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category;
mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId;
if (icer.ErrorRecord.ErrorDetails != null)
{
mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message;
}
else
{
mapArgs["ErrorMessage"] = exception.Message;
}
}
else
{
mapArgs["ExceptionClass"] = exception.GetType().Name;
mapArgs["ErrorCategory"] = string.Empty;
mapArgs["ErrorId"] = string.Empty;
mapArgs["ErrorMessage"] = exception.Message;
}
FillEventArgs(mapArgs, logContext);
FillEventArgs(mapArgs, additionalInfo);
EventInstance entry = new EventInstance(eventId, EngineHealthCategoryId);
entry.EntryType = GetEventLogEntryType(logContext);
string detail = GetEventDetail("EngineHealthContext", mapArgs);
LogEvent(entry, mapArgs["ErrorMessage"], detail);
}
private static EventLogEntryType GetEventLogEntryType(LogContext logContext)
{
switch (logContext.Severity)
{
case "Critical":
case "Error":
return EventLogEntryType.Error;
case "Warning":
return EventLogEntryType.Warning;
default:
return EventLogEntryType.Information;
}
}
/// <summary>
/// Log engine lifecycle event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="newState"></param>
/// <param name="previousState"></param>
internal override void LogEngineLifecycleEvent(LogContext logContext, EngineState newState, EngineState previousState)
{
int eventId = GetEngineLifecycleEventId(newState);
if (eventId == _invalidEventId)
return;
Hashtable mapArgs = new Hashtable();
mapArgs["NewEngineState"] = newState.ToString();
mapArgs["PreviousEngineState"] = previousState.ToString();
FillEventArgs(mapArgs, logContext);
EventInstance entry = new EventInstance(eventId, EngineLifecycleCategoryId);
entry.EntryType = EventLogEntryType.Information;
string detail = GetEventDetail("EngineLifecycleContext", mapArgs);
LogEvent(entry, newState, previousState, detail);
}
private const int _baseEngineLifecycleEventId = 400;
private const int _invalidEventId = -1;
/// <summary>
/// Get engine lifecycle event id based on engine state.
/// </summary>
/// <param name="engineState"></param>
/// <returns></returns>
private static int GetEngineLifecycleEventId(EngineState engineState)
{
switch (engineState)
{
case EngineState.None:
return _invalidEventId;
case EngineState.Available:
return _baseEngineLifecycleEventId;
case EngineState.Degraded:
return _baseEngineLifecycleEventId + 1;
case EngineState.OutOfService:
return _baseEngineLifecycleEventId + 2;
case EngineState.Stopped:
return _baseEngineLifecycleEventId + 3;
}
return _invalidEventId;
}
private const int _commandHealthEventId = 200;
/// <summary>
/// Provider interface function for logging command health event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="exception"></param>
internal override void LogCommandHealthEvent(LogContext logContext, Exception exception)
{
int eventId = _commandHealthEventId;
Hashtable mapArgs = new Hashtable();
IContainsErrorRecord icer = exception as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
{
mapArgs["ExceptionClass"] = exception.GetType().Name;
mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category;
mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId;
if (icer.ErrorRecord.ErrorDetails != null)
{
mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message;
}
else
{
mapArgs["ErrorMessage"] = exception.Message;
}
}
else
{
mapArgs["ExceptionClass"] = exception.GetType().Name;
mapArgs["ErrorCategory"] = string.Empty;
mapArgs["ErrorId"] = string.Empty;
mapArgs["ErrorMessage"] = exception.Message;
}
FillEventArgs(mapArgs, logContext);
EventInstance entry = new EventInstance(eventId, CommandHealthCategoryId);
entry.EntryType = GetEventLogEntryType(logContext);
string detail = GetEventDetail("CommandHealthContext", mapArgs);
LogEvent(entry, mapArgs["ErrorMessage"], detail);
}
/// <summary>
/// Log command life cycle event.
/// </summary>
/// <param name="getLogContext"></param>
/// <param name="newState"></param>
internal override void LogCommandLifecycleEvent(Func<LogContext> getLogContext, CommandState newState)
{
LogContext logContext = getLogContext();
int eventId = GetCommandLifecycleEventId(newState);
if (eventId == _invalidEventId)
return;
Hashtable mapArgs = new Hashtable();
mapArgs["NewCommandState"] = newState.ToString();
FillEventArgs(mapArgs, logContext);
EventInstance entry = new EventInstance(eventId, CommandLifecycleCategoryId);
entry.EntryType = EventLogEntryType.Information;
string detail = GetEventDetail("CommandLifecycleContext", mapArgs);
LogEvent(entry, logContext.CommandName, newState, detail);
}
private const int _baseCommandLifecycleEventId = 500;
/// <summary>
/// Get command lifecycle event id based on command state.
/// </summary>
/// <param name="commandState"></param>
/// <returns></returns>
private static int GetCommandLifecycleEventId(CommandState commandState)
{
switch (commandState)
{
case CommandState.Started:
return _baseCommandLifecycleEventId;
case CommandState.Stopped:
return _baseCommandLifecycleEventId + 1;
case CommandState.Terminated:
return _baseCommandLifecycleEventId + 2;
}
return _invalidEventId;
}
private const int _pipelineExecutionDetailEventId = 800;
/// <summary>
/// Log pipeline execution detail event.
///
/// This may end of logging more than one event if the detail string is too long to be fit in 64K.
/// </summary>
/// <param name="logContext"></param>
/// <param name="pipelineExecutionDetail"></param>
internal override void LogPipelineExecutionDetailEvent(LogContext logContext, List<string> pipelineExecutionDetail)
{
List<string> details = GroupMessages(pipelineExecutionDetail);
for (int i = 0; i < details.Count; i++)
{
LogPipelineExecutionDetailEvent(logContext, details[i], i + 1, details.Count);
}
}
private const int MaxLength = 16000;
private List<string> GroupMessages(List<string> messages)
{
List<string> result = new List<string>();
if (messages == null || messages.Count == 0)
return result;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < messages.Count; i++)
{
if (sb.Length + messages[i].Length < MaxLength)
{
sb.AppendLine(messages[i]);
continue;
}
result.Add(sb.ToString());
sb = new StringBuilder();
sb.AppendLine(messages[i]);
}
result.Add(sb.ToString());
return result;
}
/// <summary>
/// Log one pipeline execution detail event. Detail message is already chopped up so that it will
/// fit in 64K.
/// </summary>
/// <param name="logContext"></param>
/// <param name="pipelineExecutionDetail"></param>
/// <param name="detailSequence"></param>
/// <param name="detailTotal"></param>
private void LogPipelineExecutionDetailEvent(LogContext logContext, string pipelineExecutionDetail, int detailSequence, int detailTotal)
{
int eventId = _pipelineExecutionDetailEventId;
Hashtable mapArgs = new Hashtable();
mapArgs["PipelineExecutionDetail"] = pipelineExecutionDetail;
mapArgs["DetailSequence"] = detailSequence;
mapArgs["DetailTotal"] = detailTotal;
FillEventArgs(mapArgs, logContext);
EventInstance entry = new EventInstance(eventId, PipelineExecutionDetailCategoryId);
entry.EntryType = EventLogEntryType.Information;
string pipelineInfo = GetEventDetail("PipelineExecutionDetailContext", mapArgs);
LogEvent(entry, logContext.CommandLine, pipelineInfo, pipelineExecutionDetail);
}
private const int _providerHealthEventId = 300;
/// <summary>
/// Provider interface function for logging provider health event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="providerName"></param>
/// <param name="exception"></param>
internal override void LogProviderHealthEvent(LogContext logContext, string providerName, Exception exception)
{
int eventId = _providerHealthEventId;
Hashtable mapArgs = new Hashtable();
mapArgs["ProviderName"] = providerName;
IContainsErrorRecord icer = exception as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
{
mapArgs["ExceptionClass"] = exception.GetType().Name;
mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category;
mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId;
if (icer.ErrorRecord.ErrorDetails != null
&& !string.IsNullOrEmpty(icer.ErrorRecord.ErrorDetails.Message))
{
mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message;
}
else
{
mapArgs["ErrorMessage"] = exception.Message;
}
}
else
{
mapArgs["ExceptionClass"] = exception.GetType().Name;
mapArgs["ErrorCategory"] = string.Empty;
mapArgs["ErrorId"] = string.Empty;
mapArgs["ErrorMessage"] = exception.Message;
}
FillEventArgs(mapArgs, logContext);
EventInstance entry = new EventInstance(eventId, ProviderHealthCategoryId);
entry.EntryType = GetEventLogEntryType(logContext);
string detail = GetEventDetail("ProviderHealthContext", mapArgs);
LogEvent(entry, mapArgs["ErrorMessage"], detail);
}
/// <summary>
/// Log provider lifecycle event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="providerName"></param>
/// <param name="newState"></param>
internal override void LogProviderLifecycleEvent(LogContext logContext, string providerName, ProviderState newState)
{
int eventId = GetProviderLifecycleEventId(newState);
if (eventId == _invalidEventId)
return;
Hashtable mapArgs = new Hashtable();
mapArgs["ProviderName"] = providerName;
mapArgs["NewProviderState"] = newState.ToString();
FillEventArgs(mapArgs, logContext);
EventInstance entry = new EventInstance(eventId, ProviderLifecycleCategoryId);
entry.EntryType = EventLogEntryType.Information;
string detail = GetEventDetail("ProviderLifecycleContext", mapArgs);
LogEvent(entry, providerName, newState, detail);
}
private const int _baseProviderLifecycleEventId = 600;
/// <summary>
/// Get provider lifecycle event id based on provider state.
/// </summary>
/// <param name="providerState"></param>
/// <returns></returns>
private static int GetProviderLifecycleEventId(ProviderState providerState)
{
switch (providerState)
{
case ProviderState.Started:
return _baseProviderLifecycleEventId;
case ProviderState.Stopped:
return _baseProviderLifecycleEventId + 1;
}
return _invalidEventId;
}
private const int _settingsEventId = 700;
/// <summary>
/// Log settings event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="variableName"></param>
/// <param name="value"></param>
/// <param name="previousValue"></param>
internal override void LogSettingsEvent(LogContext logContext, string variableName, string value, string previousValue)
{
int eventId = _settingsEventId;
Hashtable mapArgs = new Hashtable();
mapArgs["VariableName"] = variableName;
mapArgs["NewValue"] = value;
mapArgs["PreviousValue"] = previousValue;
FillEventArgs(mapArgs, logContext);
EventInstance entry = new EventInstance(eventId, SettingsCategoryId);
entry.EntryType = EventLogEntryType.Information;
string detail = GetEventDetail("SettingsContext", mapArgs);
LogEvent(entry, variableName, value, previousValue, detail);
}
#endregion Log Provider Api
#region EventLog helper functions
/// <summary>
/// This is the helper function for logging an event with localizable message
/// to event log. It will trace all exception thrown by eventlog.
/// </summary>
/// <param name="entry"></param>
/// <param name="args"></param>
private void LogEvent(EventInstance entry, params object[] args)
{
try
{
_eventLog.WriteEvent(entry, args);
}
catch (ArgumentException)
{
return;
}
catch (InvalidOperationException)
{
return;
}
catch (Win32Exception)
{
return;
}
}
#endregion
#region Event Arguments
/// <summary>
/// Fill event arguments with logContext info.
///
/// In EventLog Api, arguments are passed in as an array of objects.
/// </summary>
/// <param name="mapArgs">An ArrayList to contain the event arguments.</param>
/// <param name="logContext">The log context containing the info to fill in.</param>
private static void FillEventArgs(Hashtable mapArgs, LogContext logContext)
{
mapArgs["Severity"] = logContext.Severity;
mapArgs["SequenceNumber"] = logContext.SequenceNumber;
mapArgs["HostName"] = logContext.HostName;
mapArgs["HostVersion"] = logContext.HostVersion;
mapArgs["HostId"] = logContext.HostId;
mapArgs["HostApplication"] = logContext.HostApplication;
mapArgs["EngineVersion"] = logContext.EngineVersion;
mapArgs["RunspaceId"] = logContext.RunspaceId;
mapArgs["PipelineId"] = logContext.PipelineId;
mapArgs["CommandName"] = logContext.CommandName;
mapArgs["CommandType"] = logContext.CommandType;
mapArgs["ScriptName"] = logContext.ScriptName;
mapArgs["CommandPath"] = logContext.CommandPath;
mapArgs["CommandLine"] = logContext.CommandLine;
mapArgs["User"] = logContext.User;
mapArgs["Time"] = logContext.Time;
}
/// <summary>
/// Fill event arguments with additionalInfo stored in a string dictionary.
/// </summary>
/// <param name="mapArgs">An arraylist to contain the event arguments.</param>
/// <param name="additionalInfo">A string dictionary to fill in.</param>
private static void FillEventArgs(Hashtable mapArgs, Dictionary<string, string> additionalInfo)
{
if (additionalInfo == null)
{
for (int i = 0; i < 3; i++)
{
string id = ((int)(i + 1)).ToString("d1", CultureInfo.CurrentCulture);
mapArgs["AdditionalInfo_Name" + id] = string.Empty;
mapArgs["AdditionalInfo_Value" + id] = string.Empty;
}
return;
}
string[] keys = new string[additionalInfo.Count];
string[] values = new string[additionalInfo.Count];
additionalInfo.Keys.CopyTo(keys, 0);
additionalInfo.Values.CopyTo(values, 0);
for (int i = 0; i < 3; i++)
{
string id = ((int)(i + 1)).ToString("d1", CultureInfo.CurrentCulture);
if (i < keys.Length)
{
mapArgs["AdditionalInfo_Name" + id] = keys[i];
mapArgs["AdditionalInfo_Value" + id] = values[i];
}
else
{
mapArgs["AdditionalInfo_Name" + id] = string.Empty;
mapArgs["AdditionalInfo_Value" + id] = string.Empty;
}
}
return;
}
#endregion Event Arguments
#region Event Message
private string GetEventDetail(string contextId, Hashtable mapArgs)
{
return GetMessage(contextId, mapArgs);
}
private string GetMessage(string messageId, Hashtable mapArgs)
{
if (_resourceManager == null)
return string.Empty;
string messageTemplate = _resourceManager.GetString(messageId);
if (string.IsNullOrEmpty(messageTemplate))
return string.Empty;
return FillMessageTemplate(messageTemplate, mapArgs);
}
private static string FillMessageTemplate(string messageTemplate, Hashtable mapArgs)
{
StringBuilder message = new StringBuilder();
int cursor = 0;
while (true)
{
int startIndex = messageTemplate.IndexOf('[', cursor);
if (startIndex < 0)
{
message.Append(messageTemplate.Substring(cursor));
return message.ToString();
}
int endIndex = messageTemplate.IndexOf(']', startIndex + 1);
if (endIndex < 0)
{
message.Append(messageTemplate.Substring(cursor));
return message.ToString();
}
message.Append(messageTemplate.Substring(cursor, startIndex - cursor));
cursor = startIndex;
string placeHolder = messageTemplate.Substring(startIndex + 1, endIndex - startIndex - 1);
if (mapArgs.Contains(placeHolder))
{
message.Append(mapArgs[placeHolder]);
cursor = endIndex + 1;
}
else
{
message.Append("[");
cursor++;
}
}
}
#endregion Event Message
}
}
| |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.
*/
// Distributed under the Thrift Software License
//
// See accompanying file LICENSE or visit the Thrift site at:
// http://developers.facebook.com/thrift/
using System;
using System.Collections.Generic;
using Thrift.Collections;
using Thrift.Test; //generated code
using Thrift.Transport;
using Thrift.Protocol;
using Thrift.Server;
namespace Test
{
public class TestServer
{
public class TestHandler : ThriftTest.Iface
{
public TServer server;
public TestHandler() { }
public void testVoid()
{
Console.WriteLine("testVoid()");
}
public string testString(string thing)
{
Console.WriteLine("teststring(\"" + thing + "\")");
return thing;
}
public byte testByte(byte thing)
{
Console.WriteLine("testByte(" + thing + ")");
return thing;
}
public int testI32(int thing)
{
Console.WriteLine("testI32(" + thing + ")");
return thing;
}
public long testI64(long thing)
{
Console.WriteLine("testI64(" + thing + ")");
return thing;
}
public double testDouble(double thing)
{
Console.WriteLine("testDouble(" + thing + ")");
return thing;
}
public Xtruct testStruct(Xtruct thing)
{
Console.WriteLine("testStruct({" +
"\"" + thing.String_thing + "\", " +
thing.Byte_thing + ", " +
thing.I32_thing + ", " +
thing.I64_thing + "})");
return thing;
}
public Xtruct2 testNest(Xtruct2 nest)
{
Xtruct thing = nest.Struct_thing;
Console.WriteLine("testNest({" +
nest.Byte_thing + ", {" +
"\"" + thing.String_thing + "\", " +
thing.Byte_thing + ", " +
thing.I32_thing + ", " +
thing.I64_thing + "}, " +
nest.I32_thing + "})");
return nest;
}
public Dictionary<int, int> testMap(Dictionary<int, int> thing)
{
Console.WriteLine("testMap({");
bool first = true;
foreach (int key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
Console.WriteLine(", ");
}
Console.WriteLine(key + " => " + thing[key]);
}
Console.WriteLine("})");
return thing;
}
public THashSet<int> testSet(THashSet<int> thing)
{
Console.WriteLine("testSet({");
bool first = true;
foreach (int elem in thing)
{
if (first)
{
first = false;
}
else
{
Console.WriteLine(", ");
}
Console.WriteLine(elem);
}
Console.WriteLine("})");
return thing;
}
public List<int> testList(List<int> thing)
{
Console.WriteLine("testList({");
bool first = true;
foreach (int elem in thing)
{
if (first)
{
first = false;
}
else
{
Console.WriteLine(", ");
}
Console.WriteLine(elem);
}
Console.WriteLine("})");
return thing;
}
public Numberz testEnum(Numberz thing)
{
Console.WriteLine("testEnum(" + thing + ")");
return thing;
}
public long testTypedef(long thing)
{
Console.WriteLine("testTypedef(" + thing + ")");
return thing;
}
public Dictionary<int, Dictionary<int, int>> testMapMap(int hello)
{
Console.WriteLine("testMapMap(" + hello + ")");
Dictionary<int, Dictionary<int, int>> mapmap =
new Dictionary<int, Dictionary<int, int>>();
Dictionary<int, int> pos = new Dictionary<int, int>();
Dictionary<int, int> neg = new Dictionary<int, int>();
for (int i = 1; i < 5; i++)
{
pos[i] = i;
neg[-i] = -i;
}
mapmap[4] = pos;
mapmap[-4] = neg;
return mapmap;
}
public Dictionary<long, Dictionary<Numberz, Insanity>> testInsanity(Insanity argument)
{
Console.WriteLine("testInsanity()");
Xtruct hello = new Xtruct();
hello.String_thing = "Hello2";
hello.Byte_thing = 2;
hello.I32_thing = 2;
hello.I64_thing = 2;
Xtruct goodbye = new Xtruct();
goodbye.String_thing = "Goodbye4";
goodbye.Byte_thing = (byte)4;
goodbye.I32_thing = 4;
goodbye.I64_thing = (long)4;
Insanity crazy = new Insanity();
crazy.UserMap = new Dictionary<Numberz, long>();
crazy.UserMap[Numberz.EIGHT] = (long)8;
crazy.Xtructs = new List<Xtruct>();
crazy.Xtructs.Add(goodbye);
Insanity looney = new Insanity();
crazy.UserMap[Numberz.FIVE] = (long)5;
crazy.Xtructs.Add(hello);
Dictionary<Numberz, Insanity> first_map = new Dictionary<Numberz, Insanity>();
Dictionary<Numberz, Insanity> second_map = new Dictionary<Numberz, Insanity>(); ;
first_map[Numberz.TWO] = crazy;
first_map[Numberz.THREE] = crazy;
second_map[Numberz.SIX] = looney;
Dictionary<long, Dictionary<Numberz, Insanity>> insane =
new Dictionary<long, Dictionary<Numberz, Insanity>>();
insane[(long)1] = first_map;
insane[(long)2] = second_map;
return insane;
}
public Xtruct testMulti(byte arg0, int arg1, long arg2, Dictionary<short, string> arg3, Numberz arg4, long arg5)
{
Console.WriteLine("testMulti()");
Xtruct hello = new Xtruct(); ;
hello.String_thing = "Hello2";
hello.Byte_thing = arg0;
hello.I32_thing = arg1;
hello.I64_thing = arg2;
return hello;
}
public void testException(string arg)
{
Console.WriteLine("testException(" + arg + ")");
if (arg == "Xception")
{
Xception x = new Xception();
x.ErrorCode = 1001;
x.Message = "This is an Xception";
throw x;
}
return;
}
public Xtruct testMultiException(string arg0, string arg1)
{
Console.WriteLine("testMultiException(" + arg0 + ", " + arg1 + ")");
if (arg0 == "Xception")
{
Xception x = new Xception();
x.ErrorCode = 1001;
x.Message = "This is an Xception";
throw x;
}
else if (arg0 == "Xception2")
{
Xception2 x = new Xception2();
x.ErrorCode = 2002;
x.Struct_thing = new Xtruct();
x.Struct_thing.String_thing = "This is an Xception2";
throw x;
}
Xtruct result = new Xtruct();
result.String_thing = arg1;
return result;
}
public void testStop()
{
if (server != null)
{
server.Stop();
}
}
public void testOneway(int arg)
{
Console.WriteLine("testOneway(" + arg + "), sleeping...");
System.Threading.Thread.Sleep(arg * 1000);
Console.WriteLine("testOneway finished");
}
} // class TestHandler
public static void Execute(string[] args)
{
try
{
bool useBufferedSockets = false;
int port = 9090;
if (args.Length > 0)
{
port = int.Parse(args[0]);
if (args.Length > 1)
{
bool.TryParse(args[1], out useBufferedSockets);
}
}
// Processor
TestHandler testHandler = new TestHandler();
ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler);
// Transport
TServerSocket tServerSocket = new TServerSocket(port, 0, useBufferedSockets);
TServer serverEngine;
// Simple Server
serverEngine = new TSimpleServer(testProcessor, tServerSocket);
// ThreadPool Server
// serverEngine = new TThreadPoolServer(testProcessor, tServerSocket);
// Threaded Server
// serverEngine = new TThreadedServer(testProcessor, tServerSocket);
testHandler.server = serverEngine;
// Run it
Console.WriteLine("Starting the server on port " + port + (useBufferedSockets ? " with buffered socket" : "") + "...");
serverEngine.Serve();
}
catch (Exception x)
{
Console.Error.Write(x);
}
Console.WriteLine("done.");
}
}
}
| |
//
// Image.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Binary {
using System;
using System.IO;
using Mono.Cecil.Metadata;
public sealed class Image : IBinaryVisitable {
DOSHeader m_dosHeader;
PEFileHeader m_peFileHeader;
PEOptionalHeader m_peOptionalHeader;
SectionCollection m_sections;
Section m_textSection;
ImportAddressTable m_importAddressTable;
CLIHeader m_cliHeader;
ImportTable m_importTable;
ImportLookupTable m_importLookupTable;
HintNameTable m_hintNameTable;
DebugHeader m_debugHeader;
MetadataRoot m_mdRoot;
ResourceDirectoryTable m_rsrcRoot;
FileInfo m_img;
public DOSHeader DOSHeader {
get { return m_dosHeader; }
}
public PEFileHeader PEFileHeader {
get { return m_peFileHeader; }
}
public PEOptionalHeader PEOptionalHeader {
get { return m_peOptionalHeader; }
}
public SectionCollection Sections {
get { return m_sections; }
}
public Section TextSection {
get { return m_textSection; }
set { m_textSection = value; }
}
public ImportAddressTable ImportAddressTable {
get { return m_importAddressTable; }
}
public CLIHeader CLIHeader {
get { return m_cliHeader; }
}
public DebugHeader DebugHeader {
get { return m_debugHeader; }
set { m_debugHeader = value; }
}
public MetadataRoot MetadataRoot {
get { return m_mdRoot; }
}
public ImportTable ImportTable {
get { return m_importTable; }
}
public ImportLookupTable ImportLookupTable {
get { return m_importLookupTable; }
}
public HintNameTable HintNameTable {
get { return m_hintNameTable; }
}
internal ResourceDirectoryTable ResourceDirectoryRoot {
get { return m_rsrcRoot; }
set { m_rsrcRoot = value; }
}
public FileInfo FileInformation {
get { return m_img; }
}
internal Image ()
{
m_dosHeader = new DOSHeader ();
m_peFileHeader = new PEFileHeader ();
m_peOptionalHeader = new PEOptionalHeader ();
m_sections = new SectionCollection ();
m_importAddressTable = new ImportAddressTable ();
m_cliHeader = new CLIHeader ();
m_importTable = new ImportTable ();
m_importLookupTable = new ImportLookupTable ();
m_hintNameTable = new HintNameTable ();
m_mdRoot = new MetadataRoot (this);
}
internal Image (FileInfo img) : this ()
{
m_img = img;
}
public long ResolveVirtualAddress (RVA rva)
{
foreach (Section sect in this.Sections) {
if (rva >= sect.VirtualAddress &&
rva < sect.VirtualAddress + sect.SizeOfRawData)
return rva + sect.PointerToRawData - sect.VirtualAddress;
}
return 0;
}
public BinaryReader GetReaderAtVirtualAddress (RVA rva)
{
foreach (Section sect in this.Sections) {
if (rva >= sect.VirtualAddress &&
rva < sect.VirtualAddress + sect.SizeOfRawData) {
BinaryReader br = new BinaryReader (new MemoryStream (sect.Data));
br.BaseStream.Position = rva - sect.VirtualAddress;
return br;
}
}
return null;
}
public void AddDebugHeader ()
{
m_debugHeader = new DebugHeader ();
m_debugHeader.SetDefaultValues ();
}
public void Accept (IBinaryVisitor visitor)
{
visitor.VisitImage (this);
m_dosHeader.Accept (visitor);
m_peFileHeader.Accept (visitor);
m_peOptionalHeader.Accept (visitor);
m_sections.Accept (visitor);
m_importAddressTable.Accept (visitor);
m_cliHeader.Accept (visitor);
if (m_debugHeader != null)
m_debugHeader.Accept (visitor);
m_importTable.Accept (visitor);
m_importLookupTable.Accept (visitor);
m_hintNameTable.Accept (visitor);
visitor.TerminateImage (this);
}
public static Image CreateImage ()
{
Image img = new Image ();
ImageInitializer init = new ImageInitializer (img);
img.Accept (init);
return img;
}
public static Image GetImage (string file)
{
return ImageReader.Read (file).Image;
}
public static Image GetImage (byte [] image)
{
return ImageReader.Read (image).Image;
}
public static Image GetImage (Stream stream)
{
return ImageReader.Read (stream).Image;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: A collection of methods for manipulating Files.
**
** April 09,2000 (some design refactorization)
**
===========================================================*/
using System;
#if FEATURE_MACL
using System.Security.AccessControl;
#endif
using System.Security.Permissions;
using PermissionSet = System.Security.PermissionSet;
using Win32Native = Microsoft.Win32.Win32Native;
using System.Runtime.InteropServices;
using System.Text;
using System.Runtime.Serialization;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System.IO {
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
[Serializable]
[ComVisible(true)]
public sealed class FileInfo: FileSystemInfo
{
private String _name;
#if FEATURE_CORECLR
// Migrating InheritanceDemands requires this default ctor, so we can annotate it.
#if FEATURE_CORESYSTEM
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical]
#endif //FEATURE_CORESYSTEM
private FileInfo(){}
[System.Security.SecurityCritical]
public static FileInfo UnsafeCreateFileInfo(String fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
Contract.EndContractBlock();
FileInfo fi = new FileInfo();
fi.Init(fileName, false);
return fi;
}
#endif
[System.Security.SecuritySafeCritical]
public FileInfo(String fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
Contract.EndContractBlock();
#if FEATURE_LEGACYNETCF
if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
{
System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly();
if(callingAssembly != null && !callingAssembly.IsProfileAssembly)
{
string caller = new System.Diagnostics.StackFrame(1).GetMethod().FullName;
string callee = System.Reflection.MethodBase.GetCurrentMethod().FullName;
throw new MethodAccessException(String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Arg_MethodAccessException_WithCaller"),
caller,
callee));
}
}
#endif // FEATURE_LEGACYNETCF
Init(fileName, true);
}
[System.Security.SecurityCritical]
private void Init(String fileName, bool checkHost)
{
OriginalPath = fileName;
// Must fully qualify the path for the security check
String fullPath = Path.GetFullPathInternal(fileName);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, fileName, fullPath);
state.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
#endif
_name = Path.GetFileName(fileName);
FullPath = fullPath;
DisplayPath = GetDisplayPath(fileName);
}
private String GetDisplayPath(String originalPath)
{
#if FEATURE_CORECLR
return Path.GetFileName(originalPath);
#else
return originalPath;
#endif
}
[System.Security.SecurityCritical] // auto-generated
private FileInfo(SerializationInfo info, StreamingContext context) : base(info, context)
{
#if !FEATURE_CORECLR
new FileIOPermission(FileIOPermissionAccess.Read, new String[] { FullPath }, false, false).Demand();
#endif
_name = Path.GetFileName(OriginalPath);
DisplayPath = GetDisplayPath(OriginalPath);
}
#if FEATURE_CORESYSTEM
[System.Security.SecuritySafeCritical]
#endif //FEATURE_CORESYSTEM
internal FileInfo(String fullPath, bool ignoreThis)
{
Contract.Assert(Path.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
_name = Path.GetFileName(fullPath);
OriginalPath = _name;
FullPath = fullPath;
DisplayPath = _name;
}
public override String Name {
get { return _name; }
}
public long Length {
[System.Security.SecuritySafeCritical] // auto-generated
get {
if (_dataInitialised == -1)
Refresh();
if (_dataInitialised != 0) // Refresh was unable to initialise the data
__Error.WinIOError(_dataInitialised, DisplayPath);
if ((_data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0)
__Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, DisplayPath);
return ((long)_data.fileSizeHigh) << 32 | ((long)_data.fileSizeLow & 0xFFFFFFFFL);
}
}
/* Returns the name of the directory that the file is in */
public String DirectoryName
{
[System.Security.SecuritySafeCritical]
get
{
String directoryName = Path.GetDirectoryName(FullPath);
if (directoryName != null)
{
#if FEATURE_CORECLR
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, DisplayPath, FullPath);
state.EnsureState();
#else
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { directoryName }, false, false).Demand();
#endif
}
return directoryName;
}
}
/* Creates an instance of the the parent directory */
public DirectoryInfo Directory
{
get
{
String dirName = DirectoryName;
if (dirName == null)
return null;
return new DirectoryInfo(dirName);
}
}
public bool IsReadOnly {
get {
return (Attributes & FileAttributes.ReadOnly) != 0;
}
set {
if (value)
Attributes |= FileAttributes.ReadOnly;
else
Attributes &= ~FileAttributes.ReadOnly;
}
}
#if FEATURE_MACL
public FileSecurity GetAccessControl()
{
return File.GetAccessControl(FullPath, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
}
public FileSecurity GetAccessControl(AccessControlSections includeSections)
{
return File.GetAccessControl(FullPath, includeSections);
}
public void SetAccessControl(FileSecurity fileSecurity)
{
File.SetAccessControl(FullPath, fileSecurity);
}
#endif
[System.Security.SecuritySafeCritical] // auto-generated
public StreamReader OpenText()
{
return new StreamReader(FullPath, Encoding.UTF8, true, StreamReader.DefaultBufferSize, false);
}
public StreamWriter CreateText()
{
return new StreamWriter(FullPath,false);
}
public StreamWriter AppendText()
{
return new StreamWriter(FullPath,true);
}
// Copies an existing file to a new file. An exception is raised if the
// destination file already exists. Use the
// Copy(String, String, boolean) method to allow
// overwriting an existing file.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName
// and Write permissions to destFileName.
//
public FileInfo CopyTo(String destFileName) {
if (destFileName == null)
throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
destFileName = File.InternalCopy(FullPath, destFileName, false, true);
return new FileInfo(destFileName, false);
}
// Copies an existing file to a new file. If overwrite is
// false, then an IOException is thrown if the destination file
// already exists. If overwrite is true, the file is
// overwritten.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName and Create
// and Write permissions to destFileName.
//
public FileInfo CopyTo(String destFileName, bool overwrite) {
if (destFileName == null)
throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
destFileName = File.InternalCopy(FullPath, destFileName, overwrite, true);
return new FileInfo(destFileName, false);
}
public FileStream Create() {
return File.Create(FullPath);
}
// Deletes a file. The file specified by the designated path is deleted.
// If the file does not exist, Delete succeeds without throwing
// an exception.
//
// On NT, Delete will fail for a file that is open for normal I/O
// or a file that is memory mapped. On Win95, the file will be
// deleted irregardless of whether the file is being used.
//
// Your application must have Delete permission to the target file.
//
[System.Security.SecuritySafeCritical]
public override void Delete()
{
#if FEATURE_CORECLR
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, DisplayPath, FullPath);
state.EnsureState();
#else
// For security check, path should be resolved to an absolute path.
new FileIOPermission(FileIOPermissionAccess.Write, new String[] { FullPath }, false, false).Demand();
#endif
bool r = Win32Native.DeleteFile(FullPath);
if (!r) {
int hr = Marshal.GetLastWin32Error();
if (hr==Win32Native.ERROR_FILE_NOT_FOUND)
return;
else
__Error.WinIOError(hr, DisplayPath);
}
}
[ComVisible(false)]
public void Decrypt()
{
File.Decrypt(FullPath);
}
[ComVisible(false)]
public void Encrypt()
{
File.Encrypt(FullPath);
}
// Tests if the given file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false.
//
// Your application must have Read permission for the target directory.
public override bool Exists {
[System.Security.SecuritySafeCritical] // auto-generated
get {
try {
if (_dataInitialised == -1)
Refresh();
if (_dataInitialised != 0) {
// Refresh was unable to initialise the data.
// We should normally be throwing an exception here,
// but Exists is supposed to return true or false.
return false;
}
return (_data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0;
}
catch
{
return false;
}
}
}
// User must explicitly specify opening a new file or appending to one.
public FileStream Open(FileMode mode) {
return Open(mode, FileAccess.ReadWrite, FileShare.None);
}
public FileStream Open(FileMode mode, FileAccess access) {
return Open(mode, access, FileShare.None);
}
public FileStream Open(FileMode mode, FileAccess access, FileShare share) {
return new FileStream(FullPath, mode, access, share);
}
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#endif
public FileStream OpenRead()
{
return new FileStream(FullPath, FileMode.Open, FileAccess.Read,
FileShare.Read, 4096, false);
}
public FileStream OpenWrite() {
return new FileStream(FullPath, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None);
}
// Moves a given file to a new location and potentially a new file name.
// This method does work across volumes.
//
// The caller must have certain FileIOPermissions. The caller must
// have Read and Write permission to
// sourceFileName and Write
// permissions to destFileName.
//
[System.Security.SecuritySafeCritical]
public void MoveTo(String destFileName) {
if (destFileName==null)
throw new ArgumentNullException("destFileName");
if (destFileName.Length==0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
String fullDestFileName = Path.GetFullPathInternal(destFileName);
#if FEATURE_CORECLR
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, FullPath);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName);
sourceState.EnsureState();
destState.EnsureState();
#else
new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new String[] { FullPath }, false, false).Demand();
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false);
#endif
if (!Win32Native.MoveFile(FullPath, fullDestFileName))
__Error.WinIOError();
FullPath = fullDestFileName;
OriginalPath = destFileName;
_name = Path.GetFileName(fullDestFileName);
DisplayPath = GetDisplayPath(destFileName);
// Flush any cached information about the file.
_dataInitialised = -1;
}
[ComVisible(false)]
public FileInfo Replace(String destinationFileName, String destinationBackupFileName)
{
return Replace(destinationFileName, destinationBackupFileName, false);
}
[ComVisible(false)]
public FileInfo Replace(String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
{
File.Replace(FullPath, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
return new FileInfo(destinationFileName);
}
// Returns the display path
public override String ToString()
{
return DisplayPath;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/genomics/v1alpha2/pipelines.proto
// Original file comments:
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace Google.Genomics.V1Alpha2 {
/// <summary>
/// A service for running genomics pipelines.
/// </summary>
public static class PipelinesV1Alpha2
{
static readonly string __ServiceName = "google.genomics.v1alpha2.PipelinesV1Alpha2";
static readonly Marshaller<global::Google.Genomics.V1Alpha2.CreatePipelineRequest> __Marshaller_CreatePipelineRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Genomics.V1Alpha2.CreatePipelineRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Genomics.V1Alpha2.Pipeline> __Marshaller_Pipeline = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Genomics.V1Alpha2.Pipeline.Parser.ParseFrom);
static readonly Marshaller<global::Google.Genomics.V1Alpha2.RunPipelineRequest> __Marshaller_RunPipelineRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Genomics.V1Alpha2.RunPipelineRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.LongRunning.Operation> __Marshaller_Operation = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.LongRunning.Operation.Parser.ParseFrom);
static readonly Marshaller<global::Google.Genomics.V1Alpha2.GetPipelineRequest> __Marshaller_GetPipelineRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Genomics.V1Alpha2.GetPipelineRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Genomics.V1Alpha2.ListPipelinesRequest> __Marshaller_ListPipelinesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Genomics.V1Alpha2.ListPipelinesRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Genomics.V1Alpha2.ListPipelinesResponse> __Marshaller_ListPipelinesResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Genomics.V1Alpha2.ListPipelinesResponse.Parser.ParseFrom);
static readonly Marshaller<global::Google.Genomics.V1Alpha2.DeletePipelineRequest> __Marshaller_DeletePipelineRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Genomics.V1Alpha2.DeletePipelineRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly Marshaller<global::Google.Genomics.V1Alpha2.GetControllerConfigRequest> __Marshaller_GetControllerConfigRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Genomics.V1Alpha2.GetControllerConfigRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Genomics.V1Alpha2.ControllerConfig> __Marshaller_ControllerConfig = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Genomics.V1Alpha2.ControllerConfig.Parser.ParseFrom);
static readonly Marshaller<global::Google.Genomics.V1Alpha2.SetOperationStatusRequest> __Marshaller_SetOperationStatusRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Genomics.V1Alpha2.SetOperationStatusRequest.Parser.ParseFrom);
static readonly Method<global::Google.Genomics.V1Alpha2.CreatePipelineRequest, global::Google.Genomics.V1Alpha2.Pipeline> __Method_CreatePipeline = new Method<global::Google.Genomics.V1Alpha2.CreatePipelineRequest, global::Google.Genomics.V1Alpha2.Pipeline>(
MethodType.Unary,
__ServiceName,
"CreatePipeline",
__Marshaller_CreatePipelineRequest,
__Marshaller_Pipeline);
static readonly Method<global::Google.Genomics.V1Alpha2.RunPipelineRequest, global::Google.LongRunning.Operation> __Method_RunPipeline = new Method<global::Google.Genomics.V1Alpha2.RunPipelineRequest, global::Google.LongRunning.Operation>(
MethodType.Unary,
__ServiceName,
"RunPipeline",
__Marshaller_RunPipelineRequest,
__Marshaller_Operation);
static readonly Method<global::Google.Genomics.V1Alpha2.GetPipelineRequest, global::Google.Genomics.V1Alpha2.Pipeline> __Method_GetPipeline = new Method<global::Google.Genomics.V1Alpha2.GetPipelineRequest, global::Google.Genomics.V1Alpha2.Pipeline>(
MethodType.Unary,
__ServiceName,
"GetPipeline",
__Marshaller_GetPipelineRequest,
__Marshaller_Pipeline);
static readonly Method<global::Google.Genomics.V1Alpha2.ListPipelinesRequest, global::Google.Genomics.V1Alpha2.ListPipelinesResponse> __Method_ListPipelines = new Method<global::Google.Genomics.V1Alpha2.ListPipelinesRequest, global::Google.Genomics.V1Alpha2.ListPipelinesResponse>(
MethodType.Unary,
__ServiceName,
"ListPipelines",
__Marshaller_ListPipelinesRequest,
__Marshaller_ListPipelinesResponse);
static readonly Method<global::Google.Genomics.V1Alpha2.DeletePipelineRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeletePipeline = new Method<global::Google.Genomics.V1Alpha2.DeletePipelineRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
MethodType.Unary,
__ServiceName,
"DeletePipeline",
__Marshaller_DeletePipelineRequest,
__Marshaller_Empty);
static readonly Method<global::Google.Genomics.V1Alpha2.GetControllerConfigRequest, global::Google.Genomics.V1Alpha2.ControllerConfig> __Method_GetControllerConfig = new Method<global::Google.Genomics.V1Alpha2.GetControllerConfigRequest, global::Google.Genomics.V1Alpha2.ControllerConfig>(
MethodType.Unary,
__ServiceName,
"GetControllerConfig",
__Marshaller_GetControllerConfigRequest,
__Marshaller_ControllerConfig);
static readonly Method<global::Google.Genomics.V1Alpha2.SetOperationStatusRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_SetOperationStatus = new Method<global::Google.Genomics.V1Alpha2.SetOperationStatusRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
MethodType.Unary,
__ServiceName,
"SetOperationStatus",
__Marshaller_SetOperationStatusRequest,
__Marshaller_Empty);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Genomics.V1Alpha2.PipelinesReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of PipelinesV1Alpha2</summary>
public abstract class PipelinesV1Alpha2Base
{
/// <summary>
/// Creates a pipeline that can be run later. Create takes a Pipeline that
/// has all fields other than `pipelineId` populated, and then returns
/// the same pipeline with `pipelineId` populated. This id can be used
/// to run the pipeline.
///
/// Caller must have WRITE permission to the project.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Genomics.V1Alpha2.Pipeline> CreatePipeline(global::Google.Genomics.V1Alpha2.CreatePipelineRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Runs a pipeline. If `pipelineId` is specified in the request, then
/// run a saved pipeline. If `ephemeralPipeline` is specified, then run
/// that pipeline once without saving a copy.
///
/// The caller must have READ permission to the project where the pipeline
/// is stored and WRITE permission to the project where the pipeline will be
/// run, as VMs will be created and storage will be used.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> RunPipeline(global::Google.Genomics.V1Alpha2.RunPipelineRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Retrieves a pipeline based on ID.
///
/// Caller must have READ permission to the project.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Genomics.V1Alpha2.Pipeline> GetPipeline(global::Google.Genomics.V1Alpha2.GetPipelineRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Lists pipelines.
///
/// Caller must have READ permission to the project.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Genomics.V1Alpha2.ListPipelinesResponse> ListPipelines(global::Google.Genomics.V1Alpha2.ListPipelinesRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Deletes a pipeline based on ID.
///
/// Caller must have WRITE permission to the project.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeletePipeline(global::Google.Genomics.V1Alpha2.DeletePipelineRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Gets controller configuration information. Should only be called
/// by VMs created by the Pipelines Service and not by end users.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Genomics.V1Alpha2.ControllerConfig> GetControllerConfig(global::Google.Genomics.V1Alpha2.GetControllerConfigRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Sets status of a given operation. All timestamps are sent on each
/// call, and the whole series of events is replaced, in case
/// intermediate calls are lost. Should only be called by VMs created
/// by the Pipelines Service and not by end users.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> SetOperationStatus(global::Google.Genomics.V1Alpha2.SetOperationStatusRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for PipelinesV1Alpha2</summary>
public class PipelinesV1Alpha2Client : ClientBase<PipelinesV1Alpha2Client>
{
/// <summary>Creates a new client for PipelinesV1Alpha2</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public PipelinesV1Alpha2Client(Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for PipelinesV1Alpha2 that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public PipelinesV1Alpha2Client(CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected PipelinesV1Alpha2Client() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected PipelinesV1Alpha2Client(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Creates a pipeline that can be run later. Create takes a Pipeline that
/// has all fields other than `pipelineId` populated, and then returns
/// the same pipeline with `pipelineId` populated. This id can be used
/// to run the pipeline.
///
/// Caller must have WRITE permission to the project.
/// </summary>
public virtual global::Google.Genomics.V1Alpha2.Pipeline CreatePipeline(global::Google.Genomics.V1Alpha2.CreatePipelineRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreatePipeline(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates a pipeline that can be run later. Create takes a Pipeline that
/// has all fields other than `pipelineId` populated, and then returns
/// the same pipeline with `pipelineId` populated. This id can be used
/// to run the pipeline.
///
/// Caller must have WRITE permission to the project.
/// </summary>
public virtual global::Google.Genomics.V1Alpha2.Pipeline CreatePipeline(global::Google.Genomics.V1Alpha2.CreatePipelineRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CreatePipeline, null, options, request);
}
/// <summary>
/// Creates a pipeline that can be run later. Create takes a Pipeline that
/// has all fields other than `pipelineId` populated, and then returns
/// the same pipeline with `pipelineId` populated. This id can be used
/// to run the pipeline.
///
/// Caller must have WRITE permission to the project.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Genomics.V1Alpha2.Pipeline> CreatePipelineAsync(global::Google.Genomics.V1Alpha2.CreatePipelineRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreatePipelineAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates a pipeline that can be run later. Create takes a Pipeline that
/// has all fields other than `pipelineId` populated, and then returns
/// the same pipeline with `pipelineId` populated. This id can be used
/// to run the pipeline.
///
/// Caller must have WRITE permission to the project.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Genomics.V1Alpha2.Pipeline> CreatePipelineAsync(global::Google.Genomics.V1Alpha2.CreatePipelineRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CreatePipeline, null, options, request);
}
/// <summary>
/// Runs a pipeline. If `pipelineId` is specified in the request, then
/// run a saved pipeline. If `ephemeralPipeline` is specified, then run
/// that pipeline once without saving a copy.
///
/// The caller must have READ permission to the project where the pipeline
/// is stored and WRITE permission to the project where the pipeline will be
/// run, as VMs will be created and storage will be used.
/// </summary>
public virtual global::Google.LongRunning.Operation RunPipeline(global::Google.Genomics.V1Alpha2.RunPipelineRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RunPipeline(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Runs a pipeline. If `pipelineId` is specified in the request, then
/// run a saved pipeline. If `ephemeralPipeline` is specified, then run
/// that pipeline once without saving a copy.
///
/// The caller must have READ permission to the project where the pipeline
/// is stored and WRITE permission to the project where the pipeline will be
/// run, as VMs will be created and storage will be used.
/// </summary>
public virtual global::Google.LongRunning.Operation RunPipeline(global::Google.Genomics.V1Alpha2.RunPipelineRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_RunPipeline, null, options, request);
}
/// <summary>
/// Runs a pipeline. If `pipelineId` is specified in the request, then
/// run a saved pipeline. If `ephemeralPipeline` is specified, then run
/// that pipeline once without saving a copy.
///
/// The caller must have READ permission to the project where the pipeline
/// is stored and WRITE permission to the project where the pipeline will be
/// run, as VMs will be created and storage will be used.
/// </summary>
public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> RunPipelineAsync(global::Google.Genomics.V1Alpha2.RunPipelineRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RunPipelineAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Runs a pipeline. If `pipelineId` is specified in the request, then
/// run a saved pipeline. If `ephemeralPipeline` is specified, then run
/// that pipeline once without saving a copy.
///
/// The caller must have READ permission to the project where the pipeline
/// is stored and WRITE permission to the project where the pipeline will be
/// run, as VMs will be created and storage will be used.
/// </summary>
public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> RunPipelineAsync(global::Google.Genomics.V1Alpha2.RunPipelineRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_RunPipeline, null, options, request);
}
/// <summary>
/// Retrieves a pipeline based on ID.
///
/// Caller must have READ permission to the project.
/// </summary>
public virtual global::Google.Genomics.V1Alpha2.Pipeline GetPipeline(global::Google.Genomics.V1Alpha2.GetPipelineRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetPipeline(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Retrieves a pipeline based on ID.
///
/// Caller must have READ permission to the project.
/// </summary>
public virtual global::Google.Genomics.V1Alpha2.Pipeline GetPipeline(global::Google.Genomics.V1Alpha2.GetPipelineRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetPipeline, null, options, request);
}
/// <summary>
/// Retrieves a pipeline based on ID.
///
/// Caller must have READ permission to the project.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Genomics.V1Alpha2.Pipeline> GetPipelineAsync(global::Google.Genomics.V1Alpha2.GetPipelineRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetPipelineAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Retrieves a pipeline based on ID.
///
/// Caller must have READ permission to the project.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Genomics.V1Alpha2.Pipeline> GetPipelineAsync(global::Google.Genomics.V1Alpha2.GetPipelineRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetPipeline, null, options, request);
}
/// <summary>
/// Lists pipelines.
///
/// Caller must have READ permission to the project.
/// </summary>
public virtual global::Google.Genomics.V1Alpha2.ListPipelinesResponse ListPipelines(global::Google.Genomics.V1Alpha2.ListPipelinesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListPipelines(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists pipelines.
///
/// Caller must have READ permission to the project.
/// </summary>
public virtual global::Google.Genomics.V1Alpha2.ListPipelinesResponse ListPipelines(global::Google.Genomics.V1Alpha2.ListPipelinesRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListPipelines, null, options, request);
}
/// <summary>
/// Lists pipelines.
///
/// Caller must have READ permission to the project.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Genomics.V1Alpha2.ListPipelinesResponse> ListPipelinesAsync(global::Google.Genomics.V1Alpha2.ListPipelinesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListPipelinesAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists pipelines.
///
/// Caller must have READ permission to the project.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Genomics.V1Alpha2.ListPipelinesResponse> ListPipelinesAsync(global::Google.Genomics.V1Alpha2.ListPipelinesRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListPipelines, null, options, request);
}
/// <summary>
/// Deletes a pipeline based on ID.
///
/// Caller must have WRITE permission to the project.
/// </summary>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeletePipeline(global::Google.Genomics.V1Alpha2.DeletePipelineRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeletePipeline(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Deletes a pipeline based on ID.
///
/// Caller must have WRITE permission to the project.
/// </summary>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeletePipeline(global::Google.Genomics.V1Alpha2.DeletePipelineRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_DeletePipeline, null, options, request);
}
/// <summary>
/// Deletes a pipeline based on ID.
///
/// Caller must have WRITE permission to the project.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeletePipelineAsync(global::Google.Genomics.V1Alpha2.DeletePipelineRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeletePipelineAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Deletes a pipeline based on ID.
///
/// Caller must have WRITE permission to the project.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeletePipelineAsync(global::Google.Genomics.V1Alpha2.DeletePipelineRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_DeletePipeline, null, options, request);
}
/// <summary>
/// Gets controller configuration information. Should only be called
/// by VMs created by the Pipelines Service and not by end users.
/// </summary>
public virtual global::Google.Genomics.V1Alpha2.ControllerConfig GetControllerConfig(global::Google.Genomics.V1Alpha2.GetControllerConfigRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetControllerConfig(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets controller configuration information. Should only be called
/// by VMs created by the Pipelines Service and not by end users.
/// </summary>
public virtual global::Google.Genomics.V1Alpha2.ControllerConfig GetControllerConfig(global::Google.Genomics.V1Alpha2.GetControllerConfigRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetControllerConfig, null, options, request);
}
/// <summary>
/// Gets controller configuration information. Should only be called
/// by VMs created by the Pipelines Service and not by end users.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Genomics.V1Alpha2.ControllerConfig> GetControllerConfigAsync(global::Google.Genomics.V1Alpha2.GetControllerConfigRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetControllerConfigAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets controller configuration information. Should only be called
/// by VMs created by the Pipelines Service and not by end users.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Genomics.V1Alpha2.ControllerConfig> GetControllerConfigAsync(global::Google.Genomics.V1Alpha2.GetControllerConfigRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetControllerConfig, null, options, request);
}
/// <summary>
/// Sets status of a given operation. All timestamps are sent on each
/// call, and the whole series of events is replaced, in case
/// intermediate calls are lost. Should only be called by VMs created
/// by the Pipelines Service and not by end users.
/// </summary>
public virtual global::Google.Protobuf.WellKnownTypes.Empty SetOperationStatus(global::Google.Genomics.V1Alpha2.SetOperationStatusRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SetOperationStatus(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Sets status of a given operation. All timestamps are sent on each
/// call, and the whole series of events is replaced, in case
/// intermediate calls are lost. Should only be called by VMs created
/// by the Pipelines Service and not by end users.
/// </summary>
public virtual global::Google.Protobuf.WellKnownTypes.Empty SetOperationStatus(global::Google.Genomics.V1Alpha2.SetOperationStatusRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_SetOperationStatus, null, options, request);
}
/// <summary>
/// Sets status of a given operation. All timestamps are sent on each
/// call, and the whole series of events is replaced, in case
/// intermediate calls are lost. Should only be called by VMs created
/// by the Pipelines Service and not by end users.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> SetOperationStatusAsync(global::Google.Genomics.V1Alpha2.SetOperationStatusRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SetOperationStatusAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Sets status of a given operation. All timestamps are sent on each
/// call, and the whole series of events is replaced, in case
/// intermediate calls are lost. Should only be called by VMs created
/// by the Pipelines Service and not by end users.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> SetOperationStatusAsync(global::Google.Genomics.V1Alpha2.SetOperationStatusRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_SetOperationStatus, null, options, request);
}
protected override PipelinesV1Alpha2Client NewInstance(ClientBaseConfiguration configuration)
{
return new PipelinesV1Alpha2Client(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(PipelinesV1Alpha2Base serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_CreatePipeline, serviceImpl.CreatePipeline)
.AddMethod(__Method_RunPipeline, serviceImpl.RunPipeline)
.AddMethod(__Method_GetPipeline, serviceImpl.GetPipeline)
.AddMethod(__Method_ListPipelines, serviceImpl.ListPipelines)
.AddMethod(__Method_DeletePipeline, serviceImpl.DeletePipeline)
.AddMethod(__Method_GetControllerConfig, serviceImpl.GetControllerConfig)
.AddMethod(__Method_SetOperationStatus, serviceImpl.SetOperationStatus).Build();
}
}
}
#endregion
| |
using System;
using System.Collections.Generic;
using System.Xml;
using System.Collections;
namespace GuruComponents.Netrix.XmlDesigner.Edx
{
/// <summary>
/// Provides handy access functions to the edit view descriptor document.
/// </summary>
/// <remarks>
/// The transform document consists of multiple views within one views root.
/// Each view is represented by one instance of this class.
/// </remarks>
public class View
{
private Dictionary<string, List<Match>> aContainers; // <templatename, Container>
private Dictionary<string, Dictionary<string, string>> aContainerMaps; // <templatename, map path>
private EdxDocument edxDoc;
private XmlNode docroot;
// default to first view in the document
private XmlNode currentView;
private string currentViewName;
/// <summary>
/// Constructor for the view class.
/// </summary>
/// <param name="viewroot">Root node from native XML transform document.</param>
/// <param name="edxDoc"></param>
public View(XmlNode viewroot, EdxDocument edxDoc)
{
this.docroot = viewroot;
this.edxDoc = edxDoc;
// default to first view in the document
this.currentView = viewroot.SelectSingleNode("//edx:view", edxDoc.XmlnsEdx);
if( this.currentView == null )
{
Util.Err("No edit views found!" );
return;
}
this.currentViewName = this.currentView.SelectSingleNode( "@uiname" ).Value;
// maintain cache of container matches and maps
this.aContainers = new Dictionary<string,List<Match>>();
this.aContainerMaps = new Dictionary<string,Dictionary<string,string>>();
}
/// <summary>
/// Looks up template node for specified template.
/// </summary>
/// <param name="sTemplate"></param>
/// <returns></returns>
public XmlNode GetTemplate( string sTemplate )
{
XmlNode node = this.currentView.SelectSingleNode("//edx:template[@name = '" + sTemplate + "']", edxDoc.XmlnsEdx);
if( node == null )
{
// look for common definition
node = this.docroot.SelectSingleNode("/edx:editviews/edx:common/edx:template[@name = '" + sTemplate + "']", edxDoc.XmlnsEdx);
}
if( node == null )
{
Util.Err("No information for " + sTemplate + " template in " + this.currentViewName + " view or common view definitions." );
}
return node;
}
/// <summary>
/// Looks up type of this template ("region", "container").
/// </summary>
/// <param name="oTemplateNode"></param>
/// <returns></returns>
public TemplateType GetTemplateType(XmlNode oTemplateNode )
{
return (TemplateType)Enum.Parse(typeof(TemplateType), oTemplateNode.SelectSingleNode("@type", edxDoc.XmlnsEdx).Value, true);
}
/// <summary>
/// Get template default display name.
/// </summary>
/// <param name="oTemplateNode"></param>
/// <returns></returns>
public string GetTemplateDefaultDisplayName(XmlNode oTemplateNode )
{
XmlNode n = oTemplateNode.SelectNodes("edx:xhtml", edxDoc.XmlnsEdx)[0];
if( n == null )
{
Util.Err("Couldn't get default XHTML template." );
return "";
}
XmlAttribute s = n.Attributes[ "display" ];
if( s == null )
return "default";
else
return s.Value;
}
/// <summary>
/// Looks up template node for specified template name
/// </summary>
/// <param name="oTemplateNode"></param>
/// <param name="sName"></param>
public XmlNode GetTemplateHtmlByName(XmlNode oTemplateNode, string sName )
{
if( sName == null || sName == "default" )
return oTemplateNode.SelectSingleNode("edx:xhtml", edxDoc.XmlnsEdx); // [0] must be the first
else
return oTemplateNode.SelectSingleNode("edx:xhtml[@display = '" + sName + "']", edxDoc.XmlnsEdx);
}
/// <summary>
/// Looks up the display name for the spec'd template.
/// </summary>
/// <param name="oTemplateNode"></param>
public string GetTemplateName(XmlNode oTemplateNode )
{
XmlNode node = oTemplateNode.SelectSingleNode("@uiname", edxDoc.XmlnsEdx);
if( node == null )
{
// fall back to just the template name itself
node = oTemplateNode.SelectSingleNode("@name", edxDoc.XmlnsEdx);
}
if( node != null )
return node.Value;
else
{
Util.Err("Error: template with no name" );
return "";
}
}
/// <summary>
/// Gets list of display formats for spec'd template, e.g. default, details, hidden, etc.
/// </summary>
/// <param name="oTemplateNode"></param>
/// <returns></returns>
public List<string> GetDisplays(XmlNode oTemplateNode )
{
XmlNodeList nodes = oTemplateNode.SelectNodes("edx:xhtml", edxDoc.XmlnsEdx);
List<string> a = new List<string>();
for(int i = 0; i < nodes.Count; i++ )
{
XmlNode n = nodes[i].SelectSingleNode("@display", edxDoc.XmlnsEdx);
if( n != null )
a.Add(n.Value);
}
return a;
}
/// <summary>
/// Returns an array of objects describing each of the matches on the spec'd container.
/// </summary>
/// <param name="sTemplate"></param>
public List<Match> GetContainerMatches(string sTemplate)
{
// check for cached copy
if( aContainers[sTemplate] != null )
return aContainers[sTemplate];
XmlNode oTemplateNode = GetTemplate( sTemplate );
if( oTemplateNode == null )
{
Util.Err("getContainerMatches: no template found for '" + sTemplate + "'" );
return null;
}
XmlNodeList nodes = oTemplateNode.SelectNodes( "edx:match", edxDoc.XmlnsEdx );
List<Match> a = new List<Match>();
for(int i = 0; i < nodes.Count; i++ )
{
string sTag = (nodes[i].Attributes[ "element" ] == null) ? null : nodes[i].Attributes[ "element" ].Value;
if( sTag != null )
{
// get template name from XHTML node
if( nodes[i].ChildNodes.Count != 1 )
{
Util.Err("getContainerMatches: a match must contain one and only one HTML node inside the match spec, tag = " + sTag );
return null;
}
string sMatchTemplate = (nodes[i].ChildNodes[0].Attributes[ "edxtemplate" ] == null) ? null : nodes[i].ChildNodes[0].Attributes[ "edxtemplate" ].Value;
if( sMatchTemplate == null )
{
Util.Err("getContainerMatches: no edxtemplate spec'd for match on tag " + sTag );
return null;
}
// got candidate, check it's template for XML insert fragment
XmlNode oins = this.currentView.SelectSingleNode("edx:template[@name='" + sMatchTemplate + "']", edxDoc.XmlnsEdx);
if( oins != null )
{
// got a fragment?
if (oins.SelectSingleNode("edx:insert", edxDoc.XmlnsEdx) != null)
{
string sUI = (oins.Attributes[ "uiname" ] == null) ? null : oins.Attributes[ "uiname" ].Value;
if( sUI == null )
sUI = sTag;
// create a full match spec
Match oMatch = new Match( sTag, sMatchTemplate, sUI, oins );
a.Add(oMatch);
}
}
}
}
// preserve for future
aContainers[sTemplate] = a;
return a;
}
/// <summary>
/// Looks for or builds a tag map for spec'd container template.
/// </summary>
/// <param name="sTemplate"></param>
public Dictionary<string, string> GetContainerMap(string sTemplate)
{
if (aContainerMaps[sTemplate] == null)
{
CompileContainerMap(sTemplate);
}
return aContainerMaps[sTemplate];
}
/// <summary>
/// Compiles a tag map for spec'd container template.
/// </summary>
/// <param name="sTemplate"></param>
public void CompileContainerMap(string sTemplate )
{
// look up template
XmlNode oTemp = GetTemplate( sTemplate );
if( oTemp == null )
return;
// see what type we have
TemplateType sType = GetTemplateType( oTemp );
if( sType == TemplateType.Container )
{
// parse container match contents
XmlNodeList nodes = oTemp.SelectNodes("edx:match", edxDoc.XmlnsEdx);
// make sure we have some matches
if( nodes.Count == 0 )
{
// pretty dumb container, but maybe it's a development stub, no error
//aContainerMaps[sTemplate] = "*"; // show no sub-containment
aContainerMaps[sTemplate] = new Dictionary<string, string>();
aContainerMaps[sTemplate]["*"] = null;
return;
}
// put an empty map in place to keep us from trying to compile ourselves
Dictionary<string, string> a = new Dictionary<string,string>();
aContainerMaps[sTemplate] = a;
// parse matched element list
for(int i = 0; i < nodes.Count; i++ )
{
XmlNode n = nodes[i];
string sTag = n.Attributes[ "element" ].Value;
if( sTag == null || sTag == "" )
{
Util.Err("Bad match spec in container '" + sTemplate + "'. Must specify element to match." );
continue;
}
// verify we see one and only one node of XHTML inside the match
if( n.ChildNodes.Count != 1 )
{
Util.Err("Bad XHTML spec for match on tag '" + sTag + "'. Must contain one and only one node of XHTML." );
continue;
}
// get the XHTML node for this match
XmlNode oXhtml = n.ChildNodes[0];
// get the template and options (if spec'd)
string sTmp = (oXhtml.Attributes[ "edxtemplate" ] == null) ? null : oXhtml.Attributes[ "edxtemplate" ].Value;
if( sTmp == null || sTmp == "" )
{
// must not be a "live" node, just show as end of line
a[sTag] = "*";
continue;
}
// figure out if splittable
bool bSplit;
if( sTmp.Substring( 0, 6 ) == "field:" )
{
a[sTag] = "*";
continue;
}
else if( sTmp.Substring( 0, 7 ) == "widget:" )
{
a[sTag] = "*";
continue;
}
else if( GetTemplateType( GetTemplate( sTmp ) ) == TemplateType.Container )
bSplit = true;
else
bSplit = false;
// see if explicit options say otherwise
string sOptions = (oXhtml.Attributes[ "edxoptions" ] == null) ? null : oXhtml.Attributes[ "edxoptions" ].Value;
if( sOptions != null && sOptions != "" )
{
IList aOps = Util.ParseOptions( sOptions );
for(int j = 0; j < aOps.Count; j++ )
{
if( ((Option) aOps[j]).Name == "allow-split" && ((Option) aOps[j]).Value == "true" )
{
bSplit = true;
break;
}
}
}
// if it's not splittable, end of the line
if( !bSplit )
{
a[sTag] = "*";
continue;
}
// descend into it
GetContainerMap( sTmp );
// a[sTag] = aContainerMaps[sTmp];
}
// note: our map is already in place, we're done
}
else
{
// must be wrapper region, look inside default XHTML for a container
XmlNode oXhtml = GetTemplateHtmlByName( oTemp, null );
if( oXhtml == null )
return;
// get all nodes with edxtemplates
XmlNodeList nodes = oXhtml.SelectNodes(".//*[@edxtemplate != '']", edxDoc.XmlnsEdx);
// look for a nested container
string sCont = null;
for(int i = 0; i < nodes.Count; i++ )
{
XmlNode n = nodes[i];
string sTemp = (n.Attributes[ "edxtemplate" ] == null) ? null : n.Attributes[ "edxtemplate" ].Value;
if( sTemp.StartsWith("field:") || sTemp.StartsWith("widget:"))
continue;
XmlNode oTmp = GetTemplate( sTemp );
if( oTmp == null )
{
Util.Err("No template found for edxtemplate '" + sTemp + "'" );
return;
}
if( GetTemplateType( oTmp ) == TemplateType.Container )
{
if( sCont != null )
{
Util.Err("Can't have two containers in a splittable region: " + sTemplate );
return;
}
sCont = sTemp;
}
}
if( sCont == null )
{
// not an error, just the end of the line. we mark this tag
// to show we've visited it
aContainerMaps[sTemplate] = new Dictionary<string, string>(); // "*";
}
else
{
// descend into this container (if necessary)
GetContainerMap( sCont );
// and we ourselves share that map then since we're merely a wrapper for it
aContainerMaps[sTemplate] = aContainerMaps[sCont];
}
}
}
}
}
| |
// Copyright (c) 2013-2018 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Runtime.InteropServices;
using Icu.Normalization;
namespace Icu
{
internal static partial class NativeMethods
{
private class NormalizeMethodsContainer
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
internal delegate int unorm_normalizeDelegate(string source, int sourceLength,
Normalizer.UNormalizationMode mode, int options,
IntPtr result, int resultLength, out ErrorCode errorCode);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
internal delegate byte unorm_isNormalizedDelegate(string source, int sourceLength,
Normalizer.UNormalizationMode mode, out ErrorCode errorCode);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
internal delegate IntPtr unorm2_getInstanceDelegate(
[MarshalAs(UnmanagedType.LPStr)] string packageName,
[MarshalAs(UnmanagedType.LPStr)] string name,
Normalizer2.Mode mode, out ErrorCode errorCode);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
internal delegate int unorm2_normalizeDelegate(IntPtr norm2, string source,
int sourceLength, IntPtr dest, int capacity, ref ErrorCode errorCode);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.I1)]
internal delegate bool unorm2_isNormalizedDelegate(IntPtr norm2, string source,
int sourceLength, out ErrorCode errorCode);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.I1)]
internal delegate bool unorm2_hasBoundaryAfterDelegate(IntPtr norm2, int c);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.I1)]
internal delegate bool unorm2_hasBoundaryBeforeDelegate(IntPtr norm2, int c);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
internal delegate int unorm2_getDecompositionDelegate(IntPtr norm2, int c,
IntPtr decomposition, int capacity, out ErrorCode errorCode);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
internal delegate int unorm2_getRawDecompositionDelegate(IntPtr norm2, int c,
IntPtr decomposition, int capacity, out ErrorCode errorCode);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
internal delegate int unorm2_getCombiningClassDelegate(IntPtr norm2, int c);
internal unorm_normalizeDelegate unorm_normalize;
internal unorm_isNormalizedDelegate unorm_isNormalized;
internal unorm2_getInstanceDelegate unorm2_getInstance;
internal unorm2_normalizeDelegate unorm2_normalize;
internal unorm2_isNormalizedDelegate unorm2_isNormalized;
internal unorm2_hasBoundaryAfterDelegate unorm2_hasBoundaryAfter;
internal unorm2_hasBoundaryBeforeDelegate unorm2_hasBoundaryBefore;
internal unorm2_getDecompositionDelegate unorm2_getDecomposition;
internal unorm2_getRawDecompositionDelegate unorm2_getRawDecomposition;
internal unorm2_getCombiningClassDelegate unorm2_getCombiningClass;
}
private static NormalizeMethodsContainer _NormalizeMethods;
private static NormalizeMethodsContainer NormalizeMethods =>
_NormalizeMethods ??
(_NormalizeMethods = new NormalizeMethodsContainer());
#region normalize
/// <summary>
/// Normalize a string according to the given mode and options.
/// </summary>
public static int unorm_normalize(string source, int sourceLength,
Normalizer.UNormalizationMode mode, int options,
IntPtr result, int resultLength, out ErrorCode errorCode)
{
errorCode = ErrorCode.NoErrors;
if (NormalizeMethods.unorm_normalize == null)
NormalizeMethods.unorm_normalize = GetMethod<NormalizeMethodsContainer.unorm_normalizeDelegate>(IcuCommonLibHandle, "unorm_normalize");
return NormalizeMethods.unorm_normalize(source, sourceLength, mode, options, result,
resultLength, out errorCode);
}
// Note that ICU's UBool type is typedef to an 8-bit integer.
/// <summary>
/// Check whether a string is normalized according to the given mode and options.
/// </summary>
public static byte unorm_isNormalized(string source, int sourceLength,
Normalizer.UNormalizationMode mode, out ErrorCode errorCode)
{
errorCode = ErrorCode.NoErrors;
if (NormalizeMethods.unorm_isNormalized == null)
NormalizeMethods.unorm_isNormalized = GetMethod<NormalizeMethodsContainer.unorm_isNormalizedDelegate>(IcuCommonLibHandle, "unorm_isNormalized");
return NormalizeMethods.unorm_isNormalized(source, sourceLength, mode, out errorCode);
}
#endregion normalize
#region normalize2
/// <summary>
/// Returns a UNormalizer2 instance which uses the specified data file (packageName/name
/// similar to ucnv_openPackage() and ures_open()/ResourceBundle) and which composes or
/// decomposes text according to the specified mode.
/// </summary>
public static IntPtr unorm2_getInstance(string packageName, string name,
Normalizer2.Mode mode, out ErrorCode errorCode)
{
errorCode = ErrorCode.NoErrors;
if (NormalizeMethods.unorm2_getInstance == null)
{
NormalizeMethods.unorm2_getInstance = GetMethod<NormalizeMethodsContainer.unorm2_getInstanceDelegate>(
IcuCommonLibHandle, "unorm2_getInstance");
}
return NormalizeMethods.unorm2_getInstance(packageName, name, mode, out errorCode);
}
/// <summary>
/// Normalize a string according to the given mode and options.
/// </summary>
public static int unorm2_normalize(IntPtr norm2, string source, int sourceLength,
IntPtr result, int resultLength, out ErrorCode errorCode)
{
errorCode = ErrorCode.NoErrors;
if (NormalizeMethods.unorm2_normalize == null)
{
NormalizeMethods.unorm2_normalize = GetMethod<NormalizeMethodsContainer.unorm2_normalizeDelegate>(
IcuCommonLibHandle, "unorm2_normalize");
}
// Theoretically it should be unnecessary to initialize errorCode here. Instead we
// should be able to use `out` instead. However, there seems to be a bug somewhere:
// if this method gets called twice and errorCode != NoErrors, the error code won't
// get reset, even though the method seems to work without errors.
errorCode = ErrorCode.NoErrors;
return NormalizeMethods.unorm2_normalize(norm2, source, sourceLength, result,
resultLength, ref errorCode);
}
// Note that ICU's UBool type is typedef to an 8-bit integer.
/// <summary>
/// Check whether a string is normalized according to the given mode and options.
/// </summary>
public static bool unorm2_isNormalized(IntPtr norm2, string source, int sourceLength,
out ErrorCode errorCode)
{
errorCode = ErrorCode.NoErrors;
if (NormalizeMethods.unorm2_isNormalized == null)
{
NormalizeMethods.unorm2_isNormalized = GetMethod<NormalizeMethodsContainer.unorm2_isNormalizedDelegate>(
IcuCommonLibHandle, "unorm2_isNormalized");
}
return NormalizeMethods.unorm2_isNormalized(norm2, source, sourceLength, out errorCode);
}
/// <summary>Tests if the character always has a normalization boundary after it,
/// regardless of context.</summary>
public static bool unorm2_hasBoundaryAfter(IntPtr norm2, int codePoint)
{
if (NormalizeMethods.unorm2_hasBoundaryAfter == null)
{
NormalizeMethods.unorm2_hasBoundaryAfter = GetMethod<NormalizeMethodsContainer.unorm2_hasBoundaryAfterDelegate>(
IcuCommonLibHandle, nameof(unorm2_hasBoundaryAfter));
}
return NormalizeMethods.unorm2_hasBoundaryAfter(norm2, codePoint);
}
/// <summary>Tests if the character always has a normalization boundary before it,
/// regardless of context.</summary>
public static bool unorm2_hasBoundaryBefore(IntPtr norm2, int codePoint)
{
if (NormalizeMethods.unorm2_hasBoundaryBefore == null)
{
NormalizeMethods.unorm2_hasBoundaryBefore = GetMethod<NormalizeMethodsContainer.unorm2_hasBoundaryBeforeDelegate>(
IcuCommonLibHandle, nameof(unorm2_hasBoundaryBefore));
}
return NormalizeMethods.unorm2_hasBoundaryBefore(norm2, codePoint);
}
/// <summary>Gets the decomposition mapping of c.</summary>
public static int unorm2_getDecomposition(IntPtr norm2, int c, IntPtr decomposition,
int capacity, out ErrorCode errorCode)
{
errorCode = ErrorCode.NoErrors;
if (NormalizeMethods.unorm2_getDecomposition == null)
{
NormalizeMethods.unorm2_getDecomposition = GetMethod<NormalizeMethodsContainer.unorm2_getDecompositionDelegate>(
IcuCommonLibHandle, nameof(unorm2_getDecomposition));
}
return NormalizeMethods.unorm2_getDecomposition(norm2, c, decomposition, capacity,
out errorCode);
}
/// <summary>Gets the raw decomposition mapping of c.</summary>
public static int unorm2_getRawDecomposition(IntPtr norm2, int c, IntPtr decomposition,
int capacity, out ErrorCode errorCode)
{
errorCode = ErrorCode.NoErrors;
if (NormalizeMethods.unorm2_getRawDecomposition == null)
{
NormalizeMethods.unorm2_getRawDecomposition = GetMethod<NormalizeMethodsContainer.unorm2_getRawDecompositionDelegate>(
IcuCommonLibHandle, nameof(unorm2_getRawDecomposition));
}
return NormalizeMethods.unorm2_getRawDecomposition(norm2, c, decomposition, capacity,
out errorCode);
}
/// <summary>Gets the combining class of c. </summary>
public static int unorm2_getCombiningClass(IntPtr norm2, int c)
{
if (NormalizeMethods.unorm2_getCombiningClass == null)
{
NormalizeMethods.unorm2_getCombiningClass = GetMethod<NormalizeMethodsContainer.unorm2_getCombiningClassDelegate>(
IcuCommonLibHandle, nameof(unorm2_getCombiningClass));
}
return NormalizeMethods.unorm2_getCombiningClass(norm2, c);
}
#endregion normalize2
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\GameNetworkManager.h:27
namespace UnrealEngine
{
[ManageType("ManageGameNetworkManager")]
public partial class ManageGameNetworkManager : AGameNetworkManager, IManageWrapper
{
public ManageGameNetworkManager(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_EnableStandbyCheatDetection(IntPtr self, bool bIsEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_UpdateNetSpeeds(IntPtr self, bool bIsLanMatch);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_UpdateNetSpeedsTimer(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_BeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_ClearCrossLevelReferences(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_Destroyed(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_ForceNetRelevant(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_ForceNetUpdate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_GatherCurrentMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_InvalidateLightingCacheDetailed(IntPtr self, bool bTranslationOnly);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_K2_DestroyActor(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_LifeSpanExpired(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_MarkComponentsAsPendingKill(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_NotifyActorBeginCursorOver(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_NotifyActorEndCursorOver(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_OnRep_AttachmentReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_OnRep_Instigator(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_OnRep_Owner(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_OnRep_ReplicatedMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_OnRep_ReplicateMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_OnReplicationPausedChanged(IntPtr self, bool bIsReplicationPaused);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_OutsideWorldBounds(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostActorCreated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostInitializeComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostNetInit(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostNetReceiveLocationAndRotation(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostNetReceivePhysicState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostNetReceiveRole(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostRegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostUnregisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PreInitializeComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PreRegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PrestreamTextures(IntPtr self, float seconds, bool bEnableStreaming, int cinematicTextureGroups);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_RegisterActorTickFunctions(IntPtr self, bool bRegister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_RegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_ReregisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_RerunConstructionScripts(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_Reset(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_RewindForReplay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_SetActorHiddenInGame(IntPtr self, bool bNewHidden);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_SetLifeSpan(IntPtr self, float inLifespan);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_SetReplicateMovement(IntPtr self, bool bInReplicateMovement);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_TearOff(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_TeleportSucceeded(IntPtr self, bool bIsATest);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_Tick(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_TornOff(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_UnregisterAllComponents(IntPtr self, bool bForReregister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameNetworkManager_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
/// <summary>
/// Turns standby detection on/off
/// </summary>
/// <param name="bIsEnabled">true to turn it on, false to disable it</param>
public override void EnableStandbyCheatDetection(bool bIsEnabled)
=> E__Supper__AGameNetworkManager_EnableStandbyCheatDetection(this, bIsEnabled);
/// <summary>
/// Update network speeds for listen servers based on number of connected players.
/// </summary>
public override void UpdateNetSpeeds(bool bIsLanMatch)
=> E__Supper__AGameNetworkManager_UpdateNetSpeeds(this, bIsLanMatch);
/// <summary>
/// Timer which calls UpdateNetSpeeds() once a second.
/// </summary>
public override void UpdateNetSpeedsTimer()
=> E__Supper__AGameNetworkManager_UpdateNetSpeedsTimer(this);
/// <summary>
/// Overridable native event for when play begins for this actor.
/// </summary>
protected override void BeginPlay()
=> E__Supper__AGameNetworkManager_BeginPlay(this);
/// <summary>
/// Do anything needed to clear out cross level references; Called from ULevel::PreSave
/// </summary>
public override void ClearCrossLevelReferences()
=> E__Supper__AGameNetworkManager_ClearCrossLevelReferences(this);
/// <summary>
/// Called when this actor is explicitly being destroyed during gameplay or in the editor, not called during level streaming or gameplay ending
/// </summary>
public override void Destroyed()
=> E__Supper__AGameNetworkManager_Destroyed(this);
/// <summary>
/// Forces this actor to be net relevant if it is not already by default
/// </summary>
public override void ForceNetRelevant()
=> E__Supper__AGameNetworkManager_ForceNetRelevant(this);
/// <summary>
/// Force actor to be updated to clients/demo net drivers
/// </summary>
public override void ForceNetUpdate()
=> E__Supper__AGameNetworkManager_ForceNetUpdate(this);
/// <summary>
/// Fills ReplicatedMovement property
/// </summary>
public override void GatherCurrentMovement()
=> E__Supper__AGameNetworkManager_GatherCurrentMovement(this);
/// <summary>
/// Invalidates anything produced by the last lighting build.
/// </summary>
public override void InvalidateLightingCacheDetailed(bool bTranslationOnly)
=> E__Supper__AGameNetworkManager_InvalidateLightingCacheDetailed(this, bTranslationOnly);
/// <summary>
/// Destroy the actor
/// </summary>
public override void DestroyActor()
=> E__Supper__AGameNetworkManager_K2_DestroyActor(this);
/// <summary>
/// Called when the lifespan of an actor expires (if he has one).
/// </summary>
public override void LifeSpanExpired()
=> E__Supper__AGameNetworkManager_LifeSpanExpired(this);
/// <summary>
/// Called to mark all components as pending kill when the actor is being destroyed
/// </summary>
public override void MarkComponentsAsPendingKill()
=> E__Supper__AGameNetworkManager_MarkComponentsAsPendingKill(this);
/// <summary>
/// Event when this actor has the mouse moved over it with the clickable interface.
/// </summary>
public override void NotifyActorBeginCursorOver()
=> E__Supper__AGameNetworkManager_NotifyActorBeginCursorOver(this);
/// <summary>
/// Event when this actor has the mouse moved off of it with the clickable interface.
/// </summary>
public override void NotifyActorEndCursorOver()
=> E__Supper__AGameNetworkManager_NotifyActorEndCursorOver(this);
public override void OnRep_AttachmentReplication()
=> E__Supper__AGameNetworkManager_OnRep_AttachmentReplication(this);
public override void OnRep_Instigator()
=> E__Supper__AGameNetworkManager_OnRep_Instigator(this);
protected override void OnRep_Owner()
=> E__Supper__AGameNetworkManager_OnRep_Owner(this);
public override void OnRep_ReplicatedMovement()
=> E__Supper__AGameNetworkManager_OnRep_ReplicatedMovement(this);
public override void OnRep_ReplicateMovement()
=> E__Supper__AGameNetworkManager_OnRep_ReplicateMovement(this);
/// <summary>
/// Called on the client when the replication paused value is changed
/// </summary>
public override void OnReplicationPausedChanged(bool bIsReplicationPaused)
=> E__Supper__AGameNetworkManager_OnReplicationPausedChanged(this, bIsReplicationPaused);
/// <summary>
/// Called when the Actor is outside the hard limit on world bounds
/// </summary>
public override void OutsideWorldBounds()
=> E__Supper__AGameNetworkManager_OutsideWorldBounds(this);
/// <summary>
/// Called when an actor is done spawning into the world (from UWorld::SpawnActor), both in the editor and during gameplay
/// <para>For actors with a root component, the location and rotation will have already been set. </para>
/// This is called before calling construction scripts, but after native components have been created
/// </summary>
public override void PostActorCreated()
=> E__Supper__AGameNetworkManager_PostActorCreated(this);
/// <summary>
/// Allow actors to initialize themselves on the C++ side after all of their components have been initialized, only called during gameplay
/// </summary>
public override void PostInitializeComponents()
=> E__Supper__AGameNetworkManager_PostInitializeComponents(this);
/// <summary>
/// Always called immediately after spawning and reading in replicated properties
/// </summary>
public override void PostNetInit()
=> E__Supper__AGameNetworkManager_PostNetInit(this);
/// <summary>
/// Update location and rotation from ReplicatedMovement. Not called for simulated physics!
/// </summary>
public override void PostNetReceiveLocationAndRotation()
=> E__Supper__AGameNetworkManager_PostNetReceiveLocationAndRotation(this);
/// <summary>
/// Update and smooth simulated physic state, replaces PostNetReceiveLocation() and PostNetReceiveVelocity()
/// </summary>
public override void PostNetReceivePhysicState()
=> E__Supper__AGameNetworkManager_PostNetReceivePhysicState(this);
/// <summary>
/// Always called immediately after a new Role is received from the remote.
/// </summary>
public override void PostNetReceiveRole()
=> E__Supper__AGameNetworkManager_PostNetReceiveRole(this);
/// <summary>
/// Called after all the components in the Components array are registered, called both in editor and during gameplay
/// </summary>
public override void PostRegisterAllComponents()
=> E__Supper__AGameNetworkManager_PostRegisterAllComponents(this);
/// <summary>
/// Called after all currently registered components are cleared
/// </summary>
public override void PostUnregisterAllComponents()
=> E__Supper__AGameNetworkManager_PostUnregisterAllComponents(this);
/// <summary>
/// Called right before components are initialized, only called during gameplay
/// </summary>
public override void PreInitializeComponents()
=> E__Supper__AGameNetworkManager_PreInitializeComponents(this);
/// <summary>
/// Called before all the components in the Components array are registered, called both in editor and during gameplay
/// </summary>
public override void PreRegisterAllComponents()
=> E__Supper__AGameNetworkManager_PreRegisterAllComponents(this);
/// <summary>
/// Calls PrestreamTextures() for all the actor's meshcomponents.
/// </summary>
/// <param name="seconds">Number of seconds to force all mip-levels to be resident</param>
/// <param name="bEnableStreaming">Whether to start (true) or stop (false) streaming</param>
/// <param name="cinematicTextureGroups">Bitfield indicating which texture groups that use extra high-resolution mips</param>
public override void PrestreamTextures(float seconds, bool bEnableStreaming, int cinematicTextureGroups)
=> E__Supper__AGameNetworkManager_PrestreamTextures(this, seconds, bEnableStreaming, cinematicTextureGroups);
/// <summary>
/// Virtual call chain to register all tick functions for the actor class hierarchy
/// </summary>
/// <param name="bRegister">true to register, false, to unregister</param>
protected override void RegisterActorTickFunctions(bool bRegister)
=> E__Supper__AGameNetworkManager_RegisterActorTickFunctions(this, bRegister);
/// <summary>
/// Ensure that all the components in the Components array are registered
/// </summary>
public override void RegisterAllComponents()
=> E__Supper__AGameNetworkManager_RegisterAllComponents(this);
/// <summary>
/// Will reregister all components on this actor. Does a lot of work - should only really be used in editor, generally use UpdateComponentTransforms or MarkComponentsRenderStateDirty.
/// </summary>
public override void ReregisterAllComponents()
=> E__Supper__AGameNetworkManager_ReregisterAllComponents(this);
/// <summary>
/// Rerun construction scripts, destroying all autogenerated components; will attempt to preserve the root component location.
/// </summary>
public override void RerunConstructionScripts()
=> E__Supper__AGameNetworkManager_RerunConstructionScripts(this);
/// <summary>
/// Reset actor to initial state - used when restarting level without reloading.
/// </summary>
public override void Reset()
=> E__Supper__AGameNetworkManager_Reset(this);
/// <summary>
/// Called on the actor before checkpoint data is applied during a replay.
/// <para>Only called if bReplayRewindable is set. </para>
/// </summary>
public override void RewindForReplay()
=> E__Supper__AGameNetworkManager_RewindForReplay(this);
/// <summary>
/// Sets the actor to be hidden in the game
/// </summary>
/// <param name="bNewHidden">Whether or not to hide the actor and all its components</param>
public override void SetActorHiddenInGame(bool bNewHidden)
=> E__Supper__AGameNetworkManager_SetActorHiddenInGame(this, bNewHidden);
/// <summary>
/// Set the lifespan of this actor. When it expires the object will be destroyed. If requested lifespan is 0, the timer is cleared and the actor will not be destroyed.
/// </summary>
public override void SetLifeSpan(float inLifespan)
=> E__Supper__AGameNetworkManager_SetLifeSpan(this, inLifespan);
/// <summary>
/// Set whether this actor's movement replicates to network clients.
/// </summary>
/// <param name="bInReplicateMovement">Whether this Actor's movement replicates to clients.</param>
public override void SetReplicateMovement(bool bInReplicateMovement)
=> E__Supper__AGameNetworkManager_SetReplicateMovement(this, bInReplicateMovement);
/// <summary>
/// Networking - Server - TearOff this actor to stop replication to clients. Will set bTearOff to true.
/// </summary>
public override void TearOff()
=> E__Supper__AGameNetworkManager_TearOff(this);
/// <summary>
/// Called from TeleportTo() when teleport succeeds
/// </summary>
public override void TeleportSucceeded(bool bIsATest)
=> E__Supper__AGameNetworkManager_TeleportSucceeded(this, bIsATest);
/// <summary>
/// Function called every frame on this Actor. Override this function to implement custom logic to be executed every frame.
/// <para>Note that Tick is disabled by default, and you will need to check PrimaryActorTick.bCanEverTick is set to true to enable it. </para>
/// </summary>
/// <param name="deltaSeconds">Game time elapsed during last frame modified by the time dilation</param>
public override void Tick(float deltaSeconds)
=> E__Supper__AGameNetworkManager_Tick(this, deltaSeconds);
/// <summary>
/// Networking - called on client when actor is torn off (bTearOff==true), meaning it's no longer replicated to clients.
/// <para>@see bTearOff </para>
/// </summary>
public override void TornOff()
=> E__Supper__AGameNetworkManager_TornOff(this);
/// <summary>
/// Unregister all currently registered components
/// </summary>
/// <param name="bForReregister">If true, RegisterAllComponents will be called immediately after this so some slow operations can be avoided</param>
public override void UnregisterAllComponents(bool bForReregister)
=> E__Supper__AGameNetworkManager_UnregisterAllComponents(this, bForReregister);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__AGameNetworkManager_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__AGameNetworkManager_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__AGameNetworkManager_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__AGameNetworkManager_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__AGameNetworkManager_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__AGameNetworkManager_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__AGameNetworkManager_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__AGameNetworkManager_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__AGameNetworkManager_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__AGameNetworkManager_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__AGameNetworkManager_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__AGameNetworkManager_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__AGameNetworkManager_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__AGameNetworkManager_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__AGameNetworkManager_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageGameNetworkManager self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageGameNetworkManager(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageGameNetworkManager>(PtrDesc);
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComUtils.Admin.DS
{
public class sys_RoleProductDS
{
public sys_RoleProductDS()
{
}
private const string THIS = "PCSComUtils.Admin.DS.sys_RoleProductDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to sys_RoleProduct
/// </Description>
/// <Inputs>
/// sys_RoleProductVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, November 16, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
sys_RoleProductVO objObject = (sys_RoleProductVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO sys_RoleProduct("
+ sys_RoleProductTable.ROLEID_FLD + ","
+ sys_RoleProductTable.PRODUCTID_FLD + ")"
+ "VALUES(?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(sys_RoleProductTable.ROLEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_RoleProductTable.ROLEID_FLD].Value = objObject.RoleID;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_RoleProductTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_RoleProductTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from sys_RoleProduct
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + sys_RoleProductTable.TABLE_NAME + " WHERE " + "RoleProductID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// DeleteByProductID
/// </summary>
/// <param name="pintProductID"></param>
/// <author>Trada</author>
/// <date>Thursday, Nov 17 2005</date>
public void DeleteByProductID(int pintProductID)
{
const string METHOD_NAME = THIS + ".DeleteByProductID()";
string strSql = String.Empty;
strSql= "DELETE " + sys_RoleProductTable.TABLE_NAME + " WHERE "
+ sys_RoleProductTable.PRODUCTID_FLD + "=" + pintProductID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from sys_RoleProduct
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// sys_RoleProductVO
/// </Outputs>
/// <Returns>
/// sys_RoleProductVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, November 16, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ sys_RoleProductTable.ROLEPRODUCTID_FLD + ","
+ sys_RoleProductTable.ROLEID_FLD + ","
+ sys_RoleProductTable.PRODUCTID_FLD
+ " FROM " + sys_RoleProductTable.TABLE_NAME
+" WHERE " + sys_RoleProductTable.ROLEPRODUCTID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
sys_RoleProductVO objObject = new sys_RoleProductVO();
while (odrPCS.Read())
{
objObject.RoleProductID = int.Parse(odrPCS[sys_RoleProductTable.ROLEPRODUCTID_FLD].ToString().Trim());
objObject.RoleID = int.Parse(odrPCS[sys_RoleProductTable.ROLEID_FLD].ToString().Trim());
objObject.ProductID = int.Parse(odrPCS[sys_RoleProductTable.PRODUCTID_FLD].ToString().Trim());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to sys_RoleProduct
/// </Description>
/// <Inputs>
/// sys_RoleProductVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
sys_RoleProductVO objObject = (sys_RoleProductVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE sys_RoleProduct SET "
+ sys_RoleProductTable.ROLEID_FLD + "= ?" + ","
+ sys_RoleProductTable.PRODUCTID_FLD + "= ?"
+" WHERE " + sys_RoleProductTable.ROLEPRODUCTID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(sys_RoleProductTable.ROLEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_RoleProductTable.ROLEID_FLD].Value = objObject.RoleID;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_RoleProductTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_RoleProductTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_RoleProductTable.ROLEPRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_RoleProductTable.ROLEPRODUCTID_FLD].Value = objObject.RoleProductID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from sys_RoleProduct
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, November 16, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ sys_RoleProductTable.ROLEPRODUCTID_FLD + ","
+ sys_RoleProductTable.ROLEID_FLD + ","
+ sys_RoleProductTable.PRODUCTID_FLD
+ " FROM " + sys_RoleProductTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,sys_RoleProductTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// GetDataByRoleID
/// </summary>
/// <param name="pintRoleID"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Thursday, Nov 17 2005</date>
public DataTable GetDataByRoleID(int pintRoleID)
{
const string METHOD_NAME = THIS + ".GetDataByRoleID()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ sys_RoleProductTable.ROLEPRODUCTID_FLD + ","
+ sys_RoleProductTable.ROLEID_FLD + ","
+ sys_RoleProductTable.PRODUCTID_FLD
+ " FROM " + sys_RoleProductTable.TABLE_NAME
+ " WHERE " + sys_RoleProductTable.ROLEID_FLD + " = " + pintRoleID.ToString();
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,sys_RoleProductTable.TABLE_NAME);
return dstPCS.Tables[0];
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// CheckHasID
/// </summary>
/// <param name="pintProductID"></param>
/// <param name="pintRoleID"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Thursday, Nov 17 2005</date>
public bool CheckHasID(int pintProductID, int pintRoleID)
{
const string METHOD_NAME = THIS + ".CheckHasID()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ sys_RoleProductTable.ROLEPRODUCTID_FLD + ","
+ sys_RoleProductTable.ROLEID_FLD + ","
+ sys_RoleProductTable.PRODUCTID_FLD
+ " FROM " + sys_RoleProductTable.TABLE_NAME
+ " WHERE " + sys_RoleProductTable.PRODUCTID_FLD + " = " + pintProductID.ToString()
+ " AND " + sys_RoleProductTable.ROLEID_FLD + " = " + pintRoleID.ToString();
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,sys_RoleProductTable.TABLE_NAME);
if (dstPCS.Tables[0].Rows.Count > 0)
{
return true;
}
else
return false;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, November 16, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ sys_RoleProductTable.ROLEPRODUCTID_FLD + ","
+ sys_RoleProductTable.ROLEID_FLD + ","
+ sys_RoleProductTable.PRODUCTID_FLD
+ " FROM " + sys_RoleProductTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,sys_RoleProductTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if(ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
namespace System.IO {
// ABOUT:
// Helps with path normalization; support allocating on the stack or heap
//
// PathHelper can't stackalloc the array for obvious reasons; you must pass
// in an array of chars allocated on the stack.
//
// USAGE:
// Suppose you need to represent a char array of length len. Then this is the
// suggested way to instantiate PathHelper:
// ***************************************************************************
// PathHelper pathHelper;
// if (charArrayLength less than stack alloc threshold == Path.MaxPath)
// char* arrayPtr = stackalloc char[Path.MaxPath];
// pathHelper = new PathHelper(arrayPtr);
// else
// pathHelper = new PathHelper(capacity, maxPath);
// ***************************************************************************
//
// note in the StringBuilder ctor:
// - maxPath may be greater than Path.MaxPath (for isolated storage)
// - capacity may be greater than maxPath. This is even used for non-isolated
// storage scenarios where we want to temporarily allow strings greater
// than Path.MaxPath if they can be normalized down to Path.MaxPath. This
// can happen if the path contains escape characters "..".
//
unsafe internal struct PathHelper { // should not be serialized
// maximum size, max be greater than max path if contains escape sequence
private int m_capacity;
// current length (next character position)
private int m_length;
// max path, may be less than capacity
private int m_maxPath;
// ptr to stack alloc'd array of chars
[SecurityCritical]
private char* m_arrayPtr;
// StringBuilder
private StringBuilder m_sb;
// whether to operate on stack alloc'd or heap alloc'd array
private bool useStackAlloc;
// Whether to skip calls to Win32Native.GetLongPathName becasue we tried before and failed:
private bool doNotTryExpandShortFileName;
// Instantiates a PathHelper with a stack alloc'd array of chars
[System.Security.SecurityCritical]
internal PathHelper(char* charArrayPtr, int length) {
Contract.Requires(charArrayPtr != null);
// force callers to be aware of this
Contract.Requires(length == Path.MaxPath);
this.m_length = 0;
this.m_sb = null;
this.m_arrayPtr = charArrayPtr;
this.m_capacity = length;
this.m_maxPath = Path.MaxPath;
useStackAlloc = true;
doNotTryExpandShortFileName = false;
}
// Instantiates a PathHelper with a heap alloc'd array of ints. Will create a StringBuilder
[System.Security.SecurityCritical]
internal PathHelper(int capacity, int maxPath)
{
this.m_length = 0;
this.m_arrayPtr = null;
this.useStackAlloc = false;
this.m_sb = new StringBuilder(capacity);
this.m_capacity = capacity;
this.m_maxPath = maxPath;
doNotTryExpandShortFileName = false;
}
internal int Length {
get {
if (useStackAlloc) {
return m_length;
}
else {
return m_sb.Length;
}
}
set {
if (useStackAlloc) {
m_length = value;
}
else {
m_sb.Length = value;
}
}
}
internal int Capacity {
get {
return m_capacity;
}
}
internal char this[int index] {
[System.Security.SecurityCritical]
get {
Contract.Requires(index >= 0 && index < Length);
if (useStackAlloc) {
return m_arrayPtr[index];
}
else {
return m_sb[index];
}
}
[System.Security.SecurityCritical]
set {
Contract.Requires(index >= 0 && index < Length);
if (useStackAlloc) {
m_arrayPtr[index] = value;
}
else {
m_sb[index] = value;
}
}
}
[System.Security.SecurityCritical]
internal unsafe void Append(char value) {
if (Length + 1 >= m_capacity)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
if (useStackAlloc) {
m_arrayPtr[Length] = value;
m_length++;
}
else {
m_sb.Append(value);
}
}
[System.Security.SecurityCritical]
internal unsafe int GetFullPathName() {
if (useStackAlloc) {
char* finalBuffer = stackalloc char[Path.MaxPath + 1];
int result = Win32Native.GetFullPathName(m_arrayPtr, Path.MaxPath + 1, finalBuffer, IntPtr.Zero);
// If success, the return buffer length does not account for the terminating null character.
// If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
// If failure, the return buffer length is zero
if (result > Path.MaxPath) {
char* tempBuffer = stackalloc char[result];
finalBuffer = tempBuffer;
result = Win32Native.GetFullPathName(m_arrayPtr, result, finalBuffer, IntPtr.Zero);
}
// Full path is genuinely long
if (result >= Path.MaxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
Contract.Assert(result < Path.MaxPath, "did we accidently remove a PathTooLongException check?");
if (result == 0 && m_arrayPtr[0] != '\0') {
__Error.WinIOError();
}
else if (result < Path.MaxPath) {
// Null terminate explicitly (may be only needed for some cases such as empty strings)
// GetFullPathName return length doesn't account for null terminating char...
finalBuffer[result] = '\0'; // Safe to write directly as result is < Path.MaxPath
}
// We have expanded the paths and GetLongPathName may or may not behave differently from before.
// We need to call it again to see:
doNotTryExpandShortFileName = false;
String.wstrcpy(m_arrayPtr, finalBuffer, result);
// Doesn't account for null terminating char. Think of this as the last
// valid index into the buffer but not the length of the buffer
Length = result;
return result;
}
else {
StringBuilder finalBuffer = new StringBuilder(m_capacity + 1);
int result = Win32Native.GetFullPathName(m_sb.ToString(), m_capacity + 1, finalBuffer, IntPtr.Zero);
// If success, the return buffer length does not account for the terminating null character.
// If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
// If failure, the return buffer length is zero
if (result > m_maxPath) {
finalBuffer.Length = result;
result = Win32Native.GetFullPathName(m_sb.ToString(), result, finalBuffer, IntPtr.Zero);
}
// Fullpath is genuinely long
if (result >= m_maxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
Contract.Assert(result < m_maxPath, "did we accidentally remove a PathTooLongException check?");
if (result == 0 && m_sb[0] != '\0') {
if (Length >= m_maxPath) {
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
}
__Error.WinIOError();
}
// We have expanded the paths and GetLongPathName may or may not behave differently from before.
// We need to call it again to see:
doNotTryExpandShortFileName = false;
m_sb = finalBuffer;
return result;
}
}
[System.Security.SecurityCritical]
internal unsafe bool TryExpandShortFileName() {
if (doNotTryExpandShortFileName)
return false;
if (useStackAlloc) {
NullTerminate();
char* buffer = UnsafeGetArrayPtr();
char* shortFileNameBuffer = stackalloc char[Path.MaxPath + 1];
int r = Win32Native.GetLongPathName(buffer, shortFileNameBuffer, Path.MaxPath);
// If success, the return buffer length does not account for the terminating null character.
// If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
// If failure, the return buffer length is zero
if (r >= Path.MaxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
if (r == 0) {
// Note: GetLongPathName will return ERROR_INVALID_FUNCTION on a
// path like \\.\PHYSICALDEVICE0 - some device driver doesn't
// support GetLongPathName on that string. This behavior is
// by design, according to the Core File Services team.
// We also get ERROR_NOT_ENOUGH_QUOTA in SQL_CLR_STRESS runs
// intermittently on paths like D:\DOCUME~1\user\LOCALS~1\Temp\
// We do not need to call GetLongPathName if we know it will fail becasue the path does not exist:
int lastErr = Marshal.GetLastWin32Error();
if (lastErr == Win32Native.ERROR_FILE_NOT_FOUND || lastErr == Win32Native.ERROR_PATH_NOT_FOUND)
doNotTryExpandShortFileName = true;
return false;
}
// Safe to copy as we have already done Path.MaxPath bound checking
String.wstrcpy(buffer, shortFileNameBuffer, r);
Length = r;
// We should explicitly null terminate as in some cases the long version of the path
// might actually be shorter than what we started with because of Win32's normalization
// Safe to write directly as bufferLength is guaranteed to be < Path.MaxPath
NullTerminate();
return true;
}
else {
StringBuilder sb = GetStringBuilder();
String origName = sb.ToString();
String tempName = origName;
bool addedPrefix = false;
if (tempName.Length > Path.MaxPath) {
tempName = Path.AddLongPathPrefix(tempName);
addedPrefix = true;
}
sb.Capacity = m_capacity;
sb.Length = 0;
int r = Win32Native.GetLongPathName(tempName, sb, m_capacity);
if (r == 0) {
// Note: GetLongPathName will return ERROR_INVALID_FUNCTION on a
// path like \\.\PHYSICALDEVICE0 - some device driver doesn't
// support GetLongPathName on that string. This behavior is
// by design, according to the Core File Services team.
// We also get ERROR_NOT_ENOUGH_QUOTA in SQL_CLR_STRESS runs
// intermittently on paths like D:\DOCUME~1\user\LOCALS~1\Temp\
// We do not need to call GetLongPathName if we know it will fail becasue the path does not exist:
int lastErr = Marshal.GetLastWin32Error();
if (Win32Native.ERROR_FILE_NOT_FOUND == lastErr || Win32Native.ERROR_PATH_NOT_FOUND == lastErr)
doNotTryExpandShortFileName = true;
sb.Length = 0;
sb.Append(origName);
return false;
}
if (addedPrefix)
r -= 4;
// If success, the return buffer length does not account for the terminating null character.
// If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
// If failure, the return buffer length is zero
if (r >= m_maxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
sb = Path.RemoveLongPathPrefix(sb);
Length = sb.Length;
return true;
}
}
[System.Security.SecurityCritical]
internal unsafe void Fixup(int lenSavedName, int lastSlash) {
if (useStackAlloc) {
char* savedName = stackalloc char[lenSavedName];
String.wstrcpy(savedName, m_arrayPtr + lastSlash + 1, lenSavedName);
Length = lastSlash;
NullTerminate();
doNotTryExpandShortFileName = false;
bool r = TryExpandShortFileName();
// Clean up changes made to the newBuffer.
Append(Path.DirectorySeparatorChar);
if (Length + lenSavedName >= Path.MaxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
String.wstrcpy(m_arrayPtr + Length, savedName, lenSavedName);
Length = Length + lenSavedName;
}
else {
String savedName = m_sb.ToString(lastSlash + 1, lenSavedName);
Length = lastSlash;
doNotTryExpandShortFileName = false;
bool r = TryExpandShortFileName();
// Clean up changes made to the newBuffer.
Append(Path.DirectorySeparatorChar);
if (Length + lenSavedName >= m_maxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
m_sb.Append(savedName);
}
}
[System.Security.SecurityCritical]
internal unsafe bool OrdinalStartsWith(String compareTo, bool ignoreCase) {
if (Length < compareTo.Length)
return false;
if (useStackAlloc) {
NullTerminate();
if (ignoreCase) {
String s = new String(m_arrayPtr, 0, compareTo.Length);
return compareTo.Equals(s, StringComparison.OrdinalIgnoreCase);
}
else {
for (int i = 0; i < compareTo.Length; i++) {
if (m_arrayPtr[i] != compareTo[i]) {
return false;
}
}
return true;
}
}
else {
if (ignoreCase) {
return m_sb.ToString().StartsWith(compareTo, StringComparison.OrdinalIgnoreCase);
}
else {
return m_sb.ToString().StartsWith(compareTo, StringComparison.Ordinal);
}
}
}
[System.Security.SecuritySafeCritical]
public override String ToString() {
if (useStackAlloc) {
return new String(m_arrayPtr, 0, Length);
}
else {
return m_sb.ToString();
}
}
[System.Security.SecurityCritical]
private unsafe char* UnsafeGetArrayPtr() {
Contract.Requires(useStackAlloc, "This should never be called for PathHelpers wrapping a StringBuilder");
return m_arrayPtr;
}
private StringBuilder GetStringBuilder() {
Contract.Requires(!useStackAlloc, "This should never be called for PathHelpers that wrap a stackalloc'd buffer");
return m_sb;
}
[System.Security.SecurityCritical]
private unsafe void NullTerminate() {
Contract.Requires(useStackAlloc, "This should never be called for PathHelpers wrapping a StringBuilder");
m_arrayPtr[m_length] = '\0';
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using ASC.Api.Attributes;
using ASC.Api.Bookmarks;
using ASC.Api.Collections;
using ASC.Api.Exceptions;
using ASC.Bookmarking.Business;
using ASC.Bookmarking.Business.Permissions;
using ASC.Bookmarking.Pojo;
using ASC.Core;
using ASC.Core.Tenants;
using ASC.Web.Studio.UserControls.Common.Comments;
using ASC.Web.Studio.Utility.HtmlUtility;
using ASC.Web.UserControls.Bookmarking.Common.Presentation;
using ASC.Web.UserControls.Bookmarking.Common.Util;
namespace ASC.Api.Community
{
public partial class CommunityApi
{
private BookmarkingService _bookmarkingDao;
private BookmarkingService BookmarkingDao
{
get { return _bookmarkingDao ?? (_bookmarkingDao = BookmarkingService.GetCurrentInstanse()); }
}
///<summary>
///Returns the list of all bookmarks on the portal with the bookmark titles, date of creation and update, bookmark text and author
///</summary>
///<short>
///All bookmarks
///</short>
///<category>Bookmarks</category>
///<returns>List of all bookmarks</returns>
[Read("bookmark")]
public IEnumerable<BookmarkWrapper> GetBookmarks()
{
var bookmarks = BookmarkingDao.GetAllBookmarks((int)_context.StartIndex, (int)_context.Count);
_context.SetDataPaginated();
return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList();
}
///<summary>
///Returns the list of all bookmarks for the current user with the bookmark titles, date of creation and update, bookmark text and author
///</summary>
///<short>
///Added by me
///</short>
///<category>Bookmarks</category>
///<returns>List of bookmarks</returns>
[Read("bookmark/@self")]
public IEnumerable<BookmarkWrapper> GetMyBookmarks()
{
var bookmarks = BookmarkingDao.GetBookmarksCreatedByUser(SecurityContext.CurrentAccount.ID, (int)_context.StartIndex, (int)_context.Count);
_context.SetDataPaginated();
return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList();
}
///<summary>
///Returns a list of bookmarks matching the search query with the bookmark title, date of creation and update, bookmark description and author
///</summary>
///<short>
///Search
///</short>
///<category>Bookmarks</category>
/// <param name="query">search query</param>
///<returns>List of bookmarks</returns>
[Read("bookmark/@search/{query}")]
public IEnumerable<BookmarkWrapper> SearchBookmarks(string query)
{
var bookmarks = BookmarkingDao.SearchBookmarks(new List<string> { query }, (int)_context.StartIndex, (int)_context.Count);
_context.SetDataPaginated();
return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList();
}
///<summary>
///Returns the list of favorite bookmarks for the current user with the bookmark titles, date of creation and update, bookmark text and author
///</summary>
///<short>
///My favorite
///</short>
///<category>Bookmarks</category>
///<returns>List of bookmarks</returns>
[Read("bookmark/@favs")]
public IEnumerable<BookmarkWrapper> GetFavsBookmarks()
{
var bookmarks = BookmarkingDao.GetFavouriteBookmarksSortedByDate((int)_context.StartIndex, (int)_context.Count);
_context.SetDataPaginated();
return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList();
}
///<summary>
///Returns a list of all tags used for bookmarks with the number showing the tag usage
///</summary>
///<short>
///All tags
///</short>
///<category>Bookmarks</category>
///<returns>List of tags</returns>
[Read("bookmark/tag")]
public IEnumerable<TagWrapper> GetBookmarksTags()
{
var bookmarks = BookmarkingDao.GetAllTags();
return bookmarks.Select(x => new TagWrapper(x)).ToSmartList();
}
///<summary>
///Returns the list of all bookmarks marked by the tag specified with the bookmark titles, date of creation and update, bookmark text and author
///</summary>
///<short>
///By tag
///</short>
///<category>Bookmarks</category>
///<param name="tag">tag</param>
///<returns>List of bookmarks</returns>
[Read("bookmark/bytag")]
public IEnumerable<BookmarkWrapper> GetBookmarksByTag(string tag)
{
var bookmarks = BookmarkingDao.SearchBookmarksByTag(tag, (int)_context.StartIndex, (int)_context.Count);
_context.SetDataPaginated();
return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList();
}
///<summary>
///Returns the list of recenty added bookmarks with the bookmark titles, date of creation and update, bookmark text and author
///</summary>
///<short>
///Recently added
///</short>
///<category>Bookmarks</category>
///<returns>List of bookmarks</returns>
[Read("bookmark/top/recent")]
public IEnumerable<BookmarkWrapper> GetRecentBookmarks()
{
var bookmarks = BookmarkingDao.GetMostRecentBookmarks((int)_context.StartIndex, (int)_context.Count);
_context.SetDataPaginated();
return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList();
}
///<summary>
///Returns the list of the bookmarks most popular on the current date with the bookmark titles, date of creation and update, bookmark text and author
///</summary>
///<short>
///Top of day
///</short>
///<category>Bookmarks</category>
///<returns>List of bookmarks</returns>
[Read("bookmark/top/day")]
public IEnumerable<BookmarkWrapper> GetTopDayBookmarks()
{
var bookmarks = BookmarkingDao.GetTopOfTheDay((int)_context.StartIndex, (int)_context.Count);
_context.SetDataPaginated();
return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList();
}
///<summary>
///Returns the list of the bookmarks most popular in the current month with the bookmark titles, date of creation and update, bookmark text and author
///</summary>
///<short>
///Top of month
///</short>
///<category>Bookmarks</category>
///<returns>List of bookmarks</returns>
[Read("bookmark/top/month")]
public IEnumerable<BookmarkWrapper> GetTopMonthBookmarks()
{
var bookmarks = BookmarkingDao.GetTopOfTheMonth((int)_context.StartIndex, (int)_context.Count);
_context.SetDataPaginated();
return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList();
}
///<summary>
///Returns the list of the bookmarks most popular on the current week with the bookmark titles, date of creation and update, bookmark text and author
///</summary>
///<short>
///Top of week
///</short>
///<category>Bookmarks</category>
///<returns>list of bookmarks</returns>
[Read("bookmark/top/week")]
public IEnumerable<BookmarkWrapper> GetTopWeekBookmarks()
{
var bookmarks = BookmarkingDao.GetTopOfTheWeek((int)_context.StartIndex, (int)_context.Count);
_context.SetDataPaginated();
return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList();
}
///<summary>
///Returns the list of the bookmarks most popular in the current year with the bookmark titles, date of creation and update, bookmark text and author
///</summary>
///<short>
///Top of year
///</short>
///<category>Bookmarks</category>
///<returns>list of bookmarks</returns>
[Read("bookmark/top/year")]
public IEnumerable<BookmarkWrapper> GetTopYearBookmarks()
{
var bookmarks = BookmarkingDao.GetTopOfTheYear((int)_context.StartIndex, (int)_context.Count);
_context.SetDataPaginated();
return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList();
}
///<summary>
/// Returns the list of all comments to the bookmark with the specified ID
///</summary>
///<short>
/// Get comments
///</short>
///<category>Bookmarks</category>
///<param name="id">Bookmark ID</param>
///<returns>list of bookmark comments</returns>
[Read("bookmark/{id}/comment")]
public IEnumerable<BookmarkCommentWrapper> GetBookmarkComments(long id)
{
var comments = BookmarkingDao.GetBookmarkComments(BookmarkingDao.GetBookmarkByID(id));
return comments.Select(x => new BookmarkCommentWrapper(x)).ToSmartList();
}
///<summary>
/// Adds a comment to the bookmark with the specified ID. The parent bookmark ID can be also specified if needed.
///</summary>
///<short>
/// Add comment
///</short>
///<param name="id">Bookmark ID</param>
///<param name="content">comment content</param>
///<param name="parentId">parent comment ID</param>
///<returns>list of bookmark comments</returns>
/// <example>
/// <![CDATA[
/// Sending data in application/json:
///
/// {
/// content:"My comment",
/// parentId:"9924256A-739C-462b-AF15-E652A3B1B6EB"
/// }
///
/// Sending data in application/x-www-form-urlencoded
/// content="My comment"&parentId="9924256A-739C-462b-AF15-E652A3B1B6EB"
/// ]]>
/// </example>
/// <remarks>
/// Send parentId=00000000-0000-0000-0000-000000000000 or don't send it at all if you want your comment to be on the root level
/// </remarks>
/// <category>Bookmarks</category>
[Create("bookmark/{id}/comment")]
public BookmarkCommentWrapper AddBookmarkComment(long id, string content, Guid parentId)
{
var bookmark = BookmarkingDao.GetBookmarkByID(id);
if (bookmark == null) throw new ItemNotFoundException("bookmark not found");
var comment = new Comment
{
ID = Guid.NewGuid(),
BookmarkID = id,
Content = content,
Datetime = DateTime.UtcNow,
UserID = SecurityContext.CurrentAccount.ID,
Parent = parentId.ToString()
};
BookmarkingDao.AddComment(comment);
return new BookmarkCommentWrapper(comment);
}
///<summary>
/// Returns a detailed information on the bookmark with the specified ID
///</summary>
///<short>
/// Get bookmarks by ID
///</short>
///<param name="id">Bookmark ID</param>
///<returns>bookmark</returns>
///<category>Bookmarks</category>
[Read("bookmark/{id}")]
public BookmarkWrapper GetBookmarkById(long id)
{
return new BookmarkWrapper(BookmarkingDao.GetBookmarkByID(id));
}
///<summary>
/// Adds a bookmark with a specified title, description and tags
///</summary>
///<short>
/// Add bookmark
///</short>
///<param name="url">absolute url of bookmarking page</param>
///<param name="title">title to show</param>
///<param name="description">description</param>
///<param name="tags">tags. separated by semicolon</param>
///<returns>newly added bookmark</returns>
/// <example>
/// <![CDATA[
/// Sending data in application/json:
///
/// {
/// url:"https://www.teamlab.com",
/// title: "TeamLab",
/// description: "best site i've ever seen",
/// tags: "project management, collaboration"
/// }
///
/// Sending data in application/x-www-form-urlencoded
/// url="https://www.teamlab.com"&title="TeamLab"&description="best site i've ever seen"&tags="project management, collaboration"
/// ]]>
/// </example>
/// <category>Bookmarks</category>
[Create("bookmark")]
public BookmarkWrapper AddBookmark(string url, string title, string description, string tags)
{
try
{
var uri = new Uri(url, UriKind.Absolute);
}
catch (Exception)
{
throw new ArgumentException("invalid absolute url", "url");
}
if (string.IsNullOrEmpty(title))
{
throw new ArgumentException("title can't be empty", "title");
}
var bookmark = new Bookmark(url, TenantUtil.DateTimeNow(), title, description) { UserCreatorID = SecurityContext.CurrentAccount.ID };
BookmarkingDao.AddBookmark(bookmark, !string.IsNullOrEmpty(tags) ? tags.Split(',').Select(x => new Tag { Name = x }).ToList() : new List<Tag>());
return new BookmarkWrapper(bookmark);
}
/// <summary>
/// Get comment preview with the content specified in the request
/// </summary>
/// <short>Get comment preview</short>
/// <section>Comments</section>
/// <param name="commentid">Comment ID</param>
/// <param name="htmltext">Comment content</param>
/// <returns>Comment info</returns>
/// <category>Bookmarks</category>
[Create("bookmark/comment/preview")]
public CommentInfo GetBookmarkCommentPreview(string commentid, string htmltext)
{
var comment = new Comment
{
Datetime = TenantUtil.DateTimeNow(),
UserID = SecurityContext.CurrentAccount.ID
};
if (!String.IsNullOrEmpty(commentid))
{
comment = BookmarkingServiceHelper.GetCurrentInstanse().GetCommentById(commentid);
comment.Parent = string.Empty;
}
comment.Content = htmltext;
var ci = BookmarkingConverter.ConvertComment(comment, new List<Comment>());
ci.IsEditPermissions = false;
ci.IsResponsePermissions = false;
//var isRoot = string.IsNullOrEmpty(comment.Parent) || comment.Parent.Equals(Guid.Empty.ToString(), StringComparison.CurrentCultureIgnoreCase);
return ci;
}
/// <summary>
///Remove comment with the id specified in the request
/// </summary>
/// <short>Remove comment</short>
/// <section>Comments</section>
/// <param name="commentid">Comment ID</param>
/// <returns>Comment id</returns>
/// <category>Bookmarks</category>
[Delete("bookmark/comment/{commentid}")]
public string RemoveBookmarkComment(string commentid)
{
var comment = BookmarkingServiceHelper.GetCurrentInstanse().GetCommentById(commentid);
if (comment != null && BookmarkingPermissionsCheck.PermissionCheckEditComment(comment))
{
BookmarkingServiceHelper.GetCurrentInstanse().RemoveComment(commentid);
return commentid;
}
return null;
}
/// <category>Bookmarks</category>
[Create("bookmark/comment")]
public CommentInfo AddBookmarkComment(string parentcommentid, long entityid, string content)
{
var comment = new Comment
{
Content = content,
Datetime = TenantUtil.DateTimeNow(),
UserID = SecurityContext.CurrentAccount.ID
};
var parentID = Guid.Empty;
try
{
if (!string.IsNullOrEmpty(parentcommentid))
{
parentID = new Guid(parentcommentid);
}
}
catch
{
parentID = Guid.Empty;
}
comment.Parent = parentID.ToString();
comment.BookmarkID = entityid;
comment.ID = Guid.NewGuid();
BookmarkingServiceHelper.GetCurrentInstanse().AddComment(comment);
return BookmarkingConverter.ConvertComment(comment, new List<Comment>());
}
/// <category>Bookmarks</category>
[Update("bookmark/comment/{commentid}")]
public string UpdateBookmarkComment(string commentid, string content)
{
var comment = BookmarkingServiceHelper.GetCurrentInstanse().GetCommentById(commentid);
if (comment == null || !BookmarkingPermissionsCheck.PermissionCheckEditComment(comment)) throw new ArgumentException();
BookmarkingServiceHelper.GetCurrentInstanse().UpdateComment(commentid, content);
return HtmlUtility.GetFull(content);
}
/// <summary>
/// Removes bookmark from favourite. If after removing user bookmark raiting of this bookmark is 0, the bookmark will be removed completely.
/// </summary>
/// <short>Removes bookmark from favourite</short>
/// <param name="id">Bookmark ID</param>
/// <returns>bookmark</returns>
/// <category>Bookmarks</category>
[Delete("bookmark/@favs/{id}")]
public BookmarkWrapper RemoveBookmarkFromFavourite(long id)
{
var bookmark = BookmarkingServiceHelper.GetCurrentInstanse().RemoveBookmarkFromFavourite(id);
return bookmark == null ? null : new BookmarkWrapper(bookmark);
}
/// <summary>
/// Removes bookmark
/// </summary>
/// <short>Removes bookmark</short>
/// <param name="id">Bookmark ID</param>
/// <category>Bookmarks</category>
[Delete("bookmark/{id}")]
public void RemoveBookmark(long id)
{
BookmarkingServiceHelper.GetCurrentInstanse().RemoveBookmark(id);
}
}
}
| |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.Util;
using Google.Ads.GoogleAds.V10.Common;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V10.Enums.UserListMembershipStatusEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.UserListPrepopulationStatusEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.UserListStringRuleItemOperatorEnum.Types;
using static Google.Ads.GoogleAds.V10.Errors.CriterionErrorEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// Demonstrates various operations involved in remarketing, including:
/// (a) creating a user list based on visitors to a website,
/// (b) targeting a user list with an ad group criterion,
/// (c) updating the bid modifier on an ad group criterion,
/// (d) finding and removing all ad group criteria under a given campaign,
/// (e) targeting a user list with a campaign criterion, and
/// (f) updating the bid modifier on a campaign criterion.
/// It is unlikely that users will need to perform all of these operations consecutively, and
/// all of the operations contained herein are meant of for illustrative purposes.
/// Note: you can use user lists to target at the campaign or ad group level, but not both
/// simultaneously. Consider removing or disabling any existing user lists at the campaign level
/// before running this example.
/// </summary>
public class SetUpRemarketing : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="SetUpRemarketing"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// The ad group ID on which criteria will be targeted.
/// </summary>
[Option("adGroupId", Required = true, HelpText =
"The ad group ID on which criteria will be targeted.")]
public long AdGroupId { get; set; }
/// <summary>
/// The campaign ID on which criteria will be targeted.
/// </summary>
[Option("campaignId", Required = true, HelpText =
"The campaign ID on which criteria will be targeted.")]
public long CampaignId { get; set; }
/// <summary>
/// The bid modifier value.
/// </summary>
[Option("bidModifierValue", Required = true, HelpText =
"The bid modifier value.")]
public double BidModifierValue { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The Google Ads customer ID for which the call is made.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
// The ad group ID on which criteria will be targeted.
options.AdGroupId = long.Parse("INSERT_AD_GROUP_ID_HERE");
// The campaign ID on which criteria will be targeted.
options.CampaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
// The bid modifier value.
options.BidModifierValue = double.Parse("INSERT_BID_MODIFIER_VALUE_HERE");
return 0;
});
SetUpRemarketing codeExample = new SetUpRemarketing();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.AdGroupId,
options.CampaignId, options.BidModifierValue);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"Demonstrates various operations involved in remarketing, including:\n" +
"\t(a) creating a user list based on visitors to a website,\n" +
"\t(b) targeting a user list with an ad group criterion,\n" +
"\t(c) updating the bid modifier on an ad group criterion,\n" +
"\t(d) finding and removing all ad group criteria under a given campaign,\n" +
"\t(e) targeting a user list with a campaign criterion, and\n" +
"\t(f) updating the bid modifier on a campaign criterion.\n" +
"It is unlikely that users will need to perform all of these operations " +
"consecutively, and all of the operations contained herein are meant of for " +
"illustrative purposes.\n" +
"Note: you can use user lists to target at the campaign or ad group level, but not " +
"both simultaneously. Consider removing or disabling any existing user lists at the " +
"campaign level before running this example.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="adGroupId">The ad group ID on which criteria will be targeted.</param>
/// <param name="campaignId">The campaign ID on which criteria will be targeted.</param>
/// <param name="bidModifierValue">The bid modifier value.</param>
public void Run(GoogleAdsClient client, long customerId, long adGroupId, long campaignId,
double bidModifierValue)
{
try
{
// Create a new example user list.
string userListResourceName = CreateUserList(client, customerId);
// Target an ad group to the new user list.
string adGroupCriterionResourceName =
TargetAdsInAdGroupToUserList(client, customerId, adGroupId,
userListResourceName);
ModifyAdGroupBids(client, customerId, adGroupCriterionResourceName,
bidModifierValue);
// Remove any existing user lists at the ad group level.
RemoveExistingListCriteriaFromAdGroup(client, customerId, campaignId);
// Target the campaign to the new user list.
string campaignCriterionResourceName =
TargetAdsInCampaignToUserList(client, customerId, campaignId,
userListResourceName);
ModifyCampaignBids(client, customerId, campaignCriterionResourceName,
bidModifierValue);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
if (e.Failure.Errors.First().ErrorCode.CriterionError ==
CriterionError.CannotAttachCriteriaAtCampaignAndAdgroup)
{
Console.WriteLine("This error can occur when user lists are already targeted " +
"at the campaign level. You can use user lists to target at the campaign " +
"or ad group level, but not both simultaneously. Consider removing or " +
"disabling any existing user lists at the campaign level before running " +
"this example.");
}
throw;
}
}
/// <summary>
/// Creates a user list targeting users that have visited a given url.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <returns>The resource name of the newly created user list.</returns>
// [START setup_remarketing]
private string CreateUserList(GoogleAdsClient client, long customerId)
{
// Get the UserListService client.
UserListServiceClient userListServiceClient =
client.GetService(Services.V10.UserListService);
// Create a rule targeting any user that visited a url containing 'example.com'.
UserListRuleItemInfo rule = new UserListRuleItemInfo
{
// Use a built-in parameter to create a domain URL rule.
Name = "url__",
StringRuleItem = new UserListStringRuleItemInfo
{
Operator = UserListStringRuleItemOperator.Contains,
Value = "example.com"
}
};
// Specify that the user list targets visitors of a page based on the provided rule.
ExpressionRuleUserListInfo expressionRuleUserListInfo = new ExpressionRuleUserListInfo
{
Rule = new UserListRuleInfo()
};
UserListRuleItemGroupInfo userListRuleItemGroupInfo = new UserListRuleItemGroupInfo();
userListRuleItemGroupInfo.RuleItems.Add(rule);
expressionRuleUserListInfo.Rule.RuleItemGroups.Add(userListRuleItemGroupInfo);
// Define a representation of a user list that is generated by a rule.
RuleBasedUserListInfo ruleBasedUserListInfo = new RuleBasedUserListInfo
{
// Optional: To include past users in the user list, set the prepopulation_status to
// REQUESTED.
PrepopulationStatus = UserListPrepopulationStatus.Requested,
ExpressionRuleUserList = expressionRuleUserListInfo
};
// Create the user list.
UserList userList = new UserList
{
Name = $"All visitors to example.com #{ExampleUtilities.GetRandomString()}",
Description = "Any visitor to any page of example.com",
MembershipStatus = UserListMembershipStatus.Open,
MembershipLifeSpan = 365L,
RuleBasedUserList = ruleBasedUserListInfo
};
// Create the operation.
UserListOperation userListOperation = new UserListOperation
{
Create = userList
};
// Add the user list, then print and return the new list's resource name.
MutateUserListsResponse mutateUserListsResponse = userListServiceClient
.MutateUserLists(customerId.ToString(), new[] { userListOperation });
string userListResourceName = mutateUserListsResponse.Results.First().ResourceName;
Console.WriteLine($"Created user list with resource name '{userListResourceName}'.");
return userListResourceName;
}
// [END setup_remarketing]
/// <summary>
/// Creates an ad group criterion that targets a user list with an ad group.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="adGroupId">The ad group on which the user list will be targeted.</param>
/// <param name="userListResourceName">The resource name of the user list to be
/// targeted.</param>
/// <returns>The resource name of the newly created ad group criterion.</returns>
// [START setup_remarketing_1]
private string TargetAdsInAdGroupToUserList(
GoogleAdsClient client, long customerId, long adGroupId, string userListResourceName)
{
// Get the AdGroupCriterionService client.
AdGroupCriterionServiceClient adGroupCriterionServiceClient = client.GetService
(Services.V10.AdGroupCriterionService);
// Create the ad group criterion targeting members of the user list.
AdGroupCriterion adGroupCriterion = new AdGroupCriterion
{
AdGroup = ResourceNames.AdGroup(customerId, adGroupId),
UserList = new UserListInfo
{
UserList = userListResourceName
}
};
// Create the operation.
AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation
{
Create = adGroupCriterion
};
// Add the ad group criterion, then print and return the new criterion's resource name.
MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
adGroupCriterionServiceClient.MutateAdGroupCriteria(customerId.ToString(),
new[] { adGroupCriterionOperation });
string adGroupCriterionResourceName =
mutateAdGroupCriteriaResponse.Results.First().ResourceName;
Console.WriteLine("Successfully created ad group criterion with resource name " +
$"'{adGroupCriterionResourceName}' targeting user list with resource name " +
$"'{userListResourceName}' with ad group with ID {adGroupId}.");
return adGroupCriterionResourceName;
}
// [END setup_remarketing_1]
/// <summary>
/// Updates the bid modifier on an ad group criterion.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="adGroupCriterionResourceName">The resource name of the ad group criterion to update.</param>
/// <param name="bidModifierValue">The bid modifier value.</param>
private void ModifyAdGroupBids(
GoogleAdsClient client,
long customerId,
string adGroupCriterionResourceName,
double bidModifierValue)
{
// Get the AdGroupCriterionService client.
AdGroupCriterionServiceClient adGroupCriterionServiceClient =
client.GetService(Services.V10.AdGroupCriterionService);
// Create the ad group criterion with a bid modifier. You may alternatively set the bid
// for the ad group criterion directly.
AdGroupCriterion adGroupCriterion = new AdGroupCriterion
{
ResourceName = adGroupCriterionResourceName,
BidModifier = bidModifierValue
};
// Create the update operation.
AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation
{
Update = adGroupCriterion,
UpdateMask = FieldMasks.AllSetFieldsOf(adGroupCriterion)
};
// Update the ad group criterion and print the results.
MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
adGroupCriterionServiceClient.MutateAdGroupCriteria(customerId.ToString(),
new[] { adGroupCriterionOperation });
Console.WriteLine("Successfully updated the bid for ad group criterion with resource " +
$"name '{mutateAdGroupCriteriaResponse.Results.First().ResourceName}'.");
}
/// <summary>
/// Removes all ad group criteria targeting a user list under a given campaign. This is a
/// necessary step before targeting a user list at the campaign level.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="campaignId">The campaign from which to remove the ad group criteria.</param>
// [START setup_remarketing_3]
private void RemoveExistingListCriteriaFromAdGroup(GoogleAdsClient client, long customerId,
long campaignId)
{
// Get the AdGroupCriterionService client.
AdGroupCriterionServiceClient adGroupCriterionServiceClient =
client.GetService(Services.V10.AdGroupCriterionService);
// Retrieve all of the ad group criteria under a campaign.
List<string> adGroupCriteria =
GetUserListAdGroupCriteria(client, customerId, campaignId);
// Create a list of remove operations.
List<AdGroupCriterionOperation> operations = adGroupCriteria.Select(adGroupCriterion =>
new AdGroupCriterionOperation { Remove = adGroupCriterion }).ToList();
// Remove the ad group criteria and print the resource names of the removed criteria.
MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
adGroupCriterionServiceClient.MutateAdGroupCriteria(customerId.ToString(),
operations);
Console.WriteLine($"Removed {mutateAdGroupCriteriaResponse.Results.Count} ad group " +
"criteria.");
foreach (MutateAdGroupCriterionResult result in mutateAdGroupCriteriaResponse.Results)
{
Console.WriteLine("Successfully removed ad group criterion with resource name " +
$"'{result.ResourceName}'.");
}
}
// [END setup_remarketing_3]
/// <summary>
/// Finds all of user list ad group criteria under a campaign.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="campaignId">The campaign in which to search the ad group criteria.</param>
/// <returns>A list of ad group criteria resource names.</returns>
// [START setup_remarketing_2]
private List<string> GetUserListAdGroupCriteria(
GoogleAdsClient client, long customerId, long campaignId)
{
// Get the GoogleAdsService client.
GoogleAdsServiceClient googleAdsServiceClient =
client.GetService(Services.V10.GoogleAdsService);
List<string> userListCriteriaResourceNames = new List<string>();
// Create a query that will retrieve all of the ad group criteria under a campaign.
string query = $@"
SELECT ad_group_criterion.criterion_id
FROM ad_group_criterion
WHERE
campaign.id = {campaignId}
AND ad_group_criterion.type = 'USER_LIST'";
// Issue the search request.
googleAdsServiceClient.SearchStream(customerId.ToString(), query,
delegate (SearchGoogleAdsStreamResponse resp)
{
// Display the results and add the resource names to the list.
foreach (GoogleAdsRow googleAdsRow in resp.Results)
{
string adGroupCriterionResourceName =
googleAdsRow.AdGroupCriterion.ResourceName;
Console.WriteLine("Ad group criterion with resource name " +
$"{adGroupCriterionResourceName} was found.");
userListCriteriaResourceNames.Add(adGroupCriterionResourceName);
}
});
return userListCriteriaResourceNames;
}
// [END setup_remarketing_2]
/// <summary>
/// Creates a campaign criterion that targets a user list with a campaign.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="campaignId">The campaign on which the user list will be targeted.</param>
/// <param name="userListResourceName">The resource name of the user list to be
/// targeted.</param>
/// <returns>The resource name of the newly created campaign criterion.</returns>
// [START setup_remarketing_4]
private string TargetAdsInCampaignToUserList(
GoogleAdsClient client, long customerId, long campaignId, string userListResourceName)
{
// Get the CampaignCriterionService client.
CampaignCriterionServiceClient campaignCriterionServiceClient =
client.GetService(Services.V10.CampaignCriterionService);
// Create the campaign criterion.
CampaignCriterion campaignCriterion = new CampaignCriterion
{
Campaign = ResourceNames.Campaign(customerId, campaignId),
UserList = new UserListInfo
{
UserList = userListResourceName
}
};
// Create the operation.
CampaignCriterionOperation campaignCriterionOperation = new CampaignCriterionOperation
{
Create = campaignCriterion
};
// Add the campaign criterion and print the resulting criterion's resource name.
MutateCampaignCriteriaResponse mutateCampaignCriteriaResponse =
campaignCriterionServiceClient.MutateCampaignCriteria(customerId.ToString(),
new[] { campaignCriterionOperation });
string campaignCriterionResourceName =
mutateCampaignCriteriaResponse.Results.First().ResourceName;
Console.WriteLine("Successfully created campaign criterion with resource name " +
$"'{campaignCriterionResourceName}' targeting user list with resource name " +
$"'{userListResourceName}' with campaign with ID {campaignId}.");
return campaignCriterionResourceName;
}
// [END setup_remarketing_4]
/// <summary>
/// Updates the bid modifier on a campaign criterion.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="campaignCriterionResourceName">The resource name of the campaign criterion to update.</param>
/// <param name="bidModifierValue">The bid modifier value.</param>
private void ModifyCampaignBids(
GoogleAdsClient client,
long customerId,
string campaignCriterionResourceName,
double bidModifierValue)
{
// Get the CampaignCriterionService client.
CampaignCriterionServiceClient campaignCriterionServiceClient =
client.GetService(Services.V10.CampaignCriterionService);
// Create the campaign criterion to update.
CampaignCriterion campaignCriterion = new CampaignCriterion
{
ResourceName = campaignCriterionResourceName,
BidModifier = (float) bidModifierValue
};
// Create the update operation.
CampaignCriterionOperation campaignCriterionOperation = new CampaignCriterionOperation
{
Update = campaignCriterion,
UpdateMask = FieldMasks.AllSetFieldsOf(campaignCriterion)
};
// Update the campaign criterion and print the results.
MutateCampaignCriteriaResponse mutateCampaignCriteriaResponse =
campaignCriterionServiceClient.MutateCampaignCriteria(customerId.ToString(),
new[] { campaignCriterionOperation });
Console.WriteLine("Successfully updated the bid for campaign criterion with resource " +
$"name '{mutateCampaignCriteriaResponse.Results.First().CampaignCriterion}'.");
}
}
}
| |
// 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.Linq;
using System.Security.Cryptography.Asn1;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Tests.Asn1
{
public sealed class ReadGeneralizedTime : Asn1ReaderTests
{
[Theory]
// yyyyMMddHH (2017090821)
[InlineData(PublicEncodingRules.BER, "180A32303137303930383231", 2017, 9, 8, 21, 0, 0, 0, null, 0)]
// yyyyMMddHHZ (2017090821Z)
[InlineData(PublicEncodingRules.BER, "180B323031373039303832315A", 2017, 9, 8, 21, 0, 0, 0, 0, 0)]
// yyyyMMddHH-HH (2017090821-01)
[InlineData(PublicEncodingRules.BER, "180D323031373039303832312D3031", 2017, 9, 8, 21, 0, 0, 0, -1, 0)]
// yyyyMMddHH+HHmm (2017090821+0118)
[InlineData(PublicEncodingRules.BER, "180F323031373039303832312B30313138", 2017, 9, 8, 21, 0, 0, 0, 1, 18)]
// yyyyMMddHH,hourFrac (2017090821.1)
[InlineData(PublicEncodingRules.BER, "180C323031373039303832312C31", 2017, 9, 8, 21, 6, 0, 0, null, 0)]
// yyyyMMddHH.hourFracZ (2017090821.2010Z)
[InlineData(PublicEncodingRules.BER, "1810323031373039303832312E323031305A", 2017, 9, 8, 21, 12, 3, 600, 0, 0)]
// yyyyMMddHH,hourFrac-HH (2017090821,3099-01)
[InlineData(PublicEncodingRules.BER, "1812323031373039303832312C333039392D3031", 2017, 9, 8, 21, 18, 35, 640, -1, 0)]
// yyyyMMddHH.hourFrac+HHmm (2017090821.201+0118)
[InlineData(PublicEncodingRules.BER, "1813323031373039303832312E3230312B30313138", 2017, 9, 8, 21, 12, 3, 600, 1, 18)]
// yyyyMMddHHmm (201709082358)
[InlineData(PublicEncodingRules.BER, "180C323031373039303832333538", 2017, 9, 8, 23, 58, 0, 0, null, 0)]
// yyyyMMddHHmmZ (201709082358Z)
[InlineData(PublicEncodingRules.BER, "180D3230313730393038323335385A", 2017, 9, 8, 23, 58, 0, 0, 0, 0)]
// yyyyMMddHHmm-HH (201709082358-01)
[InlineData(PublicEncodingRules.BER, "180F3230313730393038323335382D3031", 2017, 9, 8, 23, 58, 0, 0, -1, 0)]
// yyyyMMddHHmm+HHmm (201709082358+0118)
[InlineData(PublicEncodingRules.BER, "18113230313730393038323335382B30313138", 2017, 9, 8, 23, 58, 0, 0, 1, 18)]
// yyyyMMddHHmm.minuteFrac (201709082358.01)
[InlineData(PublicEncodingRules.BER, "180F3230313730393038323335382E3031", 2017, 9, 8, 23, 58, 0, 600, null, 0)]
// yyyyMMddHHmm,minuteFracZ (201709082358,11Z)
[InlineData(PublicEncodingRules.BER, "18103230313730393038323335382C31315A", 2017, 9, 8, 23, 58, 6, 600, 0, 0)]
// yyyyMMddHHmm.minuteFrac-HH (201709082358.05-01)
[InlineData(PublicEncodingRules.BER, "18123230313730393038323335382E30352D3031", 2017, 9, 8, 23, 58, 3, 0, -1, 0)]
// yyyyMMddHHmm,minuteFrac+HHmm (201709082358,007+0118)
[InlineData(PublicEncodingRules.BER, "18153230313730393038323335382C3030372B30313138", 2017, 9, 8, 23, 58, 0, 420, 1, 18)]
// yyyyMMddHHmmss (20161106012345) - Ambiguous time due to DST "fall back" in US & Canada
[InlineData(PublicEncodingRules.BER, "180E3230313631313036303132333435", 2016, 11, 6, 1, 23, 45, 0, null, 0)]
// yyyyMMddHHmmssZ (20161106012345Z)
[InlineData(PublicEncodingRules.BER, "180F32303136313130363031323334355A", 2016, 11, 6, 1, 23, 45, 0, 0, 0)]
// yyyyMMddHHmmss-HH (20161106012345-01)
[InlineData(PublicEncodingRules.BER, "181132303136313130363031323334352D3031", 2016, 11, 6, 1, 23, 45, 0, -1, 0)]
// yyyyMMddHHmmss+HHmm (20161106012345+0118)
[InlineData(PublicEncodingRules.BER, "181332303136313130363031323334352B30313138", 2016, 11, 6, 1, 23, 45, 0, 1, 18)]
// yyyyMMddHHmmss.secondFrac (20161106012345.6789) - Ambiguous time due to DST "fall back" in US & Canada
[InlineData(PublicEncodingRules.BER, "181332303136313130363031323334352E36373839", 2016, 11, 6, 1, 23, 45, 678, null, 0)]
// yyyyMMddHHmmss,secondFracZ (20161106012345,7654Z)
[InlineData(PublicEncodingRules.BER, "181432303136313130363031323334352C373635345A", 2016, 11, 6, 1, 23, 45, 765, 0, 0)]
// yyyyMMddHHmmss.secondFrac-HH (20161106012345.001-01)
[InlineData(PublicEncodingRules.BER, "181532303136313130363031323334352E3030312D3031", 2016, 11, 6, 1, 23, 45, 1, -1, 0)]
// yyyyMMddHHmmss,secondFrac+HHmm (20161106012345,0009+0118)
[InlineData(PublicEncodingRules.BER, "181832303136313130363031323334352C303030392B30313138", 2016, 11, 6, 1, 23, 45, 0, 1, 18)]
// yyyyMMddHHmmssZ (20161106012345Z)
[InlineData(PublicEncodingRules.CER, "180F32303136313130363031323334355A", 2016, 11, 6, 1, 23, 45, 0, 0, 0)]
[InlineData(PublicEncodingRules.DER, "180F32303136313130363031323334355A", 2016, 11, 6, 1, 23, 45, 0, 0, 0)]
// yyyyMMddHHmmss.secondFracZ (20161106012345,7654Z)
[InlineData(PublicEncodingRules.CER, "181432303136313130363031323334352E373635345A", 2016, 11, 6, 1, 23, 45, 765, 0, 0)]
[InlineData(PublicEncodingRules.DER, "181432303136313130363031323334352E373635345A", 2016, 11, 6, 1, 23, 45, 765, 0, 0)]
public static void ParseTime_Valid(
PublicEncodingRules ruleSet,
string inputHex,
int year,
int month,
int day,
int hour,
int minute,
int second,
int millisecond,
int? offsetHour,
int offsetMinute)
{
byte[] inputData = inputHex.HexToByteArray();
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
DateTimeOffset value = reader.ReadGeneralizedTime();
Assert.False(reader.HasData, "reader.HasData");
Assert.Equal(year, value.Year);
Assert.Equal(month, value.Month);
Assert.Equal(day, value.Day);
Assert.Equal(hour, value.Hour);
Assert.Equal(minute, value.Minute);
Assert.Equal(second, value.Second);
Assert.Equal(millisecond, value.Millisecond);
TimeSpan timeOffset;
if (offsetHour == null)
{
// Ask the system what offset it thinks was relevant for that time.
// Includes DST ambiguity.
timeOffset = new DateTimeOffset(value.LocalDateTime).Offset;
}
else
{
timeOffset = new TimeSpan(offsetHour.Value, offsetMinute, 0);
}
Assert.Equal(timeOffset, value.Offset);
}
[Theory]
// yyyyMMddHH (2017090821)
[InlineData("180A32303137303930383231")]
// yyyyMMddHHZ (2017090821Z)
[InlineData("180B323031373039303832315A")]
// yyyyMMddHH-HH (2017090821-01)
[InlineData("180D323031373039303832312D3031")]
// yyyyMMddHH+HHmm (2017090821+0118)
[InlineData("180F323031373039303832312B30313138")]
// yyyyMMddHH,hourFrac (2017090821,1)
[InlineData("180C323031373039303832312C31")]
// yyyyMMddHH.hourFrac (2017090821.1)
[InlineData("180C323031373039303832312E31")]
// yyyyMMddHH,hourFracZ (2017090821,2010Z)
[InlineData("1810323031373039303832312C323031305A")]
// yyyyMMddHH.hourFracZ (2017090821.2010Z)
[InlineData("1810323031373039303832312E323031305A")]
// yyyyMMddHH,hourFrac-HH (2017090821,3099-01)
[InlineData("1812323031373039303832312C333039392D3031")]
// yyyyMMddHH.hourFrac-HH (2017090821.3099-01)
[InlineData("1812323031373039303832312E333039392D3031")]
// yyyyMMddHH,hourFrac+HHmm (2017090821,201+0118)
[InlineData("1813323031373039303832312C3230312B30313138")]
// yyyyMMddHH.hourFrac+HHmm (2017090821.201+0118)
[InlineData("1813323031373039303832312E3230312B30313138")]
// yyyyMMddHHmm (201709082358)
[InlineData("180C323031373039303832333538")]
// yyyyMMddHHmmZ (201709082358Z)
[InlineData("180D3230313730393038323335385A")]
// yyyyMMddHHmm-HH (201709082358-01)
[InlineData("180F3230313730393038323335382D3031")]
// yyyyMMddHHmm+HHmm (201709082358+0118)
[InlineData("18113230313730393038323335382B30313138")]
// yyyyMMddHHmm,minuteFrac (201709082358,01)
[InlineData("180F3230313730393038323335382C3031")]
// yyyyMMddHHmm.minuteFrac (201709082358.01)
[InlineData("180F3230313730393038323335382E3031")]
// yyyyMMddHHmm,minuteFracZ (201709082358,11Z)
[InlineData("18103230313730393038323335382C31315A")]
// yyyyMMddHHmm.minuteFracZ (201709082358.11Z)
[InlineData("18103230313730393038323335382E31315A")]
// yyyyMMddHHmm,minuteFrac-HH (201709082358m05-01)
[InlineData("18123230313730393038323335382C30352D3031")]
// yyyyMMddHHmm.minuteFrac-HH (201709082358.05-01)
[InlineData("18123230313730393038323335382E30352D3031")]
// yyyyMMddHHmm,minuteFrac+HHmm (201709082358,007+0118)
[InlineData("18153230313730393038323335382C3030372B30313138")]
// yyyyMMddHHmm.minuteFrac+HHmm (201709082358.007+0118)
[InlineData("18153230313730393038323335382E3030372B30313138")]
// yyyyMMddHHmmss (20161106012345)
[InlineData("180E3230313631313036303132333435")]
// yyyyMMddHHmmss-HH (20161106012345-01)
[InlineData("181132303136313130363031323334352D3031")]
// yyyyMMddHHmmss+HHmm (20161106012345+0118)
[InlineData("181332303136313130363031323334352B30313138")]
// yyyyMMddHHmmss,secondFrac (20161106012345,6789)
[InlineData("181332303136313130363031323334352C36373839")]
// yyyyMMddHHmmss.secondFrac (20161106012345.6789)
[InlineData("181332303136313130363031323334352E36373839")]
// yyyyMMddHHmmss,secondFracZ (20161106012345,7654Z)
[InlineData("181432303136313130363031323334352C373635345A")]
// yyyyMMddHHmmss,secondFrac-HH (20161106012345,001-01)
[InlineData("181532303136313130363031323334352C3030312D3031")]
// yyyyMMddHHmmss.secondFrac-HH (20161106012345.001-01)
[InlineData("181532303136313130363031323334352E3030312D3031")]
// yyyyMMddHHmmss,secondFrac+HHmm (20161106012345,0009+0118)
[InlineData("181832303136313130363031323334352C303030392B30313138")]
// yyyyMMddHHmmss.secondFrac+HHmm (20161106012345.0009+0118)
[InlineData("181832303136313130363031323334352E303030392B30313138")]
// yyyyMMddHHmmss.secondFrac0Z (20161106012345.76540Z)
[InlineData("181532303136313130363031323334352E37363534305A")]
// Constructed encoding of yyyyMMddHHmmssZ
[InlineData(
"3880" +
"040432303136" +
"04023131" +
"0403303630" +
"040131" +
"0405323334355A" +
"0000")]
public static void ParseTime_BerOnly(string inputHex)
{
byte[] inputData = inputHex.HexToByteArray();
AsnReader cerReader = new AsnReader(inputData, AsnEncodingRules.CER);
AsnReader derReader = new AsnReader(inputData, AsnEncodingRules.DER);
Assert.Throws<CryptographicException>(() => cerReader.ReadGeneralizedTime());
Assert.Throws<CryptographicException>(() => derReader.ReadGeneralizedTime());
// Prove it was not just corrupt input
AsnReader berReader = new AsnReader(inputData, AsnEncodingRules.BER);
berReader.ReadGeneralizedTime();
Assert.False(berReader.HasData, "berReader.HasData");
Assert.True(cerReader.HasData, "cerReader.HasData");
Assert.True(derReader.HasData, "derReader.HasData");
}
[Theory]
[InlineData(PublicEncodingRules.BER, "2017121900.06861111087Z")]
[InlineData(PublicEncodingRules.BER, "201712190004.11666665167Z")]
[InlineData(PublicEncodingRules.BER, "20171219000406.9999991Z")]
[InlineData(PublicEncodingRules.CER, "20171219000406.9999991Z")]
[InlineData(PublicEncodingRules.DER, "20171219000406.9999991Z")]
public static void MaximumEffectivePrecision(PublicEncodingRules ruleSet, string dateAscii)
{
DateTimeOffset expectedTime = new DateTimeOffset(2017, 12, 19, 0, 4, 6, TimeSpan.Zero);
expectedTime += new TimeSpan(TimeSpan.TicksPerSecond - 9);
byte[] inputData = new byte[dateAscii.Length + 2];
inputData[0] = 0x18;
inputData[1] = (byte)dateAscii.Length;
Text.Encoding.ASCII.GetBytes(dateAscii, 0, dateAscii.Length, inputData, 2);
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
Assert.Equal(expectedTime, reader.ReadGeneralizedTime());
}
[Fact]
public static void ExcessivelyPreciseFraction()
{
byte[] inputData = Text.Encoding.ASCII.GetBytes("\u0018\u002A2017092118.012345678901234567890123456789Z");
AsnReader berReader = new AsnReader(inputData, AsnEncodingRules.BER);
DateTimeOffset value = berReader.ReadGeneralizedTime();
Assert.False(berReader.HasData, "berReader.HasData");
DateTimeOffset expected = new DateTimeOffset(2017, 9, 21, 18, 0, 44, 444, TimeSpan.Zero);
expected += new TimeSpan(4440);
Assert.Equal(expected, value);
}
[Fact]
public static void ExcessivelyPreciseFraction_OneTenthPlusEpsilon()
{
byte[] inputData = Text.Encoding.ASCII.GetBytes("\u0018\u002A20170921180044.10000000000000000000000001Z");
AsnReader derReader = new AsnReader(inputData, AsnEncodingRules.DER);
DateTimeOffset value = derReader.ReadGeneralizedTime();
Assert.False(derReader.HasData, "derReader.HasData");
DateTimeOffset expected = new DateTimeOffset(2017, 9, 21, 18, 0, 44, 100, TimeSpan.Zero);
Assert.Equal(expected, value);
}
[Theory]
[InlineData(PublicEncodingRules.BER)]
[InlineData(PublicEncodingRules.CER)]
public static void MultiSegmentExcessivelyPreciseFraction(PublicEncodingRules ruleSet)
{
// This builds "20171207173522.0000...0001Z" where the Z required a second CER segment.
// This is a bit of nonsense, really, because it is encoding 1e-985 seconds, which is
// oodles of orders of magnitude smaller than Planck time (~5e-44).
// But, the spec says "any number of decimal places", and 985 is a number.
// A0 80 (context specifc 0, constructed, indefinite length)
// 04 82 03 E8 (octet string, primitive, 1000 bytes)
// ASCII("20171207173522." + new string('0', 984) + '1')
// 04 01 (octet string, primitive, 1 byte)
// ASCII("Z")
// 00 00 (end of contents)
//
// 1001 content bytes + 10 bytes of structure.
byte[] header = "A080048203E8".HexToByteArray();
byte[] contents0 = Text.Encoding.ASCII.GetBytes("20171207173522." + new string('0', 984) + "1");
byte[] cdr = { 0x04, 0x01, (byte)'Z', 0x00, 0x00 };
byte[] inputData = header.Concat(contents0).Concat(cdr).ToArray();
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
DateTimeOffset value = reader.ReadGeneralizedTime(new Asn1Tag(TagClass.ContextSpecific, 0));
DateTimeOffset expected = new DateTimeOffset(2017, 12, 7, 17, 35, 22, TimeSpan.Zero);
Assert.Equal(expected, value);
}
[Fact]
public static void ExcessivelyPreciseFraction_OneTenthPlusEpsilonAndZero()
{
byte[] inputData = Text.Encoding.ASCII.GetBytes("\u0018\u002A20170921180044.10000000000000000000000010Z");
AsnReader berReader = new AsnReader(inputData, AsnEncodingRules.BER);
DateTimeOffset value = berReader.ReadGeneralizedTime();
Assert.False(berReader.HasData, "berReader.HasData");
DateTimeOffset expected = new DateTimeOffset(2017, 9, 21, 18, 0, 44, 100, TimeSpan.Zero);
Assert.Equal(expected, value);
AsnReader cerReader = new AsnReader(inputData, AsnEncodingRules.CER);
AsnReader derReader = new AsnReader(inputData, AsnEncodingRules.DER);
Assert.Throws<CryptographicException>(() => cerReader.ReadGeneralizedTime());
Assert.Throws<CryptographicException>(() => derReader.ReadGeneralizedTime());
}
[Fact]
public static void ExcessivelyPreciseNonFraction()
{
byte[] inputData = Text.Encoding.ASCII.GetBytes("\u0018\u002A2017092118.012345678901234567890123Q56789Z");
AsnReader berReader = new AsnReader(inputData, AsnEncodingRules.BER);
Assert.Throws<CryptographicException>(() => berReader.ReadGeneralizedTime());
}
[Theory]
// yyyyMMddHH,hourFrac (2017090821,1)
[InlineData("180C323031373039303832312C31")]
// yyyyMMddHH.hourFrac (2017090821.1)
[InlineData("180C323031373039303832312E31")]
// yyyyMMddHH,hourFracZ (2017090821,2010Z)
[InlineData("1810323031373039303832312C323031305A")]
// yyyyMMddHH.hourFracZ (2017090821.2010Z)
[InlineData("1810323031373039303832312E323031305A")]
// yyyyMMddHH,hourFrac-HH (2017090821,3099-01)
[InlineData("1812323031373039303832312C333039392D3031")]
// yyyyMMddHH.hourFrac-HH (2017090821.3099-01)
[InlineData("1812323031373039303832312E333039392D3031")]
// yyyyMMddHH,hourFrac+HHmm (2017090821,201+0118)
[InlineData("1813323031373039303832312C3230312B30313138")]
// yyyyMMddHH.hourFrac+HHmm (2017090821.201+0118)
[InlineData("1813323031373039303832312E3230312B30313138")]
// yyyyMMddHHmm,minuteFrac (201709082358,01)
[InlineData("180F3230313730393038323335382C3031")]
// yyyyMMddHHmm.minuteFrac (201709082358.01)
[InlineData("180F3230313730393038323335382E3031")]
// yyyyMMddHHmm,minuteFracZ (201709082358,11Z)
[InlineData("18103230313730393038323335382C31315A")]
// yyyyMMddHHmm.minuteFracZ (201709082358.11Z)
[InlineData("18103230313730393038323335382E31315A")]
// yyyyMMddHHmm,minuteFrac-HH (201709082358m05-01)
[InlineData("18123230313730393038323335382C30352D3031")]
// yyyyMMddHHmm.minuteFrac-HH (201709082358.05-01)
[InlineData("18123230313730393038323335382E30352D3031")]
// yyyyMMddHHmm,minuteFrac+HHmm (201709082358,007+0118)
[InlineData("18153230313730393038323335382C3030372B30313138")]
// yyyyMMddHHmm.minuteFrac+HHmm (201709082358.007+0118)
[InlineData("18153230313730393038323335382E3030372B30313138")]
// yyyyMMddHHmmss,secondFrac (20161106012345,6789)
[InlineData("181332303136313130363031323334352C36373839")]
// yyyyMMddHHmmss.secondFrac (20161106012345.6789)
[InlineData("181332303136313130363031323334352E36373839")]
// yyyyMMddHHmmss,secondFracZ (20161106012345,7654Z)
[InlineData("181432303136313130363031323334352C373635345A")]
// yyyyMMddHHmmss,secondFrac-HH (20161106012345,001-01)
[InlineData("181532303136313130363031323334352C3030312D3031")]
// yyyyMMddHHmmss.secondFrac-HH (20161106012345.001-01)
[InlineData("181532303136313130363031323334352E3030312D3031")]
// yyyyMMddHHmmss,secondFrac+HHmm (20161106012345,0009+0118)
[InlineData("181832303136313130363031323334352C303030392B30313138")]
// yyyyMMddHHmmss.secondFrac+HHmm (20161106012345.0009+0118)
[InlineData("181832303136313130363031323334352E303030392B30313138")]
// yyyyMMddHHmmss.secondFrac0Z (20161106012345.76540Z)
[InlineData("181532303136313130363031323334352E37363534305A")]
public static void VerifyDisallowFraction_BER(string inputHex)
{
byte[] inputData = inputHex.HexToByteArray();
AsnReader berReader = new AsnReader(inputData, AsnEncodingRules.BER);
Assert.Throws<CryptographicException>(() => berReader.ReadGeneralizedTime(disallowFractions: true));
// Legit if the fraction is allowed
berReader.ReadGeneralizedTime();
Assert.False(berReader.HasData, "berReader.HasData");
}
[Theory]
[InlineData("Wrong Tag", "170F32303136313130363031323334355A")]
[InlineData("Incomplete Tag", "1F")]
[InlineData("No Length", "18")]
[InlineData("No payload", "180F")]
[InlineData("Length exceeds content", "181032303136313130363031323334355A")]
[InlineData("yyyyMMdd", "18083230313631313036")]
[InlineData("yyyyMMddZ", "180932303136313130365A")]
[InlineData("yyyyMMdd+HH", "180B32303136313130362D3030")]
[InlineData("yyyyMMdd-HHmm", "180D32303136313130362B30303030")]
[InlineData("yyyyMMddH", "1809323031363131303630")]
[InlineData("yyyyMMddHZ", "180A3230313631313036305A")]
[InlineData("yQyyMMddHH", "180A32513136313130363031")]
[InlineData("yyyyMQddHH", "180A32303136315130363031")]
[InlineData("yyyyMMQdHH", "180A32303136313151363031")]
[InlineData("yyyyMMddHQ", "180A32303136313130363051")]
[InlineData("yyyyMMddHH,", "180B323031363131303630312C")]
[InlineData("yyyyMMddHH.", "180B323031363131303630312E")]
[InlineData("yyyyMMddHHQ", "180B3230313631313036303151")]
[InlineData("yyyyMMddHH,Q", "180C323031363131303630312C51")]
[InlineData("yyyyMMddHH.Q", "180C323031363131303630312E51")]
[InlineData("yyyyMMddHH..", "180C323031363131303630312E2E")]
[InlineData("yyyyMMddHH-", "180B323031363131303630312B")]
[InlineData("yyyyMMddHH+", "180B323031363131303630312D")]
[InlineData("yyyyMMddHHmQ", "180C323031363131303630313251")]
[InlineData("yyyyMMddHHm+", "180C32303136313130363031322D")]
[InlineData("yyyyMMddHHmmQ", "180D32303136313130363031323351")]
[InlineData("yyyyMMddHHmm-", "180D3230313631313036303132332B")]
[InlineData("yyyyMMddHHmm,", "180D3230313631313036303132332C")]
[InlineData("yyyyMMddHHmm+", "180D3230313631313036303132332D")]
[InlineData("yyyyMMddHHmm.", "180D3230313631313036303132332E")]
[InlineData("yyyyMMddHHmm+Q", "180E3230313631313036303132332D51")]
[InlineData("yyyyMMddHHmm.Q", "180E3230313631313036303132332E51")]
[InlineData("yyyyMMddHHmm..", "180E3230313631313036303132332E2E")]
[InlineData("yyyyMMddHHmm.ss,", "18103230313631313036303132332E31312E")]
[InlineData("yyyyMMddHHmms", "180D32303136313130363031323334")]
[InlineData("yyyyMMddHHmmsQ", "180E3230313631313036303132333451")]
[InlineData("yyyyMMddHHmmss-", "180F32303136313130363031323334352B")]
[InlineData("yyyyMMddHHmmss,", "180F32303136313130363031323334352C")]
[InlineData("yyyyMMddHHmmss+", "180F32303136313130363031323334352D")]
[InlineData("yyyyMMddHHmmss.", "180F32303136313130363031323334352E")]
[InlineData("yyyyMMddHHmmssQ", "180F323031363131303630313233343551")]
[InlineData("yyyyMMddHHmmss.Q", "181032303136313130363031323334352E51")]
[InlineData("yyyyMMddHHmmss.Q", "181032303136313130363031323334352E2E")]
[InlineData("yyyyMMddHHZmm", "180D323031363131303630315A3233")]
[InlineData("yyyyMMddHHmmZss", "180F3230313631313036303132335A3435")]
[InlineData("yyyyMMddHHmmssZ.s", "181232303136313130363031323334355A2E36")]
[InlineData("yyyyMMddHH+H", "180C323031363131303630312D30")]
[InlineData("yyyyMMddHH+HQ", "180D323031363131303630312D3051")]
[InlineData("yyyyMMddHH+HHQ", "180E323031363131303630312D303051")]
[InlineData("yyyyMMddHH+HHmQ", "180F323031363131303630312D30303051")]
[InlineData("yyyyMMddHH+HHmmQ", "1810323031363131303630312D3030303151")]
[InlineData("yyyyMMdd+H", "180A32303137313230382D30")]
[InlineData("yyyyMMddH+", "180A3230313731323038302D")]
[InlineData("yyyyMMddHH+0060", "180F323031373132303830392D30303630")]
[InlineData("yyyyMMddHH-2400", "180F323031373132303830392D32343030")]
[InlineData("yyyyMMddHH-HH:mm", "1810323031373039303832312D30313A3138")]
[InlineData("yyyyMMddHHmm-HH:mm", "18123230313730393038323131302D30313A3138")]
[InlineData("yyyyMMddHHmmss-HH:mm", "181432303137303930383231313032302D30313A3138")]
[InlineData("yyyyMMddHH,hourFrac-HH:mm", "1812323031373039303832312C312D30313A3138")]
[InlineData("yyyyMMddHH.hourFrac-HH:mm", "1812323031373039303832312E312D30313A3138")]
[InlineData("yyyyMMddHHmm,minuteFrac-HH:mm", "18183230313730393038323335382C30303030352D30313A3138")]
[InlineData("yyyyMMddHHmm.minuteFrac-HH:mm", "18183230313730393038323335382E30303030352D30313A3138")]
[InlineData("yyyyMMddHHmmss,secondFrac-HH:mm", "181932303136313130363031323334352C393939392D30313A3138")]
[InlineData("yyyyMMddHHmmss.secondFrac-HH:mm", "181932303136313130363031323334352E393939392D30313A3138")]
public static void GetGeneralizedTime_Throws(string description, string inputHex)
{
_ = description;
byte[] inputData = inputHex.HexToByteArray();
AsnReader reader = new AsnReader(inputData, AsnEncodingRules.BER);
Assert.Throws<CryptographicException>(() => reader.ReadGeneralizedTime());
}
[Theory]
[InlineData(PublicEncodingRules.BER)]
[InlineData(PublicEncodingRules.CER)]
[InlineData(PublicEncodingRules.DER)]
public static void TagMustBeCorrect_Universal(PublicEncodingRules ruleSet)
{
byte[] inputData = "180F32303136313130363031323334355A".HexToByteArray();
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
AssertExtensions.Throws<ArgumentException>(
"expectedTag",
() => reader.ReadGeneralizedTime(Asn1Tag.Null));
Assert.True(reader.HasData, "HasData after bad universal tag");
Assert.Throws<CryptographicException>(
() => reader.ReadGeneralizedTime(new Asn1Tag(TagClass.ContextSpecific, 0)));
Assert.True(reader.HasData, "HasData after wrong tag");
Assert.Equal(
new DateTimeOffset(2016, 11, 6, 1, 23, 45, TimeSpan.Zero),
reader.ReadGeneralizedTime());
Assert.False(reader.HasData, "HasData after read");
}
[Theory]
[InlineData(PublicEncodingRules.BER)]
[InlineData(PublicEncodingRules.CER)]
[InlineData(PublicEncodingRules.DER)]
public static void TagMustBeCorrect_Custom(PublicEncodingRules ruleSet)
{
byte[] inputData = "850F32303136313130363031323334355A".HexToByteArray();
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
AssertExtensions.Throws<ArgumentException>(
"expectedTag",
() => reader.ReadGeneralizedTime(Asn1Tag.Null));
Assert.True(reader.HasData, "HasData after bad universal tag");
Assert.Throws<CryptographicException>(() => reader.ReadUtcTime());
Assert.True(reader.HasData, "HasData after default tag");
Assert.Throws<CryptographicException>(
() => reader.ReadGeneralizedTime(new Asn1Tag(TagClass.Application, 5)));
Assert.True(reader.HasData, "HasData after wrong custom class");
Assert.Throws<CryptographicException>(
() => reader.ReadGeneralizedTime(new Asn1Tag(TagClass.ContextSpecific, 7)));
Assert.True(reader.HasData, "HasData after wrong custom tag value");
Assert.Equal(
new DateTimeOffset(2016, 11, 6, 1, 23, 45, TimeSpan.Zero),
reader.ReadGeneralizedTime(new Asn1Tag(TagClass.ContextSpecific, 5)));
Assert.False(reader.HasData, "HasData after reading value");
}
[Theory]
[InlineData(PublicEncodingRules.BER, "180F32303136313130363031323334355A", PublicTagClass.Universal, 24)]
[InlineData(PublicEncodingRules.CER, "180F32303136313130363031323334355A", PublicTagClass.Universal, 24)]
[InlineData(PublicEncodingRules.DER, "180F32303136313130363031323334355A", PublicTagClass.Universal, 24)]
[InlineData(PublicEncodingRules.BER, "800F31393530303130323132333435365A", PublicTagClass.ContextSpecific, 0)]
[InlineData(PublicEncodingRules.CER, "4C0F31393530303130323132333435365A", PublicTagClass.Application, 12)]
[InlineData(PublicEncodingRules.DER, "DF8A460F31393530303130323132333435365A", PublicTagClass.Private, 1350)]
public static void ExpectedTag_IgnoresConstructed(
PublicEncodingRules ruleSet,
string inputHex,
PublicTagClass tagClass,
int tagValue)
{
byte[] inputData = inputHex.HexToByteArray();
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
DateTimeOffset val1 = reader.ReadGeneralizedTime(new Asn1Tag((TagClass)tagClass, tagValue, true));
Assert.False(reader.HasData);
reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
DateTimeOffset val2 = reader.ReadGeneralizedTime(new Asn1Tag((TagClass)tagClass, tagValue, false));
Assert.False(reader.HasData);
Assert.Equal(val1, val2);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
namespace OpenSim.Region.Physics.BasicPhysicsPlugin
{
public class BasicActor : PhysicsActor
{
public BasicActor(Vector3 size)
{
Size = size;
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Agent; }
set { return; }
}
public override Vector3 RotationalVelocity { get; set; }
public override bool SetAlwaysRun
{
get { return false; }
set { return; }
}
public override uint LocalID
{
set { return; }
}
public override bool Grabbed
{
set { return; }
}
public override bool Selected
{
set { return; }
}
public override float Buoyancy
{
get { return 0f; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool Flying { get; set; }
public override bool IsColliding { get; set; }
public override bool CollidingGround
{
get { return false; }
set { return; }
}
public override bool CollidingObj
{
get { return false; }
set { return; }
}
public override bool Stopped
{
get { return false; }
}
public override Vector3 Position { get; set; }
public override Vector3 Size { get; set; }
public override PrimitiveBaseShape Shape
{
set { return; }
}
public override float Mass
{
get { return 0f; }
}
public override Vector3 Force
{
get { return Vector3.Zero; }
set { return; }
}
public override int VehicleType
{
get { return 0; }
set { return; }
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleVectorParam(int param, Vector3 value)
{
}
public override void VehicleRotationParam(int param, Quaternion rotation)
{
}
public override void VehicleFlags(int param, bool remove)
{
}
public override void SetVolumeDetect(int param)
{
}
public override Vector3 CenterOfMass
{
get { return Vector3.Zero; }
}
public override Vector3 GeometricCenter
{
get { return Vector3.Zero; }
}
public override Vector3 Velocity { get; set; }
public override Vector3 Torque
{
get { return Vector3.Zero; }
set { return; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Quaternion Orientation
{
get { return Quaternion.Identity; }
set { }
}
public override Vector3 Acceleration { get; set; }
public override bool Kinematic
{
get { return true; }
set { }
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(Vector3 axis)
{
}
public override void AddForce(Vector3 force, bool pushforce)
{
}
public override void AddAngularForce(Vector3 force, bool pushforce)
{
}
public override void SetMomentum(Vector3 momentum)
{
}
public override void CrossingFailure()
{
}
public override Vector3 PIDTarget
{
set { return; }
}
public override bool PIDActive
{
get { return false; }
set { return; }
}
public override float PIDTau
{
set { return; }
}
public override float PIDHoverHeight
{
set { return; }
}
public override bool PIDHoverActive
{
set { return; }
}
public override PIDHoverType PIDHoverType
{
set { return; }
}
public override float PIDHoverTau
{
set { return; }
}
public override Quaternion APIDTarget
{
set { return; }
}
public override bool APIDActive
{
set { return; }
}
public override float APIDStrength
{
set { return; }
}
public override float APIDDamping
{
set { return; }
}
public override void SubscribeEvents(int ms)
{
}
public override void UnSubscribeEvents()
{
}
public override bool SubscribedEvents()
{
return false;
}
}
}
| |
using System;
using System.Globalization;
using Newtonsoft.Json.Linq;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Media;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Core.PropertyEditors.ValueConverters;
using Umbraco.Cms.Core.Routing;
namespace Umbraco.Extensions
{
public static class ImageCropperTemplateCoreExtensions
{
/// <summary>
/// Gets the underlying image processing service URL by the crop alias (from the "umbracoFile" property alias) on the IPublishedContent item.
/// </summary>
/// <param name="mediaItem">The IPublishedContent item.</param>
/// <param name="cropAlias">The crop alias e.g. thumbnail.</param>
/// <param name="imageUrlGenerator">The image URL generator.</param>
/// <param name="publishedValueFallback">The published value fallback.</param>
/// <param name="publishedUrlProvider">The published URL provider.</param>
/// <param name="urlMode">The url mode.</param>
/// <returns>
/// The URL of the cropped image.
/// </returns>
public static string GetCropUrl(
this IPublishedContent mediaItem,
string cropAlias,
IImageUrlGenerator imageUrlGenerator,
IPublishedValueFallback publishedValueFallback,
IPublishedUrlProvider publishedUrlProvider,
UrlMode urlMode = UrlMode.Default) => mediaItem.GetCropUrl(imageUrlGenerator, publishedValueFallback, publishedUrlProvider, cropAlias: cropAlias, useCropDimensions: true, urlMode: urlMode);
/// <summary>
/// Gets the underlying image processing service URL by the crop alias (from the "umbracoFile" property alias in the MediaWithCrops content item) on the MediaWithCrops item.
/// </summary>
/// <param name="mediaWithCrops">The MediaWithCrops item.</param>
/// <param name="cropAlias">The crop alias e.g. thumbnail.</param>
/// <param name="imageUrlGenerator">The image URL generator.</param>
/// <param name="publishedValueFallback">The published value fallback.</param>
/// <param name="publishedUrlProvider">The published URL provider.</param>
/// <param name="urlMode">The url mode.</param>
/// <returns>
/// The URL of the cropped image.
/// </returns>
public static string GetCropUrl(
this MediaWithCrops mediaWithCrops,
string cropAlias,
IImageUrlGenerator imageUrlGenerator,
IPublishedValueFallback publishedValueFallback,
IPublishedUrlProvider publishedUrlProvider,
UrlMode urlMode = UrlMode.Default) => mediaWithCrops.GetCropUrl(imageUrlGenerator, publishedValueFallback, publishedUrlProvider, cropAlias: cropAlias, useCropDimensions: true, urlMode: urlMode);
/// <summary>
/// Gets the crop URL by using only the specified <paramref name="imageCropperValue" />.
/// </summary>
/// <param name="mediaItem">The media item.</param>
/// <param name="imageCropperValue">The image cropper value.</param>
/// <param name="cropAlias">The crop alias.</param>
/// <param name="imageUrlGenerator">The image URL generator.</param>
/// <param name="publishedValueFallback">The published value fallback.</param>
/// <param name="publishedUrlProvider">The published URL provider.</param>
/// <param name="urlMode">The url mode.s</param>
/// <returns>
/// The image crop URL.
/// </returns>
public static string GetCropUrl(
this IPublishedContent mediaItem,
ImageCropperValue imageCropperValue,
string cropAlias,
IImageUrlGenerator imageUrlGenerator,
IPublishedValueFallback publishedValueFallback,
IPublishedUrlProvider publishedUrlProvider,
UrlMode urlMode = UrlMode.Default) => mediaItem.GetCropUrl(imageUrlGenerator, publishedValueFallback, publishedUrlProvider, imageCropperValue, true, cropAlias: cropAlias, useCropDimensions: true, urlMode: urlMode);
/// <summary>
/// Gets the underlying image processing service URL by the crop alias using the specified property containing the image cropper JSON data on the IPublishedContent item.
/// </summary>
/// <param name="mediaItem">The IPublishedContent item.</param>
/// <param name="propertyAlias">The property alias of the property containing the JSON data e.g. umbracoFile.</param>
/// <param name="cropAlias">The crop alias e.g. thumbnail.</param>
/// <param name="imageUrlGenerator">The image URL generator.</param>
/// <param name="publishedValueFallback">The published value fallback.</param>
/// <param name="publishedUrlProvider">The published URL provider.</param>
/// <param name="urlMode">The url mode.</param>
/// <returns>
/// The URL of the cropped image.
/// </returns>
public static string GetCropUrl(
this IPublishedContent mediaItem,
string propertyAlias,
string cropAlias,
IImageUrlGenerator imageUrlGenerator,
IPublishedValueFallback publishedValueFallback,
IPublishedUrlProvider publishedUrlProvider,
UrlMode urlMode = UrlMode.Default) => mediaItem.GetCropUrl(imageUrlGenerator, publishedValueFallback, publishedUrlProvider, propertyAlias: propertyAlias, cropAlias: cropAlias, useCropDimensions: true, urlMode: urlMode);
/// <summary>
/// Gets the underlying image processing service URL by the crop alias using the specified property containing the image cropper JSON data on the MediaWithCrops content item.
/// </summary>
/// <param name="mediaWithCrops">The MediaWithCrops item.</param>
/// <param name="propertyAlias">The property alias of the property containing the JSON data e.g. umbracoFile.</param>
/// <param name="cropAlias">The crop alias e.g. thumbnail.</param>
/// <param name="imageUrlGenerator">The image URL generator.</param>
/// <param name="publishedValueFallback">The published value fallback.</param>
/// <param name="publishedUrlProvider">The published URL provider.</param>
/// <param name="urlMode">The url mode.</param>
/// <returns>
/// The URL of the cropped image.
/// </returns>
public static string GetCropUrl(this MediaWithCrops mediaWithCrops,
IPublishedValueFallback publishedValueFallback,
IPublishedUrlProvider publishedUrlProvider,
string propertyAlias,
string cropAlias,
IImageUrlGenerator imageUrlGenerator,
UrlMode urlMode = UrlMode.Default) => mediaWithCrops.GetCropUrl(imageUrlGenerator, publishedValueFallback, publishedUrlProvider, propertyAlias: propertyAlias, cropAlias: cropAlias, useCropDimensions: true, urlMode: urlMode);
/// <summary>
/// Gets the underlying image processing service URL from the IPublishedContent item.
/// </summary>
/// <param name="mediaItem">The IPublishedContent item.</param>
/// <param name="imageUrlGenerator">The image URL generator.</param>
/// <param name="publishedValueFallback">The published value fallback.</param>
/// <param name="publishedUrlProvider">The published URL provider.</param>
/// <param name="width">The width of the output image.</param>
/// <param name="height">The height of the output image.</param>
/// <param name="propertyAlias">Property alias of the property containing the JSON data.</param>
/// <param name="cropAlias">The crop alias.</param>
/// <param name="quality">Quality percentage of the output image.</param>
/// <param name="imageCropMode">The image crop mode.</param>
/// <param name="imageCropAnchor">The image crop anchor.</param>
/// <param name="preferFocalPoint">Use focal point, to generate an output image using the focal point instead of the predefined crop.</param>
/// <param name="useCropDimensions">Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters.</param>
/// <param name="cacheBuster">Add a serialized date of the last edit of the item to ensure client cache refresh when updated.</param>
/// <param name="furtherOptions">These are any query string parameters (formatted as query strings) that ImageProcessor supports. For example:
/// <example><![CDATA[
/// furtherOptions: "bgcolor=fff"
/// ]]></example></param>
/// <param name="urlMode">The url mode.</param>
/// <returns>
/// The URL of the cropped image.
/// </returns>
public static string GetCropUrl(
this IPublishedContent mediaItem,
IImageUrlGenerator imageUrlGenerator,
IPublishedValueFallback publishedValueFallback,
IPublishedUrlProvider publishedUrlProvider,
int? width = null,
int? height = null,
string propertyAlias = Cms.Core.Constants.Conventions.Media.File,
string cropAlias = null,
int? quality = null,
ImageCropMode? imageCropMode = null,
ImageCropAnchor? imageCropAnchor = null,
bool preferFocalPoint = false,
bool useCropDimensions = false,
bool cacheBuster = true,
string furtherOptions = null,
UrlMode urlMode = UrlMode.Default) => mediaItem.GetCropUrl(imageUrlGenerator, publishedValueFallback, publishedUrlProvider, null, false, width, height, propertyAlias, cropAlias, quality, imageCropMode, imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBuster, furtherOptions, urlMode);
/// <summary>
/// Gets the underlying image processing service URL from the MediaWithCrops item.
/// </summary>
/// <param name="mediaWithCrops">The MediaWithCrops item.</param>
/// <param name="imageUrlGenerator">The image URL generator.</param>
/// <param name="publishedValueFallback">The published value fallback.</param>
/// <param name="publishedUrlProvider">The published URL provider.</param>
/// <param name="width">The width of the output image.</param>
/// <param name="height">The height of the output image.</param>
/// <param name="propertyAlias">Property alias of the property containing the JSON data.</param>
/// <param name="cropAlias">The crop alias.</param>
/// <param name="quality">Quality percentage of the output image.</param>
/// <param name="imageCropMode">The image crop mode.</param>
/// <param name="imageCropAnchor">The image crop anchor.</param>
/// <param name="preferFocalPoint">Use focal point, to generate an output image using the focal point instead of the predefined crop.</param>
/// <param name="useCropDimensions">Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters.</param>
/// <param name="cacheBuster">Add a serialized date of the last edit of the item to ensure client cache refresh when updated.</param>
/// <param name="furtherOptions">These are any query string parameters (formatted as query strings) that ImageProcessor supports. For example:
/// <example><![CDATA[
/// furtherOptions: "bgcolor=fff"
/// ]]></example></param>
/// <param name="urlMode">The url mode.</param>
/// <returns>
/// The URL of the cropped image.
/// </returns>
public static string GetCropUrl(
this MediaWithCrops mediaWithCrops,
IImageUrlGenerator imageUrlGenerator,
IPublishedValueFallback publishedValueFallback,
IPublishedUrlProvider publishedUrlProvider,
int? width = null,
int? height = null,
string propertyAlias = Constants.Conventions.Media.File,
string cropAlias = null,
int? quality = null,
ImageCropMode? imageCropMode = null,
ImageCropAnchor? imageCropAnchor = null,
bool preferFocalPoint = false,
bool useCropDimensions = false,
bool cacheBuster = true,
string furtherOptions = null,
UrlMode urlMode = UrlMode.Default)
{
if (mediaWithCrops == null)
{
throw new ArgumentNullException(nameof(mediaWithCrops));
}
return mediaWithCrops.Content.GetCropUrl(imageUrlGenerator, publishedValueFallback, publishedUrlProvider, mediaWithCrops.LocalCrops, false, width, height, propertyAlias, cropAlias, quality, imageCropMode, imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBuster, furtherOptions, urlMode);
}
private static string GetCropUrl(
this IPublishedContent mediaItem,
IImageUrlGenerator imageUrlGenerator,
IPublishedValueFallback publishedValueFallback,
IPublishedUrlProvider publishedUrlProvider,
ImageCropperValue localCrops,
bool localCropsOnly,
int? width = null,
int? height = null,
string propertyAlias = Constants.Conventions.Media.File,
string cropAlias = null,
int? quality = null,
ImageCropMode? imageCropMode = null,
ImageCropAnchor? imageCropAnchor = null,
bool preferFocalPoint = false,
bool useCropDimensions = false,
bool cacheBuster = true,
string furtherOptions = null,
UrlMode urlMode = UrlMode.Default)
{
if (mediaItem == null)
{
throw new ArgumentNullException(nameof(mediaItem));
}
if (mediaItem.HasProperty(propertyAlias) == false || mediaItem.HasValue(propertyAlias) == false)
{
return null;
}
var mediaItemUrl = mediaItem.MediaUrl(publishedUrlProvider, propertyAlias: propertyAlias, mode: urlMode);
// Only get crops from media when required and used
if (localCropsOnly == false && (imageCropMode == ImageCropMode.Crop || imageCropMode == null))
{
// Get the default cropper value from the value converter
var cropperValue = mediaItem.Value(publishedValueFallback, propertyAlias);
var mediaCrops = cropperValue as ImageCropperValue;
if (mediaCrops == null && cropperValue is JObject jobj)
{
mediaCrops = jobj.ToObject<ImageCropperValue>();
}
if (mediaCrops == null && cropperValue is string imageCropperValue &&
string.IsNullOrEmpty(imageCropperValue) == false && imageCropperValue.DetectIsJson())
{
mediaCrops = imageCropperValue.DeserializeImageCropperValue();
}
// Merge crops
if (localCrops == null)
{
localCrops = mediaCrops;
}
else if (mediaCrops != null)
{
localCrops = localCrops.Merge(mediaCrops);
}
}
var cacheBusterValue = cacheBuster ? mediaItem.UpdateDate.ToFileTimeUtc().ToString(CultureInfo.InvariantCulture) : null;
return GetCropUrl(
mediaItemUrl, imageUrlGenerator, localCrops, width, height, cropAlias, quality, imageCropMode, imageCropAnchor, preferFocalPoint, useCropDimensions,
cacheBusterValue, furtherOptions);
}
/// <summary>
/// Gets the underlying image processing service URL from the image path.
/// </summary>
/// <param name="imageUrl">The image URL.</param>
/// <param name="imageUrlGenerator">The image URL generator.</param>
/// <param name="width">The width of the output image.</param>
/// <param name="height">The height of the output image.</param>
/// <param name="imageCropperValue">The Json data from the Umbraco Core Image Cropper property editor.</param>
/// <param name="cropAlias">The crop alias.</param>
/// <param name="quality">Quality percentage of the output image.</param>
/// <param name="imageCropMode">The image crop mode.</param>
/// <param name="imageCropAnchor">The image crop anchor.</param>
/// <param name="preferFocalPoint">Use focal point to generate an output image using the focal point instead of the predefined crop if there is one.</param>
/// <param name="useCropDimensions">Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters.</param>
/// <param name="cacheBusterValue">Add a serialized date of the last edit of the item to ensure client cache refresh when updated.</param>
/// <param name="furtherOptions">These are any query string parameters (formatted as query strings) that the underlying image processing service supports. For example:
/// <example><![CDATA[
/// furtherOptions: "bgcolor=fff"
/// ]]></example></param>
/// <returns>
/// The URL of the cropped image.
/// </returns>
public static string GetCropUrl(
this string imageUrl,
IImageUrlGenerator imageUrlGenerator,
int? width = null,
int? height = null,
string imageCropperValue = null,
string cropAlias = null,
int? quality = null,
ImageCropMode? imageCropMode = null,
ImageCropAnchor? imageCropAnchor = null,
bool preferFocalPoint = false,
bool useCropDimensions = false,
string cacheBusterValue = null,
string furtherOptions = null)
{
if (string.IsNullOrWhiteSpace(imageUrl))
{
return null;
}
ImageCropperValue cropDataSet = null;
if (string.IsNullOrEmpty(imageCropperValue) == false && imageCropperValue.DetectIsJson() && (imageCropMode == ImageCropMode.Crop || imageCropMode == null))
{
cropDataSet = imageCropperValue.DeserializeImageCropperValue();
}
return GetCropUrl(
imageUrl, imageUrlGenerator, cropDataSet, width, height, cropAlias, quality, imageCropMode,
imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBusterValue, furtherOptions);
}
/// <summary>
/// Gets the underlying image processing service URL from the image path.
/// </summary>
/// <param name="imageUrl">The image URL.</param>
/// <param name="imageUrlGenerator">The generator that will process all the options and the image URL to return a full image URLs with all processing options appended.</param>
/// <param name="cropDataSet">The crop data set.</param>
/// <param name="width">The width of the output image.</param>
/// <param name="height">The height of the output image.</param>
/// <param name="cropAlias">The crop alias.</param>
/// <param name="quality">Quality percentage of the output image.</param>
/// <param name="imageCropMode">The image crop mode.</param>
/// <param name="imageCropAnchor">The image crop anchor.</param>
/// <param name="preferFocalPoint">Use focal point to generate an output image using the focal point instead of the predefined crop if there is one.</param>
/// <param name="useCropDimensions">Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters.</param>
/// <param name="cacheBusterValue">Add a serialized date of the last edit of the item to ensure client cache refresh when updated.</param>
/// <param name="furtherOptions">These are any query string parameters (formatted as query strings) that the underlying image processing service supports. For example:
/// <example><![CDATA[
/// furtherOptions: "bgcolor=fff"
/// ]]></example></param>
/// <returns>
/// The URL of the cropped image.
/// </returns>
public static string GetCropUrl(
this string imageUrl,
IImageUrlGenerator imageUrlGenerator,
ImageCropperValue cropDataSet,
int? width = null,
int? height = null,
string cropAlias = null,
int? quality = null,
ImageCropMode? imageCropMode = null,
ImageCropAnchor? imageCropAnchor = null,
bool preferFocalPoint = false,
bool useCropDimensions = false,
string cacheBusterValue = null,
string furtherOptions = null)
{
if (string.IsNullOrWhiteSpace(imageUrl))
{
return null;
}
ImageUrlGenerationOptions options;
if (cropDataSet != null && (imageCropMode == ImageCropMode.Crop || imageCropMode == null))
{
ImageCropperValue.ImageCropperCrop crop = cropDataSet.GetCrop(cropAlias);
// If a crop was specified, but not found, return null
if (crop == null && !string.IsNullOrWhiteSpace(cropAlias))
{
return null;
}
options = cropDataSet.GetCropBaseOptions(imageUrl, crop, preferFocalPoint || string.IsNullOrWhiteSpace(cropAlias));
if (crop != null && useCropDimensions)
{
width = crop.Width;
height = crop.Height;
}
// Calculate missing dimension if a predefined crop has been specified, but has no coordinates
if (crop != null && string.IsNullOrEmpty(cropAlias) == false && crop.Coordinates == null)
{
if (width != null && height == null)
{
height = (int)MathF.Round(width.Value * ((float)crop.Height / crop.Width));
}
else if (width == null && height != null)
{
width = (int)MathF.Round(height.Value * ((float)crop.Width / crop.Height));
}
}
}
else
{
options = new ImageUrlGenerationOptions(imageUrl)
{
ImageCropMode = (imageCropMode ?? ImageCropMode.Pad), // Not sure why we default to Pad
ImageCropAnchor = imageCropAnchor
};
}
options.Quality = quality;
options.Width = width;
options.Height = height;
options.FurtherOptions = furtherOptions;
options.CacheBusterValue = cacheBusterValue;
return imageUrlGenerator.GetImageUrl(options);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Timers;
using System.IO;
using RadioPlayer;
using RadioLogger;
using RadioLibrary;
namespace RadioController
{
public class Controller
{
int SecondsSpentFading;
bool islive;
/*
bool isLive {
get {
return islive;
}
set {
islive = value;
}
}
*/
public enum ControllerAction
{
Idle,
Song,
Jingle,
News,
Live
}
~Controller() {
Stop();
}
public void Dispose() {
Stop();
}
string ControllerActionToString(ControllerAction action) {
switch (action) {
case ControllerAction.Idle:
return "Idle";
case ControllerAction.Jingle:
return "Jingle";
case ControllerAction.Live:
return "Live";
case ControllerAction.News:
return "News";
case ControllerAction.Song:
return "Song";
default:
return "Unknown";
}
}
string controller_state;
public string ControllerState {
get {
return controller_state;
}
}
ISoundObject currentElement;
ControllerAction currentState;
ControllerAction lastState;
MediaFolder songs;
MediaFolder jingles;
MediaFolder news;
TimedTrigger jingleTrigger;
TimedTrigger newsTrigger;
Timer controller_timer;
IMixer mixer;
string liveURL;
HTTPServer toggleServer;
int demoLoop = -1;
bool doFade = true;
int sample = 0;
/// <summary>
/// Switches between Fading between elements or simply cutting over
/// </summary>
/// <value><c>true</c> if it should fade; otherwise, <c>false</c>.</value>
public bool DoFade {
get {
return doFade;
}
set {
doFade = value;
}
}
/// <summary>
/// If set to a value than zero the controller goes into debug mode and switches over to the next element after the specified delay in seconds
/// </summary>
/// <value>Time to fade after or zero</value>
public int Sample {
get {
return sample;
}
set {
sample = value;
}
}
public Controller(string songFolder, string jingleFolder, string newsFolder, TimedTrigger jingleTrigger, TimedTrigger newsTrigger, string liveURL) {
SecondsSpentFading = Configuration.Settings.getInt("mixer.fadetime", 3);
//Basic state
changeState("Initializing");
mixer = new VLCMixer();
controller_timer = new Timer(500);
controller_timer.AutoReset = false;
controller_timer.Elapsed += HandleClockEvent;
//this.songs = new MediaFolder(songFolder);
//this.jingles = new MediaFolder(jingleFolder);
//this.news = new MediaFolder(newsFolder);
this.newsTrigger = newsTrigger;
this.jingleTrigger = jingleTrigger;
this.liveURL = liveURL;
// TODO: Config for Port
toggleServer = new HTTPServer(3124);
changeState("Idle");
}
void changeState(string state) {
controller_state = state;
Logger.LogInformation("Controller changed state to: " + state);
}
public void Start() {
currentState = ControllerAction.Idle;
controller_timer.Start();
if (currentElement != null) {
currentElement.Playing = true;
currentElement.Volume = 100f;
}
changeState("Running");
}
public void Stop() {
controller_timer.Stop();
changeState("Idle");
}
public void Pause() {
if (currentElement != null) {
currentElement.Playing = false;
}
changeState("Paused");
}
public void fadeOut() {
if (currentElement != null) {
// TODO: fix new tracks fading in, wjile fading out
mixer.fadeTo (currentElement, 0f, SecondsSpentFading);
}
}
public void fadeIn() {
if (currentElement != null) {
currentElement.Playing = true;
mixer.fadeTo(currentElement, 100f, SecondsSpentFading);
}
}
public void Rescan() {
songs.Refresh();
jingles.Refresh();
news.Refresh();
}
public void Skip() {
currentState = ControllerAction.Idle;
// stop the current element
if (currentElement != null) {
currentElement.Playing = false;
}
Logger.LogInformation("Track Skipped");
}
void setMPlayer(ISoundObject player) {
if (currentElement != null) {
if (doFade) {
if (lastState != ControllerAction.Jingle) {
mixer.fadeTo(currentElement, 0f, SecondsSpentFading);
}
}
}
currentElement = player;
if (currentElement != null) {
currentElement.Playing = true;
if (doFade && currentState != ControllerAction.Jingle) {
currentElement.Volume = 0;
mixer.fadeTo(currentElement, 100f, SecondsSpentFading);
} else {
currentElement.Volume = 100f;
}
}
}
void HandleClockEvent(object sender, ElapsedEventArgs e) {
ISoundObject newPlayer = null;
// Do we want to go live
if (toggleServer.State == true && currentState != ControllerAction.Live) {
//Go Live
islive = true;
currentState = ControllerAction.Live;
MediaFile streammf = new MediaFile (liveURL);
setMPlayer(mixer.createSound(streammf));
} else if (toggleServer.State == false && currentState == ControllerAction.Live) {
//Go Dead
islive = false;
currentState = ControllerAction.Idle;
setMPlayer(null);
}
newsTrigger.checkTriggers();
jingleTrigger.checkTriggers();
if (!islive) {
if ((currentElement == null)
|| (doFade && (currentElement.Duration.Subtract(currentElement.Position) <= TimeSpan.FromSeconds(SecondsSpentFading)))
|| (sample > 0 && (currentElement.Position.Seconds > sample))) {
lastState = currentState;
//Chose next Action
if (demoLoop < 0) {
if (newsTrigger.PreviousTriggerChanged && currentState != ControllerAction.News) {
currentState = ControllerAction.News;
} else {
if (jingleTrigger.PreviousTriggerChanged) {
currentState = ControllerAction.Jingle;
} else {
currentState = ControllerAction.Song;
}
}
} else {
// a basic Demo Loop
demoLoop++;
if (demoLoop % 3 == 0) {
if (demoLoop == 9) {
currentState = ControllerAction.News;
demoLoop = 0;
} else {
currentState = ControllerAction.Jingle;
}
} else {
currentState = ControllerAction.Song;
}
}
Logger.LogGood("Next action: " + ControllerActionToString(currentState));
//Create new element
switch (currentState) {
case ControllerAction.Jingle:
newPlayer = mixer.createSound(jingles.pickRandomFile());
break;
case ControllerAction.News:
MediaFile nextNews = news.pickRandomFile();
newPlayer = mixer.createSound(nextNews);
break;
case ControllerAction.Song:
MediaFile mf = songs.pickRandomFile();
Logger.LogNormal("Now playing: " + mf.MetaData.ToString());
newPlayer = mixer.createSound(mf);
break;
case ControllerAction.Idle:
Logger.LogError("Controller Action was Idle");
break;
}
if (newPlayer != null) {
setMPlayer(newPlayer);
}
}
}
controller_timer.Start();
}
}
}
| |
// 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;
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 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 TTransportException(TTransportException.ExceptionType.Unknown, "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);
}
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
public class KinectManager : MonoBehaviour
{
// Public Bool to determine how many players there are. Default of one user.
public bool TwoUsers = false;
// Public Bool to determine if the sensor is used in near mode.
public bool NearMode = false;
// Public Bool to determine whether to receive and compute the user map
public bool ComputeUserMap = false;
// Public Bool to determine whether to receive and compute the color map
public bool ComputeColorMap = false;
// Public Bool to determine whether to display user map on the GUI
public bool DisplayUserMap = false;
// Public Bool to determine whether to display color map on the GUI
public bool DisplayColorMap = false;
// Public Floats to specify the width and height of the depth and color maps as % of the camera width and height
// if percents are zero, they are calculated based on actual Kinect image?s width and height
private float MapsPercentWidth = 0f;
private float MapsPercentHeight = 0f;
// How high off the ground is the sensor (in meters)
public float SensorHeight = 1.0f;
// Bools to keep track of who is currently calibrated.
bool Player1Calibrated = false;
bool Player2Calibrated = false;
bool AllPlayersCalibrated = false;
// Values to track which ID (assigned by the Kinect) is player 1 and player 2.
uint Player1ID;
uint Player2ID;
// Lists of GameObjects that will be controlled by which player.
public List<GameObject> Player1Avatars;
public List<GameObject> Player2Avatars;
// Lists of AvatarControllers that will let the models get updated.
private List<AvatarController> Player1Controllers;
private List<AvatarController> Player2Controllers;
// List of Gestures to be detected for each player
public List<KinectGestures.Gestures> Player1Gestures;
public List<KinectGestures.Gestures> Player2Gestures;
// Minimum time between gesture detections
public float MinTimeBetweenGestures = 0f;
// List of Gesture Listeners. They must implement KinectGestures.GestureListenerInterface
public List<MonoBehaviour> GestureListeners;
// GUI Text to show messages.
public GameObject CalibrationText;
// GUI Texture to display the hand cursor for Player1
public GameObject HandCursor1;
// GUI Texture to display the hand cursor for Player1
public GameObject HandCursor2;
// Bool to specify whether Left/Right-hand-cursor and the Click-gesture control the mouse cursor and click
public bool ControlMouseCursor = false;
private KinectWrapper.SkeletonJointTransformation jointTransform;
private KinectWrapper.SkeletonJointPosition jointPosition;
private KinectWrapper.SkeletonJointOrientation jointOrientation;
// User/Depth map variables
private Texture2D usersLblTex;
private Color[] usersMapColors;
private Rect usersMapRect;
private int usersMapSize;
private short[] usersLabelMap;
private short[] usersDepthMap;
private float[] usersHistogramMap;
// Color map variables
private Texture2D usersClrTex;
private Color32[] usersClrColors;
private Rect usersClrRect;
private int usersClrSize;
private byte[] usersColorMap;
// List of all users
private List<uint> allUsers;
// Bool to keep track of whether OpenNI has been initialized
private bool KinectInitialized = false;
// The single instance of KinectManager
private static KinectManager instance;
private short[] oniUsers = new short[KinectWrapper.Constants.SkeletonCount];
private short[] oniStates = new short[KinectWrapper.Constants.SkeletonCount];
private Int32 oniUsersCount = 0;
// gestures data and parameters
private List<KinectGestures.GestureData> player1Gestures = new List<KinectGestures.GestureData>();
private List<KinectGestures.GestureData> player2Gestures = new List<KinectGestures.GestureData>();
private float gestureTrackingAtTime1 = 0f, gestureTrackingAtTime2 = 0f;
// List of Gesture Listeners. They must implement KinectGestures.GestureListenerInterface
public List<KinectGestures.GestureListenerInterface> gestureListeners;
// returns the single KinectManager instance
public static KinectManager Instance
{
get
{
return instance;
}
}
// checks if Kinect is initialized and ready to use. If not, there was an error during Kinect-sensor initialization
public static bool IsKinectInitialized()
{
return instance != null ? instance.KinectInitialized : false;
}
// checks if Kinect is initialized and ready to use. If not, there was an error during Kinect-sensor initialization
public bool IsInitialized()
{
return KinectInitialized;
}
// this function is used internally by AvatarController
public static bool IsCalibrationNeeded()
{
return true;
}
// returns the raw depth/user data,if ComputeUserMap is true
public short[] GetUsersDepthMap()
{
return usersDepthMap;
}
// returns the depth image/users histogram texture,if ComputeUserMap is true
public Texture2D GetUsersLblTex()
{
return usersLblTex;
}
// returns the color image texture,if ComputeColorMap is true
public Texture2D GetUsersClrTex()
{
return usersClrTex;
}
// returns true if at least one user is currently detected by the sensor
public bool IsUserDetected()
{
return KinectInitialized && (allUsers.Count > 0);
}
// returns the UserID of Player1, or 0 if no Player1 is detected
public uint GetPlayer1ID()
{
return Player1ID;
}
// returns the UserID of Player2, or 0 if no Player2 is detected
public uint GetPlayer2ID()
{
return Player2ID;
}
// returns true if the User is calibrated and ready to use
public bool IsPlayerCalibrated(uint UserId)
{
if(UserId == Player1ID)
return Player1Calibrated;
else if(UserId == Player2ID)
return Player2Calibrated;
return false;
}
// returns the User position, relative to the Kinect-sensor, in meters
public Vector3 GetUserPosition(uint UserId)
{
if(KinectWrapper.GetJointPosition(UserId, (int)KinectWrapper.SkeletonJoint.HIPS, ref jointPosition))
{
return new Vector3(jointPosition.x * 0.001f, jointPosition.y * 0.001f + SensorHeight, jointPosition.z * 0.001f);
}
return Vector3.zero;
}
// returns the User rotation, relative to the Kinect-sensor
public Quaternion GetUserOrientation(uint UserId, bool flip)
{
Quaternion rotUser = Quaternion.identity;
if(KinectWrapper.GetSkeletonJointOrientation(UserId, (int)KinectWrapper.SkeletonJoint.HIPS, flip, ref rotUser))
{
//Quaternion quat = ConvertMatrixToQuat(jointOrientation, (int)KinectWrapper.SkeletonJoint.HIPS, flip);
//return quat;
return rotUser;
}
return Quaternion.identity;
}
// returns true if the given joint's position is being tracked
public bool IsJointPositionTracked(uint UserId, int joint)
{
float fConfidence = KinectWrapper.GetJointPositionConfidence(UserId, joint);
return fConfidence > 0.5;
}
// returns true if the given joint's orientation is being tracked
public bool IsJointOrientationTracked(uint UserId, int joint)
{
float fConfidence = KinectWrapper.GetJointOrientationConfidence(UserId, joint);
return fConfidence > 0.5;
}
// returns the joint position of the specified user, relative to the Kinect-sensor, in meters
public Vector3 GetJointPosition(uint UserId, int joint)
{
if(KinectWrapper.GetJointPosition(UserId, joint, ref jointPosition))
{
return new Vector3(jointPosition.x * 0.001f, jointPosition.y * 0.001f + SensorHeight, jointPosition.z * 0.001f);
}
return Vector3.zero;
}
// returns the joint rotation of the specified user, relative to the Kinect-sensor
public Quaternion GetJointOrientation(uint UserId, int joint, bool flip)
{
Quaternion rotJoint = Quaternion.identity;
if(KinectWrapper.GetSkeletonJointOrientation(UserId, joint, flip, ref rotJoint))
{
//Quaternion quat = ConvertMatrixToQuat(jointOrientation, joint, flip);
//return quat;
return rotJoint;
}
return Quaternion.identity;
}
// adds a gesture to the list of detected gestures for the specified user
public void DetectGesture(uint UserId, KinectGestures.Gestures gesture)
{
int index = GetGestureIndex(UserId, gesture);
if(index >= 0)
DeleteGesture(UserId, gesture);
KinectGestures.GestureData gestureData = new KinectGestures.GestureData();
gestureData.userId = UserId;
gestureData.gesture = gesture;
gestureData.state = 0;
gestureData.joint = 0;
gestureData.progress = 0f;
gestureData.complete = false;
gestureData.cancelled = false;
gestureData.checkForGestures = new List<KinectGestures.Gestures>();
switch(gesture)
{
case KinectGestures.Gestures.ZoomIn:
gestureData.checkForGestures.Add(KinectGestures.Gestures.ZoomOut);
gestureData.checkForGestures.Add(KinectGestures.Gestures.Wheel);
break;
case KinectGestures.Gestures.ZoomOut:
gestureData.checkForGestures.Add(KinectGestures.Gestures.ZoomIn);
gestureData.checkForGestures.Add(KinectGestures.Gestures.Wheel);
break;
case KinectGestures.Gestures.Wheel:
gestureData.checkForGestures.Add(KinectGestures.Gestures.ZoomIn);
gestureData.checkForGestures.Add(KinectGestures.Gestures.ZoomOut);
break;
// case KinectGestures.Gestures.Jump:
// gestureData.checkForGestures.Add(KinectGestures.Gestures.Squat);
// break;
//
// case KinectGestures.Gestures.Squat:
// gestureData.checkForGestures.Add(KinectGestures.Gestures.Jump);
// break;
//
// case KinectGestures.Gestures.Push:
// gestureData.checkForGestures.Add(KinectGestures.Gestures.Pull);
// break;
//
// case KinectGestures.Gestures.Pull:
// gestureData.checkForGestures.Add(KinectGestures.Gestures.Push);
// break;
}
if(UserId == Player1ID)
player1Gestures.Add(gestureData);
else if(UserId == Player2ID)
player2Gestures.Add(gestureData);
}
// resets the gesture-data state for the given gesture of the specified user
public bool ResetGesture(uint UserId, KinectGestures.Gestures gesture)
{
int index = GetGestureIndex(UserId, gesture);
if(index < 0)
return false;
KinectGestures.GestureData gestureData = (UserId == Player1ID) ? player1Gestures[index] : player2Gestures[index];
gestureData.state = 0;
gestureData.joint = 0;
gestureData.progress = 0f;
gestureData.complete = false;
gestureData.cancelled = false;
gestureData.startTrackingAtTime = Time.realtimeSinceStartup + KinectWrapper.Constants.MinTimeBetweenSameGestures;
if(UserId == Player1ID)
player1Gestures[index] = gestureData;
else if(UserId == Player2ID)
player2Gestures[index] = gestureData;
return true;
}
// resets the gesture-data states for all detected gestures of the specified user
public void ResetPlayerGestures(uint UserId)
{
if(UserId == Player1ID)
{
int listSize = player1Gestures.Count;
for(int i = 0; i < listSize; i++)
{
ResetGesture(UserId, player1Gestures[i].gesture);
}
}
else if(UserId == Player2ID)
{
int listSize = player2Gestures.Count;
for(int i = 0; i < listSize; i++)
{
ResetGesture(UserId, player2Gestures[i].gesture);
}
}
}
// deletes the given gesture from the list of detected gestures for the specified user
public bool DeleteGesture(uint UserId, KinectGestures.Gestures gesture)
{
int index = GetGestureIndex(UserId, gesture);
if(index < 0)
return false;
if(UserId == Player1ID)
player1Gestures.RemoveAt(index);
else if(UserId == Player2ID)
player2Gestures.RemoveAt(index);
return true;
}
// clears detected gestures list for the specified user
public void ClearGestures(uint UserId)
{
if(UserId == Player1ID)
{
player1Gestures.Clear();
}
else if(UserId == Player2ID)
{
player2Gestures.Clear();
}
}
// returns the count of detected gestures in the list of detected gestures for the specified user
public int GetGesturesCount(uint UserId)
{
if(UserId == Player1ID)
return player1Gestures.Count;
else if(UserId == Player2ID)
return player2Gestures.Count;
return 0;
}
// returns the list of detected gestures for the specified user
public List<KinectGestures.Gestures> GetGesturesList(uint UserId)
{
List<KinectGestures.Gestures> list = new List<KinectGestures.Gestures>();
if(UserId == Player1ID)
{
foreach(KinectGestures.GestureData data in player1Gestures)
list.Add(data.gesture);
}
else if(UserId == Player2ID)
{
foreach(KinectGestures.GestureData data in player1Gestures)
list.Add(data.gesture);
}
return list;
}
// returns true, if the given gesture is in the list of detected gestures for the specified user
public bool IsGestureDetected(uint UserId, KinectGestures.Gestures gesture)
{
int index = GetGestureIndex(UserId, gesture);
return index >= 0;
}
// returns true, if the given gesture for the specified user is complete
public bool IsGestureComplete(uint UserId, KinectGestures.Gestures gesture, bool bResetOnComplete)
{
int index = GetGestureIndex(UserId, gesture);
if(index >= 0)
{
if(UserId == Player1ID)
{
KinectGestures.GestureData gestureData = player1Gestures[index];
if(bResetOnComplete && gestureData.complete)
{
ResetPlayerGestures(UserId);
return true;
}
return gestureData.complete;
}
else if(UserId == Player2ID)
{
KinectGestures.GestureData gestureData = player2Gestures[index];
if(bResetOnComplete && gestureData.complete)
{
ResetPlayerGestures(UserId);
return true;
}
return gestureData.complete;
}
}
return false;
}
// returns true, if the given gesture for the specified user is cancelled
public bool IsGestureCancelled(uint UserId, KinectGestures.Gestures gesture)
{
int index = GetGestureIndex(UserId, gesture);
if(index >= 0)
{
if(UserId == Player1ID)
{
KinectGestures.GestureData gestureData = player1Gestures[index];
return gestureData.cancelled;
}
else if(UserId == Player2ID)
{
KinectGestures.GestureData gestureData = player2Gestures[index];
return gestureData.cancelled;
}
}
return false;
}
// returns the progress in range [0, 1] of the given gesture for the specified user
public float GetGestureProgress(uint UserId, KinectGestures.Gestures gesture)
{
int index = GetGestureIndex(UserId, gesture);
if(index >= 0)
{
if(UserId == Player1ID)
{
KinectGestures.GestureData gestureData = player1Gestures[index];
return gestureData.progress;
}
else if(UserId == Player2ID)
{
KinectGestures.GestureData gestureData = player2Gestures[index];
return gestureData.progress;
}
}
return 0f;
}
// returns the current "screen position" of the given gesture for the specified user
public Vector3 GetGestureScreenPos(uint UserId, KinectGestures.Gestures gesture)
{
int index = GetGestureIndex(UserId, gesture);
if(index >= 0)
{
if(UserId == Player1ID)
{
KinectGestures.GestureData gestureData = player1Gestures[index];
return gestureData.screenPos;
}
else if(UserId == Player2ID)
{
KinectGestures.GestureData gestureData = player2Gestures[index];
return gestureData.screenPos;
}
}
return Vector3.zero;
}
// recreates and reinitializes the lists of avatar controllers, after the list of avatars for player 1/2 was changed
public void SetAvatarControllers()
{
if(Player1Avatars.Count == 0 && Player2Avatars.Count == 0)
{
AvatarController[] avatars = FindObjectsOfType(typeof(AvatarController)) as AvatarController[];
foreach(AvatarController avatar in avatars)
{
Player1Avatars.Add(avatar.gameObject);
}
}
if(Player1Controllers != null)
{
Player1Controllers.Clear();
foreach(GameObject avatar in Player1Avatars)
{
if(avatar != null && avatar.activeInHierarchy)
{
AvatarController controller = avatar.GetComponent<AvatarController>();
controller.RotateToInitialPosition();
controller.Start();
Player1Controllers.Add(controller);
}
}
}
if(Player2Controllers != null)
{
Player2Controllers.Clear();
foreach(GameObject avatar in Player2Avatars)
{
if(avatar != null && avatar.activeInHierarchy)
{
AvatarController controller = avatar.GetComponent<AvatarController>();
controller.RotateToInitialPosition();
controller.Start();
Player2Controllers.Add(controller);
}
}
}
}
// removes the currently detected kinect users, allowing a new detection/calibration process to start
public void ClearKinectUsers()
{
if(!KinectInitialized)
return;
// remove current users
for(int i = allUsers.Count - 1; i >= 0; i--)
{
uint userId = allUsers[i];
OnUserLost(userId);
}
//ResetFilters();
}
//----------------------------------- end of public functions --------------------------------------//
void Awake()
{
//CalibrationText = GameObject.Find("CalibrationText");
try
{
if(KinectWrapper.CheckOpenNIPresence())
{
// reload the same level
Application.LoadLevel(Application.loadedLevel);
}
}
catch (Exception ex)
{
Debug.LogError(ex.ToString());
if(CalibrationText != null)
{
CalibrationText.guiText.text = ex.Message;
}
}
}
void Start()
{
try
{
// Initialize the OpenNI/NiTE wrapper
int rc = KinectWrapper.Init(ComputeUserMap, ComputeColorMap);
if (rc != 0)
{
throw new Exception(String.Format("Error initing OpenNI: {0}", Marshal.PtrToStringAnsi(KinectWrapper.GetLastErrorString())));
}
// get the main camera rectangle
Rect cameraRect = Camera.main.pixelRect;
// calculate map width and height in percent, if needed
if(MapsPercentWidth == 0f)
MapsPercentWidth = (KinectWrapper.GetDepthWidth() / 2) / cameraRect.width;
if(MapsPercentHeight == 0f)
MapsPercentHeight = (KinectWrapper.GetDepthHeight() / 2) / cameraRect.height;
if(ComputeUserMap)
{
// Initialize depth & label map related stuff
usersMapSize = KinectWrapper.GetDepthWidth() * KinectWrapper.GetDepthHeight();
usersLblTex = new Texture2D(KinectWrapper.GetDepthWidth(), KinectWrapper.GetDepthHeight());
usersMapColors = new Color[usersMapSize];
//usersMapRect = new Rect(Screen.width, Screen.height - usersLblTex.height / 2, -usersLblTex.width / 2, usersLblTex.height / 2);
usersMapRect = new Rect(cameraRect.width, cameraRect.height - cameraRect.height * MapsPercentHeight, -cameraRect.width * MapsPercentWidth, cameraRect.height * MapsPercentHeight);
usersLabelMap = new short[usersMapSize];
usersDepthMap = new short[usersMapSize];
usersHistogramMap = new float[8192];
}
if(ComputeColorMap)
{
// Initialize color map related stuff
usersClrSize = KinectWrapper.GetColorWidth() * KinectWrapper.GetColorHeight();
usersClrTex = new Texture2D(KinectWrapper.GetColorWidth(), KinectWrapper.GetColorHeight());
usersClrColors = new Color32[usersClrSize];
//usersClrRect = new Rect(Screen.width, Screen.height - usersClrTex.height / 2, -usersClrTex.width / 2, usersClrTex.height / 2);
usersClrRect = new Rect(cameraRect.width, cameraRect.height - cameraRect.height * MapsPercentHeight, -cameraRect.width * MapsPercentWidth, cameraRect.height * MapsPercentHeight);
if(ComputeUserMap)
usersMapRect.x -= cameraRect.width * MapsPercentWidth; //usersClrTex.width / 2;
usersColorMap = new byte[usersClrSize * 3];
}
// Initialize user list to contain ALL users.
allUsers = new List<uint>();
// // Initialize user callbacks.
// NewUser = new KinectWrapper.UserDelegate(OnNewUser);
// CalibrationStarted = new KinectWrapper.UserDelegate(OnCalibrationStarted);
// CalibrationFailed = new KinectWrapper.UserDelegate(OnCalibrationFailed);
// CalibrationSuccess = new KinectWrapper.UserDelegate(OnCalibrationSuccess);
// UserLost = new KinectWrapper.UserDelegate(OnUserLost);
// try to automatically find the available avatar controllers in the scene
if(Player1Avatars.Count == 0 && Player2Avatars.Count == 0)
{
AvatarController[] avatars = FindObjectsOfType(typeof(AvatarController)) as AvatarController[];
foreach(AvatarController avatar in avatars)
{
Player1Avatars.Add(avatar.gameObject);
}
}
// Pull the AvatarController from each of the players Avatars.
Player1Controllers = new List<AvatarController>();
Player2Controllers = new List<AvatarController>();
// Add each of the avatars' controllers into a list for each player.
foreach(GameObject avatar in Player1Avatars)
{
Player1Controllers.Add(avatar.GetComponent<AvatarController>());
}
foreach(GameObject avatar in Player2Avatars)
{
Player2Controllers.Add(avatar.GetComponent<AvatarController>());
}
// create the list of gesture listeners
gestureListeners = new List<KinectGestures.GestureListenerInterface>();
foreach(MonoBehaviour script in GestureListeners)
{
if(script && (script is KinectGestures.GestureListenerInterface))
{
KinectGestures.GestureListenerInterface listener = (KinectGestures.GestureListenerInterface)script;
gestureListeners.Add(listener);
}
}
// GUI Text.
if(CalibrationText != null)
{
CalibrationText.guiText.text = "WAITING FOR USERS";
}
// Start looking for users.
//KinectWrapper.StartLookingForUsers(NewUser, CalibrationStarted, CalibrationFailed, CalibrationSuccess, UserLost);
KinectWrapper.StartLookingForUsers(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
Debug.Log("Waiting for users to calibrate");
// Set the default smoothing for the Kinect.
KinectWrapper.SetSkeletonSmoothing(0.7f);
instance = this;
KinectInitialized = true;
DontDestroyOnLoad(gameObject);
}
catch(DllNotFoundException ex)
{
Debug.LogError(ex.ToString());
if(CalibrationText != null)
CalibrationText.guiText.text = "Please check the OpenNI and NITE installations.";
}
catch (Exception ex)
{
Debug.LogError(ex.ToString());
if(CalibrationText != null)
CalibrationText.guiText.text = ex.Message;
}
}
void Update()
{
if(KinectInitialized)
{
// Update to the next frame.
oniUsersCount = oniUsers.Length;
KinectWrapper.Update(oniUsers, oniStates, ref oniUsersCount);
// Process the new, lost and calibrated user(s)
if(oniUsersCount > 0)
{
for(int i = 0; i < oniUsersCount; i++)
{
uint userId = (uint)oniUsers[i];
short userState = oniStates[i];
switch(userState)
{
case 1: // new user
OnNewUser(userId);
break;
case 2: // calibration started
OnCalibrationStarted(userId);
break;
case 3: // calibration succeeded
OnCalibrationSuccess(userId);
break;
case 4: // calibration failed
OnCalibrationFailed(userId);
break;
case 5: // user lost
OnUserLost(userId);
break;
}
}
}
// Draw the user map
if(ComputeUserMap)
{
UpdateUserMap();
}
// Draw the color map
if(ComputeColorMap)
{
UpdateColorMap();
}
if(Player1Calibrated)
{
// Update player 1's models
foreach (AvatarController controller in Player1Controllers)
{
//if(controller.Active)
{
controller.UpdateAvatar(Player1ID, NearMode);
}
}
// Check for player 1's gestures
CheckForGestures(Player1ID, ref player1Gestures, ref gestureTrackingAtTime1);
// Check for complete gestures
foreach(KinectGestures.GestureData gestureData in player1Gestures)
{
if(gestureData.complete)
{
if(gestureData.gesture == KinectGestures.Gestures.Click)
{
if(ControlMouseCursor)
{
MouseControl.MouseClick();
}
}
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
if(listener.GestureCompleted(Player1ID, 0, gestureData.gesture,
(KinectWrapper.SkeletonJoint)gestureData.joint, gestureData.screenPos))
{
ResetPlayerGestures(Player1ID);
}
}
}
else if(gestureData.cancelled)
{
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
if(listener.GestureCancelled(Player1ID, 0, gestureData.gesture,
(KinectWrapper.SkeletonJoint)gestureData.joint))
{
ResetGesture(Player1ID, gestureData.gesture);
}
}
}
else if(gestureData.progress >= 0.1f)
{
if((gestureData.gesture == KinectGestures.Gestures.RightHandCursor ||
gestureData.gesture == KinectGestures.Gestures.LeftHandCursor) &&
gestureData.progress >= 0.5f)
{
if(HandCursor1 != null)
{
HandCursor1.transform.position = Vector3.Lerp(HandCursor1.transform.position, gestureData.screenPos, 3 * Time.deltaTime);
}
if(ControlMouseCursor)
{
MouseControl.MouseMove(gestureData.screenPos);
}
}
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
listener.GestureInProgress(Player1ID, 0, gestureData.gesture, gestureData.progress,
(KinectWrapper.SkeletonJoint)gestureData.joint, gestureData.screenPos);
}
}
}
}
// Update player 2's models
if(Player2Calibrated)
{
foreach (AvatarController controller in Player2Controllers)
{
//if(controller.Active)
{
controller.UpdateAvatar(Player2ID, NearMode);
}
}
// Check for player 2's gestures
CheckForGestures(Player2ID, ref player2Gestures, ref gestureTrackingAtTime2);
// Check for complete gestures
foreach(KinectGestures.GestureData gestureData in player2Gestures)
{
if(gestureData.complete)
{
if(gestureData.gesture == KinectGestures.Gestures.Click)
{
if(ControlMouseCursor)
{
MouseControl.MouseClick();
}
}
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
if(listener.GestureCompleted(Player2ID, 1, gestureData.gesture,
(KinectWrapper.SkeletonJoint)gestureData.joint, gestureData.screenPos))
{
ResetPlayerGestures(Player2ID);
}
}
}
else if(gestureData.cancelled)
{
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
if(listener.GestureCancelled(Player2ID, 1, gestureData.gesture,
(KinectWrapper.SkeletonJoint)gestureData.joint))
{
ResetGesture(Player2ID, gestureData.gesture);
}
}
}
else if(gestureData.progress >= 0.1f)
{
if((gestureData.gesture == KinectGestures.Gestures.RightHandCursor ||
gestureData.gesture == KinectGestures.Gestures.LeftHandCursor) &&
gestureData.progress >= 0.5f)
{
if(HandCursor2 != null)
{
HandCursor2.transform.position = Vector3.Lerp(HandCursor2.transform.position, gestureData.screenPos, 3 * Time.deltaTime);
}
if(ControlMouseCursor)
{
MouseControl.MouseMove(gestureData.screenPos);
}
}
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
listener.GestureInProgress(Player2ID, 1, gestureData.gesture, gestureData.progress,
(KinectWrapper.SkeletonJoint)gestureData.joint, gestureData.screenPos);
}
}
}
}
}
// Kill the program with ESC.
if(Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
}
// Make sure to kill the Kinect on quitting.
void OnApplicationQuit()
{
if(KinectInitialized)
{
// Shutdown OpenNI
KinectWrapper.Shutdown();
instance = null;
}
}
// Draw the Histogram Map on the GUI.
void OnGUI()
{
if(KinectInitialized)
{
if(ComputeUserMap && (/**(allUsers.Count == 0) ||*/ DisplayUserMap))
{
GUI.DrawTexture(usersMapRect, usersLblTex);
}
if(ComputeColorMap && (/**(allUsers.Count == 0) ||*/ DisplayColorMap))
{
GUI.DrawTexture(usersClrRect, usersClrTex);
}
}
}
// Update / draw the User Map
void UpdateUserMap()
{
IntPtr pLabelMap = KinectWrapper.GetUsersLabelMap();
IntPtr pDepthMap = KinectWrapper.GetUsersDepthMap();
if(pLabelMap == IntPtr.Zero || pDepthMap == IntPtr.Zero)
return;
// copy over the maps
Marshal.Copy(pLabelMap, usersLabelMap, 0, usersMapSize);
Marshal.Copy(pDepthMap, usersDepthMap, 0, usersMapSize);
// Flip the texture as we convert label map to color array
int flipIndex, i;
int numOfPoints = 0;
Array.Clear(usersHistogramMap, 0, usersHistogramMap.Length);
// Calculate cumulative histogram for depth
for (i = 0; i < usersMapSize; i++)
{
// Only calculate for depth that contains users
if (usersLabelMap[i] != 0)
{
usersHistogramMap[usersDepthMap[i]]++;
numOfPoints++;
}
}
if (numOfPoints > 0)
{
for (i = 1; i < usersHistogramMap.Length; i++)
{
usersHistogramMap[i] += usersHistogramMap[i-1];
}
for (i = 0; i < usersHistogramMap.Length; i++)
{
usersHistogramMap[i] = 1.0f - (usersHistogramMap[i] / numOfPoints);
}
}
// Create the actual users texture based on label map and depth histogram
for (i = 0; i < usersMapSize; i++)
{
flipIndex = usersMapSize - i - 1;
if (usersLabelMap[i] == 0)
{
usersMapColors[flipIndex] = Color.clear;
}
else
{
// Create a blending color based on the depth histogram
float histVal = usersHistogramMap[usersDepthMap[i]];
Color c = new Color(histVal, histVal, histVal, 0.9f);
switch (usersLabelMap[i] % 4)
{
case 0:
usersMapColors[flipIndex] = Color.red * c;
break;
case 1:
usersMapColors[flipIndex] = Color.green * c;
break;
case 2:
usersMapColors[flipIndex] = Color.blue * c;
break;
case 3:
usersMapColors[flipIndex] = Color.magenta * c;
break;
}
}
}
// Draw it!
usersLblTex.SetPixels(usersMapColors);
usersLblTex.Apply();
}
// Update / draw the User Map
void UpdateColorMap()
{
IntPtr pColorMap = KinectWrapper.GetUsersColorMap();
if(pColorMap == IntPtr.Zero)
return;
// copy over the map
Marshal.Copy(pColorMap, usersColorMap, 0, usersClrSize * 3);
// Flip the texture as we convert color map to color array
int index = 0, flipIndex;
// Create the actual users texture based on label map and depth histogram
for (int i = 0; i < usersClrSize; i++)
{
flipIndex = usersClrSize - i - 1;
usersClrColors[flipIndex].r = usersColorMap[index];
usersClrColors[flipIndex].g = usersColorMap[index + 1];
usersClrColors[flipIndex].b = usersColorMap[index + 2];
usersClrColors[flipIndex].a = 230;
index += 3;
}
// Draw it!
usersClrTex.SetPixels32(usersClrColors);
usersClrTex.Apply();
}
// // Add model to player list.
// void AddAvatar(GameObject avatar, List<GameObject> whichPlayerList)
// {
// whichPlayerList.Add(avatar);
// }
//
// // Remove model from player list.
// void RemoveAvatar(GameObject avatar, List<GameObject> whichPlayerList)
// {
// whichPlayerList.Remove(avatar);
// }
// // Functions that let you recalibrate either player 1 or player 2.
// void RecalibratePlayer1()
// {
// OnUserLost(Player1ID);
// }
//
// void RecalibratePlayer2()
// {
// OnUserLost(Player2ID);
// }
// When a new user enters, add it to the list.
void OnNewUser(uint UserId)
{
Debug.Log(String.Format("[{0}] New user", UserId));
//allUsers.Add(UserId);
}
// Print out when the user begins calibration.
void OnCalibrationStarted(uint UserId)
{
Debug.Log(String.Format("[{0}] Calibration started", UserId));
if(CalibrationText != null)
{
CalibrationText.guiText.text = "CALIBRATING...PLEASE HOLD STILL";
}
}
// Alert us when the calibration fails.
void OnCalibrationFailed(uint UserId)
{
Debug.Log(String.Format("[{0}] Calibration failed", UserId));
if(CalibrationText != null)
{
CalibrationText.guiText.text = "WAITING FOR USERS";
}
}
// If a user successfully calibrates, assign him/her to player 1 or 2.
void OnCalibrationSuccess(uint UserId)
{
Debug.Log(String.Format("[{0}] Calibration success", UserId));
// If player 1 hasn't been calibrated, assign that UserID to it.
if(!Player1Calibrated)
{
// Check to make sure we don't accidentally assign player 2 to player 1.
if (!allUsers.Contains(UserId))
{
Player1Calibrated = true;
Player1ID = UserId;
allUsers.Add(UserId);
foreach(AvatarController controller in Player1Controllers)
{
controller.SuccessfulCalibration(UserId);
}
// add the gestures to detect, if any
foreach(KinectGestures.Gestures gesture in Player1Gestures)
{
DetectGesture(UserId, gesture);
}
// notify the gesture listeners about the new user
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
listener.UserDetected(UserId, 0);
}
// If we're not using 2 users, we're all calibrated.
//if(!TwoUsers)
{
AllPlayersCalibrated = !TwoUsers ? allUsers.Count >= 1 : allUsers.Count >= 2; // true;
}
}
}
else if(TwoUsers && !Player2Calibrated)
{
if (!allUsers.Contains(UserId))
{
Player2Calibrated = true;
Player2ID = UserId;
allUsers.Add(UserId);
foreach(AvatarController controller in Player2Controllers)
{
controller.SuccessfulCalibration(UserId);
}
// add the gestures to detect, if any
foreach(KinectGestures.Gestures gesture in Player2Gestures)
{
DetectGesture(UserId, gesture);
}
// notify the gesture listeners about the new user
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
listener.UserDetected(UserId, 1);
}
// All users are calibrated!
AllPlayersCalibrated = !TwoUsers ? allUsers.Count >= 1 : allUsers.Count >= 2; // true;
}
}
// If all users are calibrated, stop trying to find them.
if(AllPlayersCalibrated)
{
Debug.Log("All players calibrated.");
if(CalibrationText != null)
{
CalibrationText.guiText.text = "";
}
KinectWrapper.StopLookingForUsers();
}
}
// If a user walks out of the kinects all-seeing eye, try to reassign them! Or, assign a new user to player 1.
void OnUserLost(uint UserId)
{
Debug.Log(String.Format("[{0}] User lost", UserId));
// If we lose player 1...
if(UserId == Player1ID)
{
// Null out the ID and reset all the models associated with that ID.
Player1ID = 0;
Player1Calibrated = false;
foreach(AvatarController controller in Player1Controllers)
{
controller.RotateToCalibrationPose(UserId, IsCalibrationNeeded());
}
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
listener.UserLost(UserId, 0);
}
// Try to replace that user!
Debug.Log("Starting looking for users");
//KinectWrapper.StartLookingForUsers(NewUser, CalibrationStarted, CalibrationFailed, CalibrationSuccess, UserLost);
KinectWrapper.StartLookingForUsers(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
if(CalibrationText != null)
{
CalibrationText.guiText.text = "WAITING FOR USERS";
}
}
// If we lose player 2...
if(UserId == Player2ID)
{
// Null out the ID and reset all the models associated with that ID.
Player2ID = 0;
Player2Calibrated = false;
foreach(AvatarController controller in Player2Controllers)
{
controller.RotateToCalibrationPose(UserId, IsCalibrationNeeded());
}
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
listener.UserLost(UserId, 1);
}
// Try to replace that user!
Debug.Log("Starting looking for users");
//KinectWrapper.StartLookingForUsers(NewUser, CalibrationStarted, CalibrationFailed, CalibrationSuccess, UserLost);
KinectWrapper.StartLookingForUsers(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
if(CalibrationText != null)
{
CalibrationText.guiText.text = "WAITING FOR USERS";
}
}
// remove from global users list
allUsers.Remove(UserId);
AllPlayersCalibrated = !TwoUsers ? allUsers.Count >= 1 : allUsers.Count >= 2; // false;
}
// Estimates the current state of the defined gestures
void CheckForGestures(uint UserId, ref List<KinectGestures.GestureData> playerGestures, ref float gestureTrackingAtTime)
{
// check for gestures
if(Time.realtimeSinceStartup >= gestureTrackingAtTime)
{
int listGestureSize = playerGestures.Count;
float timestampNow = Time.realtimeSinceStartup;
// get joint positions and tracking
int iAllJointsCount = (int)KinectWrapper.SkeletonJoint.COUNT;
bool[] playerJointsTracked = new bool[iAllJointsCount];
Vector3[] playerJointsPos = new Vector3[iAllJointsCount];
int[] aiNeededJointIndexes = KinectGestures.GetNeededJointIndexes();
int iNeededJointsCount = aiNeededJointIndexes.Length;
for(int i = 0; i < iNeededJointsCount; i++)
{
int joint = aiNeededJointIndexes[i];
if(joint >= 0 && KinectWrapper.GetJointPositionConfidence(UserId, joint) >= 0.5f)
{
if(KinectWrapper.GetJointPosition(UserId, joint, ref jointPosition))
{
playerJointsTracked[joint] = true;
playerJointsPos[joint] = new Vector3(jointPosition.x * 0.001f, jointPosition.y * 0.001f + SensorHeight, jointPosition.z * 0.001f);
}
}
}
// check for gestures
for(int g = 0; g < listGestureSize; g++)
{
KinectGestures.GestureData gestureData = playerGestures[g];
if((timestampNow >= gestureData.startTrackingAtTime) &&
!IsConflictingGestureInProgress(gestureData))
{
KinectGestures.CheckForGesture(UserId, ref gestureData, Time.realtimeSinceStartup,
ref playerJointsPos, ref playerJointsTracked);
player1Gestures[g] = gestureData;
if(gestureData.complete)
{
gestureTrackingAtTime = timestampNow + MinTimeBetweenGestures;
}
}
}
}
}
bool IsConflictingGestureInProgress(KinectGestures.GestureData gestureData)
{
foreach(KinectGestures.Gestures gesture in gestureData.checkForGestures)
{
int index = GetGestureIndex(gestureData.userId, gesture);
if(index >= 0)
{
if(gestureData.userId == Player1ID)
{
if(player1Gestures[index].progress > 0f)
return true;
}
else if(gestureData.userId == Player2ID)
{
if(player2Gestures[index].progress > 0f)
return true;
}
}
}
return false;
}
// return the index of gesture in the list, or -1 if not found
private int GetGestureIndex(uint UserId, KinectGestures.Gestures gesture)
{
if(UserId == Player1ID)
{
int listSize = player1Gestures.Count;
for(int i = 0; i < listSize; i++)
{
if(player1Gestures[i].gesture == gesture)
return i;
}
}
else if(UserId == Player2ID)
{
int listSize = player2Gestures.Count;
for(int i = 0; i < listSize; i++)
{
if(player2Gestures[i].gesture == gesture)
return i;
}
}
return -1;
}
// // convert the matrix to quaternion, taking care of the mirroring
// private Quaternion ConvertMatrixToQuat(KinectWrapper.SkeletonJointOrientation ori, int joint, bool flip)
// {
// Matrix4x4 mat = Matrix4x4.identity;
//
// Quaternion quat = new Quaternion(ori.x, ori.y, ori.z, ori.w);
// mat.SetTRS(Vector3.zero, quat, Vector3.one);
//
// Vector3 vZ = mat.GetColumn(2);
// Vector3 vY = mat.GetColumn(1);
//
// if(!flip)
// {
// vZ.y = -vZ.y;
// vY.x = -vY.x;
// vY.z = -vY.z;
// }
// else
// {
// vZ.x = -vZ.x;
// vZ.y = -vZ.y;
// vY.z = -vY.z;
// }
//
// if(vZ.x != 0.0f || vZ.y != 0.0f || vZ.z != 0.0f)
// {
// return Quaternion.LookRotation(vZ, vY);
// }
//
// return Quaternion.identity;
// }
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using OLEDB.Test.ModuleCore;
namespace System.Xml.Tests
{
internal class VerifyNameTests3 : CTestCase
{
public override void AddChildren()
{
AddChild(new CVariation(v16) { Attribute = new Variation("15.Test for VerifyNCName(\ud801\r\udc01)") { Params = new object[] { 15, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("6.Test for VerifyNCName(abcd\ralfafkjha)") { Params = new object[] { 6, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("8.Test for VerifyNCName(abcd\tdef)") { Params = new object[] { 8, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("9.Test for VerifyNCName( \b)") { Params = new object[] { 9, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("10.Test for VerifyNCName(\ud801\udc01)") { Params = new object[] { 10, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("11.Test for VerifyNCName( \ud801\udc01)") { Params = new object[] { 11, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("12.Test for VerifyNCName(\ud801\udc01 )") { Params = new object[] { 12, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("13.Test for VerifyNCName(\ud801 \udc01)") { Params = new object[] { 13, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("14.Test for VerifyNCName(\ud801 \udc01)") { Params = new object[] { 14, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("1.Test for VerifyNCName(abcd)") { Params = new object[] { 1, "valid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("16.Test for VerifyNCName(\ud801\n\udc01)") { Params = new object[] { 16, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("17.Test for VerifyNCName(\ud801\t\udc001)") { Params = new object[] { 17, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("18.Test for VerifyNCName(a\ud801\udc01b)") { Params = new object[] { 18, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("19.Test for VerifyNCName(a\udc01\ud801b)") { Params = new object[] { 19, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("20.Test for VerifyNCName(a\ud801b)") { Params = new object[] { 20, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("21.Test for VerifyNCName(a\udc01b)") { Params = new object[] { 21, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("22.Test for VerifyNCName(\ud801\udc01:)") { Params = new object[] { 22, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("23.Test for VerifyNCName(:a\ud801\udc01b)") { Params = new object[] { 23, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("24.Test for VerifyNCName(a\ud801\udc01:b)") { Params = new object[] { 24, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("25.Test for VerifyNCName(a\udbff\udc01\b)") { Params = new object[] { 25, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("7.Test for VerifyNCName(abcd def)") { Params = new object[] { 7, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("2.Test for VerifyNCName(abcd efgh)") { Params = new object[] { 2, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("3.Test for VerifyNCName( abcd)") { Params = new object[] { 3, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("4.Test for VerifyNCName(abcd\nalfafkjha)") { Params = new object[] { 4, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("5.Test for VerifyNCName(abcd\nalfafkjha)") { Params = new object[] { 5, "invalid" } } });
AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyNCName(null)") { Param = 3 } });
AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyXmlChars(null)") { Param = 5 } });
AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyPublicId(null)") { Param = 6 } });
AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyWhitespace(null)") { Param = 7 } });
AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyName(null)") { Param = 2 } });
AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyNMTOKEN(null)") { Param = 1 } });
AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyPublicId(String.Empty)") { Params = new object[] { 6, null } } });
AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyWhitespace(String.Empty)") { Params = new object[] { 7, null } } });
AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyName(String.Empty)") { Params = new object[] { 2, typeof(ArgumentNullException) } } });
AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyNCName(String.Empty)") { Params = new object[] { 3, typeof(ArgumentNullException) } } });
AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyXmlChars(String.Empty)") { Params = new object[] { 5, null } } });
AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyNMTOKEN(String.Empty)") { Params = new object[] { 1, typeof(XmlException) } } });
}
private int v16()
{
var param = (int)CurVariation.Params[0];
string input = string.Empty;
switch (param)
{
case 1:
input = "abcd";
break;
case 2:
input = "abcd efgh";
break;
case 3:
input = " abcd";
break;
case 4:
input = "abcd ";
break;
case 5:
input = "abcd\nalfafkjha";
break;
case 6:
input = "abcd\ralfafkjha";
break;
case 7:
input = "abcd def";
break;
case 8:
input = "abcd\tdef";
break;
case 9:
input = " \b";
break;
case 10:
input = "\ud801\udc01";
break;
case 11:
input = " \ud801\udc01";
break;
case 12:
input = "\ud801\udc01 ";
break;
case 13:
input = "\ud801 \udc01";
break;
case 14:
input = "\ud801 \udc01";
break;
case 15:
input = "\ud801\r\udc01";
break;
case 16:
input = "\ud801\n\udc01";
break;
case 17:
input = "\ud801\t\udc01";
break;
case 18:
input = "a\ud801\udc01b";
break;
case 19:
input = "a\udc01\ud801b";
break;
case 20:
input = "a\ud801b";
break;
case 21:
input = "a\udc01b";
break;
case 22:
input = "\ud801\udc01:";
break;
case 23:
input = ":a\ud801\udc01b";
break;
case 24:
input = "a\ud801\udc01b:";
break;
case 25:
input = "a\udbff\udc01\b";
break;
}
string expected = CurVariation.Params[1].ToString();
try
{
XmlConvert.VerifyNCName(input);
}
catch (XmlException e)
{
CError.WriteLine(e.LineNumber);
CError.WriteLine(e.LinePosition);
return (expected.Equals("invalid")) ? TEST_PASS : TEST_FAIL;
}
return (expected.Equals("valid")) ? TEST_PASS : TEST_FAIL;
}
private int v17()
{
var param = (int)CurVariation.Param;
try
{
switch (param)
{
case 1:
XmlConvert.VerifyNMTOKEN(null);
break;
case 2:
XmlConvert.VerifyName(null);
break;
case 3:
XmlConvert.VerifyNCName(null);
break;
case 5:
XmlConvert.VerifyXmlChars(null);
break;
case 6:
XmlConvert.VerifyPublicId(null);
break;
case 7:
XmlConvert.VerifyWhitespace(null);
break;
}
}
catch (ArgumentNullException)
{
return param != 4 ? TEST_PASS : TEST_FAIL; //param4 -> VerifyToken should not throw here
}
return TEST_FAIL;
}
/// <summary>
/// Params[] = { VariationNumber, Exception type (null if exception not expected) }
/// </summary>
/// <returns></returns>
private int v18()
{
var param = (int)CurVariation.Params[0];
var exceptionType = (Type)CurVariation.Params[1];
try
{
switch (param)
{
case 1:
XmlConvert.VerifyNMTOKEN(string.Empty);
break;
case 2:
XmlConvert.VerifyName(string.Empty);
break;
case 3:
XmlConvert.VerifyNCName(string.Empty);
break;
case 5:
XmlConvert.VerifyXmlChars(string.Empty);
break;
case 6:
XmlConvert.VerifyPublicId(string.Empty);
break;
case 7:
XmlConvert.VerifyWhitespace(string.Empty);
break;
}
}
catch (ArgumentException e)
{
return (exceptionType != null && e.GetType().Name == exceptionType.Name) ? TEST_PASS : TEST_FAIL;
}
catch (XmlException e)
{
CError.WriteLine(e.LineNumber);
CError.WriteLine(e.LinePosition);
return (exceptionType != null && e.GetType().Name == exceptionType.Name) ? TEST_PASS : TEST_FAIL;
}
return exceptionType == null ? TEST_PASS : TEST_FAIL;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using 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 GeneratedRoutersClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<Routers.RoutersClient> mockGrpcClient = new moq::Mock<Routers.RoutersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRouterRequest request = new GetRouterRequest
{
Region = "regionedb20d96",
Router = "routerd55c39f3",
Project = "projectaa6ff846",
};
Router expectedResponse = new Router
{
Id = 11672635353343658936UL,
Bgp = new RouterBgp(),
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Nats = { new RouterNat(), },
Interfaces =
{
new RouterInterface(),
},
CreationTimestamp = "creation_timestamp235e59a1",
Region = "regionedb20d96",
Network = "networkd22ce091",
EncryptedInterconnectRouter = false,
Description = "description2cf9da67",
BgpPeers =
{
new RouterBgpPeer(),
},
SelfLink = "self_link7e87f12d",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RoutersClient client = new RoutersClientImpl(mockGrpcClient.Object, null);
Router response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<Routers.RoutersClient> mockGrpcClient = new moq::Mock<Routers.RoutersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRouterRequest request = new GetRouterRequest
{
Region = "regionedb20d96",
Router = "routerd55c39f3",
Project = "projectaa6ff846",
};
Router expectedResponse = new Router
{
Id = 11672635353343658936UL,
Bgp = new RouterBgp(),
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Nats = { new RouterNat(), },
Interfaces =
{
new RouterInterface(),
},
CreationTimestamp = "creation_timestamp235e59a1",
Region = "regionedb20d96",
Network = "networkd22ce091",
EncryptedInterconnectRouter = false,
Description = "description2cf9da67",
BgpPeers =
{
new RouterBgpPeer(),
},
SelfLink = "self_link7e87f12d",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Router>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RoutersClient client = new RoutersClientImpl(mockGrpcClient.Object, null);
Router responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Router responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<Routers.RoutersClient> mockGrpcClient = new moq::Mock<Routers.RoutersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRouterRequest request = new GetRouterRequest
{
Region = "regionedb20d96",
Router = "routerd55c39f3",
Project = "projectaa6ff846",
};
Router expectedResponse = new Router
{
Id = 11672635353343658936UL,
Bgp = new RouterBgp(),
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Nats = { new RouterNat(), },
Interfaces =
{
new RouterInterface(),
},
CreationTimestamp = "creation_timestamp235e59a1",
Region = "regionedb20d96",
Network = "networkd22ce091",
EncryptedInterconnectRouter = false,
Description = "description2cf9da67",
BgpPeers =
{
new RouterBgpPeer(),
},
SelfLink = "self_link7e87f12d",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RoutersClient client = new RoutersClientImpl(mockGrpcClient.Object, null);
Router response = client.Get(request.Project, request.Region, request.Router);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<Routers.RoutersClient> mockGrpcClient = new moq::Mock<Routers.RoutersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRouterRequest request = new GetRouterRequest
{
Region = "regionedb20d96",
Router = "routerd55c39f3",
Project = "projectaa6ff846",
};
Router expectedResponse = new Router
{
Id = 11672635353343658936UL,
Bgp = new RouterBgp(),
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Nats = { new RouterNat(), },
Interfaces =
{
new RouterInterface(),
},
CreationTimestamp = "creation_timestamp235e59a1",
Region = "regionedb20d96",
Network = "networkd22ce091",
EncryptedInterconnectRouter = false,
Description = "description2cf9da67",
BgpPeers =
{
new RouterBgpPeer(),
},
SelfLink = "self_link7e87f12d",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Router>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RoutersClient client = new RoutersClientImpl(mockGrpcClient.Object, null);
Router responseCallSettings = await client.GetAsync(request.Project, request.Region, request.Router, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Router responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.Router, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRouterStatusRequestObject()
{
moq::Mock<Routers.RoutersClient> mockGrpcClient = new moq::Mock<Routers.RoutersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRouterStatusRouterRequest request = new GetRouterStatusRouterRequest
{
Region = "regionedb20d96",
Router = "routerd55c39f3",
Project = "projectaa6ff846",
};
RouterStatusResponse expectedResponse = new RouterStatusResponse
{
Kind = "kindf7aa39d9",
Result = new RouterStatus(),
};
mockGrpcClient.Setup(x => x.GetRouterStatus(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RoutersClient client = new RoutersClientImpl(mockGrpcClient.Object, null);
RouterStatusResponse response = client.GetRouterStatus(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRouterStatusRequestObjectAsync()
{
moq::Mock<Routers.RoutersClient> mockGrpcClient = new moq::Mock<Routers.RoutersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRouterStatusRouterRequest request = new GetRouterStatusRouterRequest
{
Region = "regionedb20d96",
Router = "routerd55c39f3",
Project = "projectaa6ff846",
};
RouterStatusResponse expectedResponse = new RouterStatusResponse
{
Kind = "kindf7aa39d9",
Result = new RouterStatus(),
};
mockGrpcClient.Setup(x => x.GetRouterStatusAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RouterStatusResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RoutersClient client = new RoutersClientImpl(mockGrpcClient.Object, null);
RouterStatusResponse responseCallSettings = await client.GetRouterStatusAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
RouterStatusResponse responseCancellationToken = await client.GetRouterStatusAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRouterStatus()
{
moq::Mock<Routers.RoutersClient> mockGrpcClient = new moq::Mock<Routers.RoutersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRouterStatusRouterRequest request = new GetRouterStatusRouterRequest
{
Region = "regionedb20d96",
Router = "routerd55c39f3",
Project = "projectaa6ff846",
};
RouterStatusResponse expectedResponse = new RouterStatusResponse
{
Kind = "kindf7aa39d9",
Result = new RouterStatus(),
};
mockGrpcClient.Setup(x => x.GetRouterStatus(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RoutersClient client = new RoutersClientImpl(mockGrpcClient.Object, null);
RouterStatusResponse response = client.GetRouterStatus(request.Project, request.Region, request.Router);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRouterStatusAsync()
{
moq::Mock<Routers.RoutersClient> mockGrpcClient = new moq::Mock<Routers.RoutersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRouterStatusRouterRequest request = new GetRouterStatusRouterRequest
{
Region = "regionedb20d96",
Router = "routerd55c39f3",
Project = "projectaa6ff846",
};
RouterStatusResponse expectedResponse = new RouterStatusResponse
{
Kind = "kindf7aa39d9",
Result = new RouterStatus(),
};
mockGrpcClient.Setup(x => x.GetRouterStatusAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RouterStatusResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RoutersClient client = new RoutersClientImpl(mockGrpcClient.Object, null);
RouterStatusResponse responseCallSettings = await client.GetRouterStatusAsync(request.Project, request.Region, request.Router, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
RouterStatusResponse responseCancellationToken = await client.GetRouterStatusAsync(request.Project, request.Region, request.Router, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void PreviewRequestObject()
{
moq::Mock<Routers.RoutersClient> mockGrpcClient = new moq::Mock<Routers.RoutersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PreviewRouterRequest request = new PreviewRouterRequest
{
Region = "regionedb20d96",
Router = "routerd55c39f3",
RouterResource = new Router(),
Project = "projectaa6ff846",
};
RoutersPreviewResponse expectedResponse = new RoutersPreviewResponse
{
Resource = new Router(),
};
mockGrpcClient.Setup(x => x.Preview(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RoutersClient client = new RoutersClientImpl(mockGrpcClient.Object, null);
RoutersPreviewResponse response = client.Preview(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task PreviewRequestObjectAsync()
{
moq::Mock<Routers.RoutersClient> mockGrpcClient = new moq::Mock<Routers.RoutersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PreviewRouterRequest request = new PreviewRouterRequest
{
Region = "regionedb20d96",
Router = "routerd55c39f3",
RouterResource = new Router(),
Project = "projectaa6ff846",
};
RoutersPreviewResponse expectedResponse = new RoutersPreviewResponse
{
Resource = new Router(),
};
mockGrpcClient.Setup(x => x.PreviewAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RoutersPreviewResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RoutersClient client = new RoutersClientImpl(mockGrpcClient.Object, null);
RoutersPreviewResponse responseCallSettings = await client.PreviewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
RoutersPreviewResponse responseCancellationToken = await client.PreviewAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Preview()
{
moq::Mock<Routers.RoutersClient> mockGrpcClient = new moq::Mock<Routers.RoutersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PreviewRouterRequest request = new PreviewRouterRequest
{
Region = "regionedb20d96",
Router = "routerd55c39f3",
RouterResource = new Router(),
Project = "projectaa6ff846",
};
RoutersPreviewResponse expectedResponse = new RoutersPreviewResponse
{
Resource = new Router(),
};
mockGrpcClient.Setup(x => x.Preview(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RoutersClient client = new RoutersClientImpl(mockGrpcClient.Object, null);
RoutersPreviewResponse response = client.Preview(request.Project, request.Region, request.Router, request.RouterResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task PreviewAsync()
{
moq::Mock<Routers.RoutersClient> mockGrpcClient = new moq::Mock<Routers.RoutersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PreviewRouterRequest request = new PreviewRouterRequest
{
Region = "regionedb20d96",
Router = "routerd55c39f3",
RouterResource = new Router(),
Project = "projectaa6ff846",
};
RoutersPreviewResponse expectedResponse = new RoutersPreviewResponse
{
Resource = new Router(),
};
mockGrpcClient.Setup(x => x.PreviewAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RoutersPreviewResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RoutersClient client = new RoutersClientImpl(mockGrpcClient.Object, null);
RoutersPreviewResponse responseCallSettings = await client.PreviewAsync(request.Project, request.Region, request.Router, request.RouterResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
RoutersPreviewResponse responseCancellationToken = await client.PreviewAsync(request.Project, request.Region, request.Router, request.RouterResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Runtime.Serialization;
using Signum.Utilities;
using Signum.Entities.Reflection;
using Signum.Utilities.ExpressionTrees;
using Signum.Entities.Basics;
using NpgsqlTypes;
namespace Signum.Entities
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class UniqueIndexAttribute : Attribute
{
public bool AllowMultipleNulls { get; set; }
public bool AvoidAttachToUniqueIndexes { get; set; }
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class AttachToUniqueIndexesAttribute : Attribute
{
}
[Serializable]
public struct Implementations : IEquatable<Implementations>, ISerializable
{
object? arrayOrType;
public bool IsByAll { get { return arrayOrType == null; } }
public IEnumerable<Type> Types
{
get
{
if (arrayOrType == null)
throw new InvalidOperationException("ImplementedByAll");
return Enumerate();
}
}
private IEnumerable<Type> Enumerate()
{
if (arrayOrType is Type t)
{
yield return t;
}
else if (arrayOrType is Type[] ts)
{
foreach (var item in ts)
yield return item;
}
else
throw new InvalidOperationException("IsByAll");
}
public static Implementations? TryFromAttributes(Type t, PropertyRoute route, ImplementedByAttribute? ib, ImplementedByAllAttribute? iba)
{
if (ib != null && iba != null)
throw new NotSupportedException("Route {0} contains both {1} and {2}".FormatWith(route, ib.GetType().Name, iba.GetType().Name));
if (ib != null) return Implementations.By(ib.ImplementedTypes);
if (iba != null) return Implementations.ByAll;
if (Error(t) == null)
return Implementations.By(t);
return null;
}
public static Implementations FromAttributes(Type t, PropertyRoute route, ImplementedByAttribute? ib, ImplementedByAllAttribute? iba)
{
Implementations? imp = TryFromAttributes(t, route, ib, iba);
if (imp == null)
{
var message = Error(t) + @". Set implementations for {0}.".FormatWith(route);
if (t.IsInterface || t.IsAbstract)
{
message += @"\r\n" + ConsiderMessage(route, "typeof(YourConcrete" + t.TypeName() + ")");
}
throw new InvalidOperationException(message);
}
return imp.Value;
}
internal static string ConsiderMessage(PropertyRoute route, string targetTypes)
{
return $@"Consider writing something like this in your Starter class:
sb.Schema.Settings.FieldAttributes(({route.RootType.TypeName()} a) => a.{route.PropertyString().Replace("/", ".First().")}).Replace(new ImplementedByAttribute({targetTypes}))";
}
public static Implementations ByAll { get { return new Implementations(); } }
public static Implementations By(Type type)
{
var error = Error(type);
if (error.HasText())
throw new InvalidOperationException(error);
return new Implementations { arrayOrType = type };
}
public static Implementations By(params Type[] types)
{
if (types == null || types.Length == 0)
return new Implementations { arrayOrType = types ?? new Type[0] };
if (types.Length == 1)
return By(types[0]);
var error = types.Select(Error).NotNull().ToString("\r\n");
if (error.HasText())
throw new InvalidOperationException(error);
return new Implementations { arrayOrType = types.OrderBy(a => a.FullName).ToArray() };
}
static string? Error(Type type)
{
if (type.IsInterface)
return "{0} is an interface".FormatWith(type.Name);
if (type.IsAbstract)
return "{0} is abstract".FormatWith(type.Name);
if (!type.IsEntity())
return "{0} is not {1}".FormatWith(type.Name, typeof(Entity).Name);
return null;
}
public string Key()
{
if (IsByAll)
return "[ALL]";
return Types.ToString(TypeEntity.GetCleanName, ", ");
}
public override string ToString()
{
if (IsByAll)
return "ImplementedByAll";
return "ImplementedBy({0})".FormatWith(Types.ToString(t => t.Name, ", "));
}
public override bool Equals(object? obj)
{
return obj is Implementations imp && Equals(imp);
}
public bool Equals(Implementations other)
{
return IsByAll && other.IsByAll ||
arrayOrType == other.arrayOrType ||
Enumerable.SequenceEqual(Types, other.Types);
}
public override int GetHashCode()
{
return arrayOrType == null ? 0 : Types.Aggregate(0, (acum, type) => acum ^ type.GetHashCode());
}
Implementations(SerializationInfo info, StreamingContext context)
{
string str = info.GetString("arrayOrType")!;
arrayOrType = str == "ALL" ? null :
str.Split('|').Select(Type.GetType).ToArray();
if (arrayOrType is Type[] array && array.Length == 1)
arrayOrType = array[0];
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("arrayOrType", arrayOrType == null ? "ALL" :
arrayOrType is Type t ? t.AssemblyQualifiedName :
arrayOrType is Type[] ts ? ts.ToString(a => a.AssemblyQualifiedName, "|") : null);
}
public static bool operator ==(Implementations left, Implementations right)
{
return left.Equals(right);
}
public static bool operator !=(Implementations left, Implementations right)
{
return !(left == right);
}
}
[Serializable, AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ImplementedByAttribute : Attribute
{
Type[] implementedTypes;
public Type[] ImplementedTypes
{
get { return implementedTypes; }
}
public ImplementedByAttribute(params Type[] types)
{
implementedTypes = types;
}
}
[Serializable, AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ImplementedByAllAttribute : Attribute
{
public ImplementedByAllAttribute()
{
}
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class IgnoreAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class FieldWithoutPropertyAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ForceNotNullableAttribute : Attribute
{
}
/// <summary>
/// Very rare. Reference types (classes) or Nullable are already nullable in the database.
/// This attribute is only necessary in the case an entity field is not-nullable but you can not make the DB column nullable because of legacy data, or cycles in a graph of entities.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ForceNullableAttribute: Attribute
{
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class DbTypeAttribute : Attribute
{
SqlDbType? sqlDbType;
public bool HasSqlDbType => sqlDbType.HasValue;
public SqlDbType SqlDbType
{
get { return sqlDbType!.Value; }
set { sqlDbType = value; }
}
NpgsqlDbType? npgsqlDbType;
public bool HasNpgsqlDbType => npgsqlDbType.HasValue;
public NpgsqlDbType NpgsqlDbType
{
get { return npgsqlDbType!.Value; }
set { npgsqlDbType = value; }
}
int? size;
public bool HasSize => size.HasValue;
public int Size
{
get { return size!.Value; }
set { size = value; }
}
int? scale;
public bool HasScale => scale.HasValue;
public int Scale
{
get { return scale!.Value; }
set { scale = value; }
}
public string? UserDefinedTypeName { get; set; }
public string? Default { get; set; }
public string? DefaultSqlServer { get; set; }
public string? DefaultPostgres { get; set; }
public string? GetDefault(bool isPostgres)
{
return (isPostgres ? DefaultPostgres : DefaultSqlServer) ?? Default;
}
public string? Collation { get; set; }
public const string SqlServer_NewId = "NEWID()";
public const string SqlServer_NewSequentialId = "NEWSEQUENTIALID()";
public const string Postgres_UuidGenerateV1= "uuid_generate_v1()";
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property /*MList fields*/, Inherited = true, AllowMultiple = false)]
public sealed class PrimaryKeyAttribute : DbTypeAttribute
{
public Type Type { get; set; }
public string Name { get; set; }
public bool Identity { get; set; }
bool identityBehaviour;
public bool IdentityBehaviour
{
get { return identityBehaviour; }
set
{
identityBehaviour = value;
if (Type == typeof(Guid) && identityBehaviour)
{
this.DefaultSqlServer = SqlServer_NewId;
this.DefaultPostgres = Postgres_UuidGenerateV1;
}
}
}
public PrimaryKeyAttribute(Type type, string name = "ID")
{
this.Type = type;
this.Name = name;
this.Identity = type == typeof(Guid) ? false : true;
this.IdentityBehaviour = true;
}
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class ColumnNameAttribute : Attribute
{
public string Name { get; set; }
public ColumnNameAttribute(string name)
{
this.Name = name;
}
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class BackReferenceColumnNameAttribute : Attribute
{
public string Name { get; set; }
public BackReferenceColumnNameAttribute(string name)
{
this.Name = name;
}
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ViewPrimaryKeyAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property /*MList fields*/, Inherited = true, AllowMultiple = false)]
public sealed class TableNameAttribute : Attribute
{
public string Name { get; set; }
public string? SchemaName { get; set; }
public string? DatabaseName { get; set; }
public string? ServerName { get; set; }
public TableNameAttribute(string fullName)
{
var parts = fullName.Split('.');
this.Name = parts.ElementAtOrDefault(parts.Length - 1).Trim('[', ']');
this.SchemaName = parts.ElementAtOrDefault(parts.Length - 2)?.Trim('[', ']');
this.DatabaseName = parts.ElementAtOrDefault(parts.Length - 3)?.Trim('[', ']');
this.ServerName = parts.ElementAtOrDefault(parts.Length - 4)?.Trim('[', ']');
}
}
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public sealed class TicksColumnAttribute : DbTypeAttribute
{
public bool HasTicks { get; private set; }
public string? Name { get; set; }
public Type? Type { get; set; }
public TicksColumnAttribute(bool hasTicks = true)
{
this.HasTicks = hasTicks;
}
}
/// <summary>
/// Activates SQL Server 2016 Temporal Tables
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property /*MList fields*/, Inherited = true, AllowMultiple = false)]
public sealed class SystemVersionedAttribute : Attribute
{
public string? TemporalTableName { get; set; }
public string StartDateColumnName { get; set; } = "SysStartDate";
public string EndDateColumnName { get; set; } = "SysEndDate";
public string PostgreeSysPeriodColumname { get; set; } = "sys_period";
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class AvoidForeignKeyAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class AvoidExpandQueryAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class CombineStrategyAttribute : Attribute
{
public readonly CombineStrategy Strategy;
public CombineStrategyAttribute(CombineStrategy strategy)
{
this.Strategy = strategy;
}
}
public enum CombineStrategy
{
Union,
Case,
}
public static class LinqHintEntities
{
public static T CombineCase<T>(this T value) where T : IEntity
{
return value;
}
public static T CombineUnion<T>(this T value) where T : IEntity
{
return value;
}
}
}
| |
// Copyright(c) DEVSENSE s.r.o.
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Devsense.PHP.Syntax.Ast
{
#region WhileStmt
/// <summary>
/// Represents a while-loop statement.
/// </summary>
public sealed class WhileStmt : Statement
{
/// <summary>
/// Loop type.
/// </summary>
public enum Type { While, Do };
/// <summary>Type of statement</summary>
public Type LoopType { get { return type; } }
private Type type;
/// <summary>
/// Condition or a <B>null</B> reference for unbounded loop.
/// </summary>
public Expression CondExpr { get { return condExpr; } internal set { condExpr = value; } }
private Expression condExpr;
/// <summary>
/// Position of the header parentheses.
/// </summary>
public Text.Span ConditionPosition { get { return _conditionPosition; } }
private Text.Span _conditionPosition;
/// <summary>Body of loop</summary>
public Statement/*!*/ Body { get { return body; } internal set { body = value; } }
private Statement/*!*/ body;
/// <summary>
/// Create loop.
/// </summary>
/// <param name="span">Entire span.</param>
/// <param name="type">Loop type.</param>
/// <param name="condExpr">Loop condition.</param>
/// <param name="conditionSpan">Condition span.</param>
/// <param name="body">Loop body.</param>
public WhileStmt(Text.Span span, Type type, Expression/*!*/ condExpr, Text.Span conditionSpan, Statement/*!*/ body)
: base(span)
{
Debug.Assert(condExpr != null && body != null);
this.type = type;
this.condExpr = condExpr;
this.body = body;
this._conditionPosition = conditionSpan;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitWhileStmt(this);
}
}
#endregion
#region ForStmt
/// <summary>
/// Represents a for-loop statement.
/// </summary>
public sealed class ForStmt : Statement
{
private readonly Expression[]/*!*/ initExList;
private readonly Expression[]/*!*/ condExList;
private readonly Expression[]/*!*/ actionExList;
private Statement/*!*/ body;
/// <summary>List of expressions used for initialization</summary>
public IList<Expression> /*!*/ InitExList { get { return initExList; } }
/// <summary>List of expressions used as condition</summary>
public IList<Expression> /*!*/ CondExList { get { return condExList; } }
/// <summary>List of expressions used to incrent iterator</summary>
public IList<Expression> /*!*/ ActionExList { get { return actionExList; } }
/// <summary>Body of statement</summary>
public Statement/*!*/ Body { get { return body; } internal set { body = value; } }
/// <summary>
/// Position of the header parentheses.
/// </summary>
public Text.Span ConditionSpan { get { return _conditionSpan; } }
private Text.Span _conditionSpan;
public ForStmt(Text.Span p,
IList<Expression>/*!*/ initExList, IList<Expression>/*!*/ condExList, IList<Expression>/*!*/ actionExList,
Text.Span conditionSpan, Statement/*!*/ body)
: base(p)
{
Debug.Assert(initExList != null && condExList != null && actionExList != null && body != null);
this.initExList = initExList.AsArray();
this.condExList = condExList.AsArray();
this.actionExList = actionExList.AsArray();
this.body = body;
this._conditionSpan = conditionSpan;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitForStmt(this);
}
}
#endregion
#region ForeachStmt
/// <summary>
/// Represents a foreach-loop statement.
/// </summary>
public sealed class ForeachVar : AstNode
{
/// <summary>
/// Whether the variable is aliased.
/// </summary>
public bool Alias { get { return _alias; } set { _alias = value; } }
private bool _alias;
/// <summary>
/// The variable itself. Can be <c>null</c> reference if <see cref="ArrayEx"/> is represented instead.
/// </summary>
public VariableUse Variable { get { return _target as VariableUse; } }
/// <summary>
/// PHP list expression. Can be <c>null</c> reference if <see cref="VariableUse"/> is represented instead.
/// </summary>
public ArrayEx List { get { return _target as ArrayEx; } }
/// <summary>
/// Inner expression representing <see cref="Variable"/> or <see cref="List"/>.
/// </summary>
public VarLikeConstructUse/*!*/Target => _target;
private readonly VarLikeConstructUse/*!*/_target;
/// <summary>
/// Position of foreach variable.
/// </summary>
public Text.Span Span => _target.Span;
public ForeachVar(VariableUse variable, bool alias)
{
_target = variable;
_alias = alias;
}
/// <summary>
/// Initializes instance of <see cref="ForeachVar"/> representing PHP list expression.
/// </summary>
/// <param name="list"></param>
public ForeachVar(IArrayExpression/*!*/list)
{
Debug.Assert(list != null);
Debug.Assert(list.Operation == Operations.List);
_target = (VarLikeConstructUse)list;
_alias = false;
}
}
/// <summary>
/// Represents a foreach statement.
/// </summary>
public class ForeachStmt : Statement
{
private Expression/*!*/ enumeree;
/// <summary>Array to enumerate through</summary>
public Expression /*!*/Enumeree { get { return enumeree; } }
private ForeachVar keyVariable;
/// <summary>Variable to store key in (can be null)</summary>
public ForeachVar KeyVariable { get { return keyVariable; } }
private ForeachVar/*!*/ valueVariable;
/// <summary>Variable to store value in</summary>
public ForeachVar /*!*/ ValueVariable { get { return valueVariable; } }
private Statement/*!*/ body;
/// <summary>Body - statement in loop</summary>
public Statement/*!*/ Body { get { return body; } internal set { body = value; } }
public ForeachStmt(Text.Span span, Expression/*!*/ enumeree, ForeachVar key, ForeachVar/*!*/ value, Statement/*!*/ body)
: base(span)
{
Debug.Assert(enumeree != null && value != null && body != null);
this.enumeree = enumeree;
this.keyVariable = key;
this.valueVariable = value;
this.body = body;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitForeachStmt(this);
}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
/// <summary>
/// System.Collections.Generic.List.RemoveRange(Int32,Int32)
/// </summary>
public class ListRemoveRange
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Remove all the elements in the int type list");
try
{
int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 10, 2, 4 };
List<int> listObject = new List<int>(iArray);
listObject.RemoveRange(0, 10);
if (listObject.Count != 0)
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,count is: " + listObject.Count);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is type of string");
try
{
string[] strArray = { "dog", "apple", "joke", "banana", "chocolate", "dog", "food" };
List<string> listObject = new List<string>(strArray);
listObject.RemoveRange(3, 3);
string[] expected = { "dog", "apple", "joke", "food" };
for (int i = 0; i < 4; i++)
{
if (listObject[i] != expected[i])
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,result is: " + listObject[i]);
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: The count argument is zero");
try
{
MyClass myclass1 = new MyClass();
MyClass myclass2 = new MyClass();
MyClass myclass3 = new MyClass();
MyClass[] mc = new MyClass[3] { myclass1, myclass2, myclass3 };
List<MyClass> listObject = new List<MyClass>(mc);
listObject.RemoveRange(1, 0);
for (int i = 0; i < 3; i++)
{
if (listObject[i] != mc[i])
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected,result is: " + listObject[i]);
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The index is a negative number");
try
{
int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 10, 2, 4 };
List<int> listObject = new List<int>(iArray);
listObject.RemoveRange(-1, 3);
TestLibrary.TestFramework.LogError("101", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: The count is a negative number");
try
{
int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 10, 2, 4 };
List<int> listObject = new List<int>(iArray);
listObject.RemoveRange(3, -2);
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: index and count do not denote a valid range of elements in the List");
try
{
string[] strArray = { "dog", "apple", "joke", "banana", "chocolate", "dog", "food" };
List<string> listObject = new List<string>(strArray);
listObject.RemoveRange(3, 10);
TestLibrary.TestFramework.LogError("105", "The ArgumentException was not thrown as expected");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ListRemoveRange test = new ListRemoveRange();
TestLibrary.TestFramework.BeginTestCase("ListRemoveRange");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
public class MyClass
{
}
| |
// Copyright (c) 2010, Eric Maupin
// 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 Gablarski nor the names of its
// contributors may be used to endorse or promote products
// or services derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
// AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gablarski.Messages;
using Gablarski.Server;
using NUnit.Framework;
using Tempest;
using Tempest.Tests;
namespace Gablarski.Tests
{
[TestFixture]
public class ServerUserManagerTests
{
private MockConnectionProvider provider;
private IServerUserManager manager;
private MockClientConnection client;
private MockServerConnection server;
private IUserInfo user;
[SetUp]
public void Setup()
{
user = new UserInfo ("Nickname", "Phonetic", "Username", 1, 2, true);
manager = new ServerUserManager();
provider = new MockConnectionProvider (GablarskiProtocol.Instance);
provider.Start (MessageTypes.All);
var cs = provider.GetConnections (GablarskiProtocol.Instance);
server = cs.Item2;
client = cs.Item1;
}
[TearDown]
public void TearDown()
{
user = null;
manager = null;
server = null;
server = null;
}
[Test]
public void LoginNull()
{
Assert.Throws<ArgumentNullException> (() => manager.Login (null, user));
Assert.Throws<ArgumentNullException> (() => manager.Login (server, null));
}
[Test]
public void Login()
{
manager.Connect (server);
Assert.IsFalse (manager.GetIsLoggedIn (server));
manager.Login (server, user);
Assert.IsTrue (manager.GetIsLoggedIn (server));
}
[Test]
public void LoginIgnoreBeforeConnect()
{
manager.Login (server, user);
Assert.IsFalse (manager.GetIsLoggedIn (server));
Assert.IsFalse (manager.GetIsLoggedIn (user));
}
[Test]
public void LoginAlreadyLoggedIn()
{
manager.Connect (server);
manager.Login (server, user);
Assert.IsTrue (manager.GetIsLoggedIn (server));
var c = provider.GetServerConnection();
manager.Connect (c);
manager.Login (c, user);
Assert.IsFalse (server.IsConnected);
Assert.IsFalse (manager.GetIsLoggedIn (server));
Assert.IsTrue (manager.GetIsLoggedIn (user));
Assert.IsTrue (manager.GetIsLoggedIn (c));
}
[Test]
public void GetIsLoggedInNull()
{
Assert.Throws<ArgumentNullException> (() => manager.GetIsLoggedIn ((IServerConnection)null));
Assert.Throws<ArgumentNullException> (() => manager.GetIsLoggedIn ((UserInfo)null));
}
[Test]
public void GetIsLoggedInConnection()
{
manager.Connect (server);
Assert.IsFalse (manager.GetIsLoggedIn (server));
manager.Login (server, user);
Assert.IsTrue (manager.GetIsLoggedIn (server));
}
[Test]
public void GetIsLoggedInConnectionNotFound()
{
Assert.IsFalse (manager.GetIsLoggedIn (server));
}
[Test]
public void GetIsLoggedInUser()
{
manager.Connect (server);
Assert.IsFalse (manager.GetIsLoggedIn (server));
manager.Login (server, user);
Assert.IsTrue (manager.GetIsLoggedIn (server));
}
[Test]
public void GetIsLoggedInUserNotFound()
{
Assert.IsFalse (manager.GetIsLoggedIn (server));
}
[Test]
public void JoinNull()
{
Assert.Throws<ArgumentNullException> (() => manager.Join (server, null));
Assert.Throws<ArgumentNullException> (() => manager.Join (null, user));
}
[Test]
public void JoinIgnoreNotConnected()
{
manager.Join (server, user);
Assert.IsFalse (manager.GetIsJoined (server));
Assert.IsFalse (manager.GetIsJoined (user));
}
[Test]
public void Join()
{
manager.Connect (server);
manager.Join (server, user);
Assert.IsTrue (manager.GetIsJoined (server));
Assert.IsTrue (manager.GetIsJoined (user));
IUserInfo joinedUser = manager.GetUser (server);
Assert.AreEqual (user.UserId, joinedUser.UserId);
Assert.AreEqual (user.Username, joinedUser.Username);
Assert.AreEqual (user.Nickname, joinedUser.Nickname);
Assert.AreEqual (user.Phonetic, joinedUser.Phonetic);
Assert.AreEqual (user.Status, joinedUser.Status);
Assert.AreEqual (user.IsMuted, joinedUser.IsMuted);
}
[Test]
public void JoinLoggedIn()
{
manager.Connect (server);
manager.Login (server, new UserInfo (user.Username, user.UserId, user.CurrentChannelId, false));
manager.Join (server, user);
Assert.IsTrue (manager.GetIsJoined (server));
Assert.IsTrue (manager.GetIsJoined (user));
IUserInfo joinedUser = manager.GetUser (server);
Assert.AreEqual (user.UserId, joinedUser.UserId);
Assert.AreEqual (user.Username, joinedUser.Username);
Assert.AreEqual (user.Nickname, joinedUser.Nickname);
Assert.AreEqual (user.Phonetic, joinedUser.Phonetic);
Assert.AreEqual (user.Status, joinedUser.Status);
Assert.AreEqual (user.IsMuted, joinedUser.IsMuted);
}
[Test]
public void JoinIgnoreDupe()
{
manager.Connect (server);
manager.Join (server, user);
manager.Join (server, user);
Assert.IsTrue (manager.GetIsJoined (server));
Assert.IsTrue (manager.GetIsJoined (user));
}
[Test]
public void GetIsJoinedNull()
{
Assert.Throws<ArgumentNullException> (() => manager.GetIsJoined ((IServerConnection)null));
Assert.Throws<ArgumentNullException> (() => manager.GetIsJoined ((UserInfo)null));
}
[Test]
public void GetIsJoinedConnection()
{
manager.Connect (server);
Assert.IsFalse (manager.GetIsJoined (server));
manager.Join (server, user);
Assert.IsTrue (manager.GetIsJoined (server));
}
[Test]
public void GetIsJoinedConnectionNotFound()
{
Assert.IsFalse (manager.GetIsJoined (server));
}
[Test]
public void GetIsJoinedUser()
{
manager.Connect (server);
Assert.IsFalse (manager.GetIsJoined (user));
manager.Join (server, user);
Assert.IsTrue (manager.GetIsJoined (user));
}
[Test]
public void GetIsJoinedUserNotFound()
{
Assert.IsFalse (manager.GetIsJoined (user));
}
[Test]
public void MoveNull()
{
Assert.Throws<ArgumentNullException> (() => manager.Move (null, new ChannelInfo (1)));
Assert.Throws<ArgumentNullException> (() => manager.Move (user, null));
}
[Test]
public void MoveNotConnected()
{
Assert.DoesNotThrow (() =>
manager.Move (user, new ChannelInfo (1)));
Assert.IsNull (manager.GetUser (server));
}
[Test]
public void MoveNotJoined()
{
manager.Connect (server);
Assert.DoesNotThrow (() =>
manager.Move (user, new ChannelInfo (1)));
Assert.IsNull (manager.GetUser (server));
}
[Test]
public void MoveSameChannel()
{
var c = new ChannelInfo (2);
manager.Connect (server);
manager.Join (server, user);
manager.Move (user, c);
user = manager.GetUser (server);
Assert.AreEqual (c.ChannelId, user.CurrentChannelId);
}
[Test]
public void MoveChannel()
{
var c = new ChannelInfo(3);
manager.Connect (server);
manager.Join (server, user);
manager.Move (user, c);
user = manager.GetUser (server);
Assert.AreEqual (c.ChannelId, user.CurrentChannelId);
}
[Test]
public void ToggleMuteNull()
{
Assert.Throws<ArgumentNullException> (() => manager.ToggleMute (null));
}
[Test]
public void ToggleMuteNotConnected()
{
Assert.DoesNotThrow (() =>
manager.ToggleMute (user));
Assert.IsNull (manager.GetConnection (user));
}
[Test]
public void ToggleMuteUnmuted()
{
user = new UserInfo (user, false);
Assert.IsFalse (user.IsMuted);
manager.Connect (server);
manager.Join (server, user);
user = manager.GetUser (server);
Assert.IsNotNull (user);
Assert.IsFalse (user.IsMuted);
Assert.IsTrue (manager.ToggleMute (user));
user = manager.GetUser (server);
Assert.IsNotNull (user);
Assert.IsTrue (user.IsMuted);
}
[Test]
public void ToggleMuteMuted()
{
user = new UserInfo (user, true);
Assert.IsTrue (user.IsMuted);
manager.Connect (server);
manager.Join (server, user);
user = manager.GetUser (server);
Assert.IsNotNull (user);
Assert.IsTrue (user.IsMuted);
Assert.IsFalse (manager.ToggleMute (user));
user = manager.GetUser (server);
Assert.IsNotNull (user);
Assert.IsFalse (user.IsMuted);
}
[Test]
public void SetStatusNull()
{
Assert.Throws<ArgumentNullException> (() => manager.SetStatus (null, UserStatus.Normal));
}
[Test]
public void SetStatus()
{
manager.Connect (server);
manager.Join (server, user);
Assert.AreEqual (UserStatus.Normal, user.Status);
user = manager.SetStatus (user, UserStatus.MutedSound);
Assert.IsNotNull (user);
Assert.AreEqual (UserStatus.MutedSound, user.Status);
}
[Test]
public void SetStatusNotConnected()
{
Assert.IsNull (manager.SetStatus (user, UserStatus.Normal));
}
[Test]
public void SetCommentNull()
{
Assert.Throws<ArgumentNullException> (() => manager.SetComment (null, "comment"));
Assert.DoesNotThrow (() => manager.SetComment (user, null));
}
[Test]
public void SetCommentNotConnected()
{
Assert.IsNull (manager.SetComment (user, "comment"));
}
[Test]
public void SetComment()
{
manager.Connect (server);
manager.Join (server, user);
Assert.AreEqual (null, user.Comment);
const string comment = "There are three monkeys in the barrel.";
var u = manager.SetComment (user, comment);
Assert.IsNotNull (u);
Assert.AreEqual (comment, u.Comment);
}
[Test]
public void ConnectNull()
{
Assert.Throws<ArgumentNullException> (() => manager.Connect (null));
}
[Test]
public void Connect()
{
Assert.IsFalse (manager.GetIsConnected (server));
manager.Connect (server);
Assert.IsTrue (manager.GetIsConnected (server));
}
[Test]
public void GetIsConnectedNull()
{
Assert.Throws<ArgumentNullException> (() => manager.GetIsConnected (null));
}
[Test]
public void GetIsConnected()
{
Assert.IsFalse (manager.GetIsConnected (server));
manager.Connect (server);
Assert.IsTrue (manager.GetIsConnected (server));
Assert.IsFalse (manager.GetIsConnected (provider.GetServerConnection()));
manager.Disconnect (server);
Assert.IsFalse (manager.GetIsConnected (server));
}
[Test]
public void DisconnectNull()
{
Assert.Throws<ArgumentNullException> (() => new ServerUserManager().Disconnect ((IConnection)null));
Assert.Throws<ArgumentNullException> (() => new ServerUserManager().Disconnect ((Func<IConnection, bool>)null));
}
[Test]
public void Disconnect()
{
manager.Connect (server);
Assert.IsTrue (manager.GetIsConnected (server));
manager.Disconnect (server);
Assert.IsFalse (manager.GetIsConnected (server));
Assert.IsFalse (manager.GetIsLoggedIn (server));
}
[Test]
public void DisconnectJoinedUser()
{
manager.Connect (server);
manager.Join (server, user);
manager.Disconnect (server);
Assert.IsNull (manager.GetConnection (user));
Assert.IsNull (manager.GetUser (server));
Assert.IsFalse (manager.GetIsJoined (server));
Assert.IsFalse (manager.GetIsJoined (user));
Assert.IsFalse (manager.GetIsConnected (server));
}
[Test]
public void DisconnectLoggedInUser()
{
manager.Connect (server);
manager.Login (server, user);
manager.Disconnect (server);
Assert.IsNull (manager.GetConnection (user));
Assert.IsNull (manager.GetUser (server));
Assert.IsFalse (manager.GetIsJoined (user));
Assert.IsFalse (manager.GetIsLoggedIn (user));
Assert.IsFalse (manager.GetIsConnected (server));
}
[Test]
public void DisconnectPredicate()
{
manager.Connect (server);
manager.Join (server, user);
manager.Disconnect (c => c == server);
Assert.IsNull (manager.GetConnection (user));
Assert.IsNull (manager.GetUser (server));
Assert.IsFalse (manager.GetIsJoined (user));
Assert.IsFalse (manager.GetIsConnected (server));
}
[Test]
public void GetUserNull()
{
Assert.Throws<ArgumentNullException> (() => manager.GetUser (null));
}
[Test]
public void GetUser()
{
manager.Connect (server);
manager.Join (server, user);
Assert.AreEqual (user, manager.GetUser (server));
}
[Test]
public void GetUserNotFound()
{
Assert.IsNull (manager.GetUser (server));
}
[Test]
public void GetConnectionNull()
{
Assert.Throws<ArgumentNullException> (() => manager.GetConnection (null));
}
[Test]
public void GetConnection()
{
manager.Connect (server);
manager.Join (server, user);
Assert.AreEqual (server, manager.GetConnection (user));
}
[Test]
public void GetConnectionNotFound()
{
Assert.IsNull (manager.GetConnection (new UserInfo ("Username", 1, 2, true)));
}
[Test]
public void GetIsNicknameInUseNull ()
{
Assert.Throws<ArgumentNullException> (() => manager.GetIsNicknameInUse (null));
}
[Test]
public void GetIsNicknameInUse()
{
manager.Connect (server);
Assert.IsFalse (manager.GetIsNicknameInUse (user.Nickname));
manager.Join (server, user);
Assert.IsTrue (manager.GetIsNicknameInUse (user.Nickname));
Assert.IsTrue (manager.GetIsNicknameInUse (user.Nickname + " "));
Assert.IsTrue (manager.GetIsNicknameInUse (user.Nickname.ToUpper()));
Assert.IsFalse (manager.GetIsNicknameInUse ("asdf"));
}
[Test]
public void GetIsNicknameInUseNoNickname()
{
user = new UserInfo ("Username", 1, 2, true);
manager.Connect (server);
manager.Login (server, user);
Assert.IsFalse (manager.GetIsNicknameInUse (user.Username));
}
}
}
| |
using System.Device.I2c;
namespace SensorClock.Workers
{
public class ClockWorker : BackgroundService
{
private const byte ADDR_ALLCALL = 0x70;
private const byte ADDR_HOUR = 0x71;
private const byte ADDR_MINUTE = 0x01;
private const byte ADDR_SECOND = 0x02;
private const byte AUTO_INCREMENT = 0x80;
private const int DIMM_HOUR_BEGIN = 22;
private const int DIMM_HOUR_END = 8;
private const byte MODE1_ALLCALL = 0x01;
private const byte MODE1_SLEEP = 0x10;
private const byte MODE1_SUBADDR1 = 0x08;
private const byte PWM_DEFAULT = 0x44;
private const byte PWM_DIMM = 0x01;
private const byte REGISTER_GRPPWM = 0x12;
private const byte REGISTER_LEDOUT0 = 0x14;
private const byte REGISTER_MODE1 = 0x00;
private const byte REGISTER_PWM0 = 0x02;
private readonly I2cDevice _allcall;
private readonly I2cDevice _hour;
private readonly I2cDevice _minute;
private readonly I2cDevice _second;
private readonly byte[] _secondDisplayed = new byte[17];
#region Mask
private static readonly byte[][] DIGITS = {
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00 },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
new byte[]{ REGISTER_PWM0 | AUTO_INCREMENT, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 }
};
#endregion Mask
private readonly ILogger<ClockWorker> _logger;
public ClockWorker(ILogger<ClockWorker> logger)
{
_logger = logger;
_allcall = I2cDevice.Create(new I2cConnectionSettings(1, ADDR_ALLCALL));
_hour = I2cDevice.Create(new I2cConnectionSettings(1, ADDR_HOUR));
_minute = I2cDevice.Create(new I2cConnectionSettings(1, ADDR_MINUTE));
_second = I2cDevice.Create(new I2cConnectionSettings(1, ADDR_SECOND));
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await Init();
while (!stoppingToken.IsCancellationRequested)
{
Tick();
try
{
await Task.Delay(20, stoppingToken);
}
catch (OperationCanceledException)
{
return;
}
}
}
private async Task Init()
{
_allcall.Write(new byte[] { REGISTER_MODE1, MODE1_SUBADDR1 | MODE1_ALLCALL });
await Task.Delay(10);
_allcall.Write(new byte[] { REGISTER_GRPPWM, PWM_DEFAULT });
_allcall.Write(new byte[] { REGISTER_PWM0 | AUTO_INCREMENT, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
_allcall.Write(new byte[] { REGISTER_LEDOUT0 | AUTO_INCREMENT, 0xFF, 0xFF, 0xFF, 0xFF });
_minute.Write(new byte[] { REGISTER_MODE1, MODE1_ALLCALL });
_second.Write(new byte[] { REGISTER_MODE1, MODE1_ALLCALL });
}
private void Tick()
{
var now = DateTime.Now;
Buffer.BlockCopy(DIGITS[now.Second], 0, _secondDisplayed, 0, _secondDisplayed.Length);
if (now.Millisecond > 500)
_secondDisplayed[11] = 0xFF;
_second.Write(_secondDisplayed);
_minute.Write(DIGITS[now.Minute]);
_hour.Write(DIGITS[now.Hour]);
if (now.Hour < DIMM_HOUR_END || now.Hour >= DIMM_HOUR_BEGIN)
_allcall.Write(new byte[] { REGISTER_GRPPWM, PWM_DIMM });
else
_allcall.Write(new byte[] { REGISTER_GRPPWM, PWM_DEFAULT });
}
public override void Dispose()
{
_hour.Dispose();
_minute.Dispose();
_second.Dispose();
_allcall.Write(new byte[] { REGISTER_LEDOUT0 | AUTO_INCREMENT, 0x00, 0x00, 0x00, 0x00 });
_allcall.Write(new byte[] { REGISTER_PWM0 | AUTO_INCREMENT, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
_allcall.Write(new byte[] { REGISTER_MODE1, MODE1_SLEEP | MODE1_ALLCALL });
_allcall.Dispose();
base.Dispose();
}
}
}
| |
//
// PkzipClassic encryption
//
// Copyright 2004 John Reilly
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
//
#if ZIPLIB
#if !NETCF_1_0
using System;
using System.Security.Cryptography;
using ICSharpCode.SharpZipLib.Checksums;
namespace ICSharpCode.SharpZipLib.Encryption
{
/// <summary>
/// PkzipClassic embodies the classic or original encryption facilities used in Pkzip archives.
/// While it has been superceded by more recent and more powerful algorithms, its still in use and
/// is viable for preventing casual snooping
/// </summary>
internal abstract class PkzipClassic : SymmetricAlgorithm
{
/// <summary>
/// Generates new encryption keys based on given seed
/// </summary>
/// <param name="seed">The seed value to initialise keys with.</param>
/// <returns>A new key value.</returns>
static public byte[] GenerateKeys(byte[] seed)
{
if ( seed == null ) {
throw new ArgumentNullException("seed");
}
if ( seed.Length == 0 ) {
throw new ArgumentException("Length is zero", "seed");
}
uint[] newKeys = new uint[] {
0x12345678,
0x23456789,
0x34567890
};
for (int i = 0; i < seed.Length; ++i) {
newKeys[0] = Crc32.ComputeCrc32(newKeys[0], seed[i]);
newKeys[1] = newKeys[1] + (byte)newKeys[0];
newKeys[1] = newKeys[1] * 134775813 + 1;
newKeys[2] = Crc32.ComputeCrc32(newKeys[2], (byte)(newKeys[1] >> 24));
}
byte[] result = new byte[12];
result[0] = (byte)(newKeys[0] & 0xff);
result[1] = (byte)((newKeys[0] >> 8) & 0xff);
result[2] = (byte)((newKeys[0] >> 16) & 0xff);
result[3] = (byte)((newKeys[0] >> 24) & 0xff);
result[4] = (byte)(newKeys[1] & 0xff);
result[5] = (byte)((newKeys[1] >> 8) & 0xff);
result[6] = (byte)((newKeys[1] >> 16) & 0xff);
result[7] = (byte)((newKeys[1] >> 24) & 0xff);
result[8] = (byte)(newKeys[2] & 0xff);
result[9] = (byte)((newKeys[2] >> 8) & 0xff);
result[10] = (byte)((newKeys[2] >> 16) & 0xff);
result[11] = (byte)((newKeys[2] >> 24) & 0xff);
return result;
}
}
/// <summary>
/// PkzipClassicCryptoBase provides the low level facilities for encryption
/// and decryption using the PkzipClassic algorithm.
/// </summary>
class PkzipClassicCryptoBase
{
/// <summary>
/// Transform a single byte
/// </summary>
/// <returns>
/// The transformed value
/// </returns>
protected byte TransformByte()
{
uint temp = ((keys[2] & 0xFFFF) | 2);
return (byte)((temp * (temp ^ 1)) >> 8);
}
/// <summary>
/// Set the key schedule for encryption/decryption.
/// </summary>
/// <param name="keyData">The data use to set the keys from.</param>
protected void SetKeys(byte[] keyData)
{
if ( keyData == null ) {
throw new ArgumentNullException("keyData");
}
if ( keyData.Length != 12 ) {
throw new InvalidOperationException("Key length is not valid");
}
keys = new uint[3];
keys[0] = (uint)((keyData[3] << 24) | (keyData[2] << 16) | (keyData[1] << 8) | keyData[0]);
keys[1] = (uint)((keyData[7] << 24) | (keyData[6] << 16) | (keyData[5] << 8) | keyData[4]);
keys[2] = (uint)((keyData[11] << 24) | (keyData[10] << 16) | (keyData[9] << 8) | keyData[8]);
}
/// <summary>
/// Update encryption keys
/// </summary>
protected void UpdateKeys(byte ch)
{
keys[0] = Crc32.ComputeCrc32(keys[0], ch);
keys[1] = keys[1] + (byte)keys[0];
keys[1] = keys[1] * 134775813 + 1;
keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24));
}
/// <summary>
/// Reset the internal state.
/// </summary>
protected void Reset()
{
keys[0] = 0;
keys[1] = 0;
keys[2] = 0;
}
#region Instance Fields
uint[] keys;
#endregion
}
/// <summary>
/// PkzipClassic CryptoTransform for encryption.
/// </summary>
class PkzipClassicEncryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform
{
/// <summary>
/// Initialise a new instance of <see cref="PkzipClassicEncryptCryptoTransform"></see>
/// </summary>
/// <param name="keyBlock">The key block to use.</param>
internal PkzipClassicEncryptCryptoTransform(byte[] keyBlock)
{
SetKeys(keyBlock);
}
#region ICryptoTransform Members
/// <summary>
/// Transforms the specified region of the specified byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the byte array to use as data.</param>
/// <returns>The computed transform.</returns>
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
byte[] result = new byte[inputCount];
TransformBlock(inputBuffer, inputOffset, inputCount, result, 0);
return result;
}
/// <summary>
/// Transforms the specified region of the input byte array and copies
/// the resulting transform to the specified region of the output byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the input byte array to use as data.</param>
/// <param name="outputBuffer">The output to which to write the transform.</param>
/// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param>
/// <returns>The number of bytes written.</returns>
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
for (int i = inputOffset; i < inputOffset + inputCount; ++i) {
byte oldbyte = inputBuffer[i];
outputBuffer[outputOffset++] = (byte)(inputBuffer[i] ^ TransformByte());
UpdateKeys(oldbyte);
}
return inputCount;
}
/// <summary>
/// Gets a value indicating whether the current transform can be reused.
/// </summary>
public bool CanReuseTransform
{
get {
return true;
}
}
/// <summary>
/// Gets the size of the input data blocks in bytes.
/// </summary>
public int InputBlockSize
{
get {
return 1;
}
}
/// <summary>
/// Gets the size of the output data blocks in bytes.
/// </summary>
public int OutputBlockSize
{
get {
return 1;
}
}
/// <summary>
/// Gets a value indicating whether multiple blocks can be transformed.
/// </summary>
public bool CanTransformMultipleBlocks
{
get {
return true;
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Cleanup internal state.
/// </summary>
public void Dispose()
{
Reset();
}
#endregion
}
/// <summary>
/// PkzipClassic CryptoTransform for decryption.
/// </summary>
class PkzipClassicDecryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform
{
/// <summary>
/// Initialise a new instance of <see cref="PkzipClassicDecryptCryptoTransform"></see>.
/// </summary>
/// <param name="keyBlock">The key block to decrypt with.</param>
internal PkzipClassicDecryptCryptoTransform(byte[] keyBlock)
{
SetKeys(keyBlock);
}
#region ICryptoTransform Members
/// <summary>
/// Transforms the specified region of the specified byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the byte array to use as data.</param>
/// <returns>The computed transform.</returns>
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
byte[] result = new byte[inputCount];
TransformBlock(inputBuffer, inputOffset, inputCount, result, 0);
return result;
}
/// <summary>
/// Transforms the specified region of the input byte array and copies
/// the resulting transform to the specified region of the output byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the input byte array to use as data.</param>
/// <param name="outputBuffer">The output to which to write the transform.</param>
/// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param>
/// <returns>The number of bytes written.</returns>
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
for (int i = inputOffset; i < inputOffset + inputCount; ++i) {
byte newByte = (byte)(inputBuffer[i] ^ TransformByte());
outputBuffer[outputOffset++] = newByte;
UpdateKeys(newByte);
}
return inputCount;
}
/// <summary>
/// Gets a value indicating whether the current transform can be reused.
/// </summary>
public bool CanReuseTransform
{
get {
return true;
}
}
/// <summary>
/// Gets the size of the input data blocks in bytes.
/// </summary>
public int InputBlockSize
{
get {
return 1;
}
}
/// <summary>
/// Gets the size of the output data blocks in bytes.
/// </summary>
public int OutputBlockSize
{
get {
return 1;
}
}
/// <summary>
/// Gets a value indicating whether multiple blocks can be transformed.
/// </summary>
public bool CanTransformMultipleBlocks
{
get {
return true;
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Cleanup internal state.
/// </summary>
public void Dispose()
{
Reset();
}
#endregion
}
/// <summary>
/// Defines a wrapper object to access the Pkzip algorithm.
/// This class cannot be inherited.
/// </summary>
internal sealed class PkzipClassicManaged : PkzipClassic
{
/// <summary>
/// Get / set the applicable block size in bits.
/// </summary>
/// <remarks>The only valid block size is 8.</remarks>
public override int BlockSize
{
get {
return 8;
}
set {
if (value != 8) {
throw new CryptographicException("Block size is invalid");
}
}
}
/// <summary>
/// Get an array of legal <see cref="KeySizes">key sizes.</see>
/// </summary>
public override KeySizes[] LegalKeySizes
{
get {
KeySizes[] keySizes = new KeySizes[1];
keySizes[0] = new KeySizes(12 * 8, 12 * 8, 0);
return keySizes;
}
}
/// <summary>
/// Generate an initial vector.
/// </summary>
public override void GenerateIV()
{
// Do nothing.
}
/// <summary>
/// Get an array of legal <see cref="KeySizes">block sizes</see>.
/// </summary>
public override KeySizes[] LegalBlockSizes
{
get {
KeySizes[] keySizes = new KeySizes[1];
keySizes[0] = new KeySizes(1 * 8, 1 * 8, 0);
return keySizes;
}
}
/// <summary>
/// Get / set the key value applicable.
/// </summary>
public override byte[] Key
{
get {
if ( key_ == null ) {
GenerateKey();
}
return (byte[]) key_.Clone();
}
set {
if ( value == null ) {
throw new ArgumentNullException("value");
}
if ( value.Length != 12 ) {
throw new CryptographicException("Key size is illegal");
}
key_ = (byte[]) value.Clone();
}
}
/// <summary>
/// Generate a new random key.
/// </summary>
public override void GenerateKey()
{
key_ = new byte[12];
Random rnd = new Random();
rnd.NextBytes(key_);
}
/// <summary>
/// Create an encryptor.
/// </summary>
/// <param name="rgbKey">The key to use for this encryptor.</param>
/// <param name="rgbIV">Initialisation vector for the new encryptor.</param>
/// <returns>Returns a new PkzipClassic encryptor</returns>
public override ICryptoTransform CreateEncryptor(
byte[] rgbKey,
byte[] rgbIV)
{
key_ = rgbKey;
return new PkzipClassicEncryptCryptoTransform(Key);
}
/// <summary>
/// Create a decryptor.
/// </summary>
/// <param name="rgbKey">Keys to use for this new decryptor.</param>
/// <param name="rgbIV">Initialisation vector for the new decryptor.</param>
/// <returns>Returns a new decryptor.</returns>
public override ICryptoTransform CreateDecryptor(
byte[] rgbKey,
byte[] rgbIV)
{
key_ = rgbKey;
return new PkzipClassicDecryptCryptoTransform(Key);
}
#region Instance Fields
byte[] key_;
#endregion
}
}
#endif
#endif
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text;
namespace System.Management.Automation
{
internal class MergedCommandParameterMetadata
{
/// <summary>
/// Replaces any existing metadata in this object with the metadata specified.
///
/// Note that this method should NOT be called after a MergedCommandParameterMetadata
/// instance is made read only by calling MakeReadOnly(). This is because MakeReadOnly()
/// will turn 'bindableParameters', 'aliasedParameters' and 'parameterSetMap' into
/// ReadOnlyDictionary and ReadOnlyCollection.
/// </summary>
///
/// <param name="metadata">
/// The metadata to replace in this object.
/// </param>
///
/// <returns>
/// A list of the merged parameter metadata that was added.
/// </returns>
internal List<MergedCompiledCommandParameter> ReplaceMetadata(MergedCommandParameterMetadata metadata)
{
var result = new List<MergedCompiledCommandParameter>();
// Replace bindable parameters
_bindableParameters.Clear();
foreach (KeyValuePair<string, MergedCompiledCommandParameter> entry in metadata.BindableParameters)
{
_bindableParameters.Add(entry.Key, entry.Value);
result.Add(entry.Value);
}
_aliasedParameters.Clear();
foreach (KeyValuePair<string, MergedCompiledCommandParameter> entry in metadata.AliasedParameters)
{
_aliasedParameters.Add(entry.Key, entry.Value);
}
// Replace additional meta info
_defaultParameterSetName = metadata._defaultParameterSetName;
_nextAvailableParameterSetIndex = metadata._nextAvailableParameterSetIndex;
_parameterSetMap.Clear();
var parameterSetMapInList = (List<string>)_parameterSetMap;
parameterSetMapInList.AddRange(metadata._parameterSetMap);
Diagnostics.Assert(ParameterSetCount == _nextAvailableParameterSetIndex,
"After replacement with the metadata of the new parameters, ParameterSetCount should be equal to nextAvailableParameterSetIndex");
return result;
} // ReplaceMetadata
/// <summary>
/// Merges the specified metdata with the other metadata already defined
/// in this object.
/// </summary>
///
/// <param name="parameterMetadata">
/// The compiled metadata for the type to be merged.
/// </param>
///
/// <param name="binderAssociation">
/// The type of binder that the CommandProcessor will use to bind
/// the parameters for <paramref name="parameterMetadata"/>
/// </param>
///
/// <returns>
/// A collection of the merged parameter metadata that was added.
/// </returns>
///
/// <exception cref="MetadataException">
/// If a parameter name or alias described in the <paramref name="parameterMetadata"/> already
/// exists.
/// </exception>
///
internal Collection<MergedCompiledCommandParameter> AddMetadataForBinder(
InternalParameterMetadata parameterMetadata,
ParameterBinderAssociation binderAssociation)
{
if (parameterMetadata == null)
{
throw PSTraceSource.NewArgumentNullException("parameterMetadata");
}
Collection<MergedCompiledCommandParameter> result =
new Collection<MergedCompiledCommandParameter>();
// Merge in the bindable parameters
foreach (KeyValuePair<string, CompiledCommandParameter> bindableParameter in parameterMetadata.BindableParameters)
{
if (_bindableParameters.ContainsKey(bindableParameter.Key))
{
MetadataException exception =
new MetadataException(
"ParameterNameAlreadyExistsForCommand",
null,
Metadata.ParameterNameAlreadyExistsForCommand,
bindableParameter.Key);
throw exception;
}
// NTRAID#Windows Out Of Band Releases-926371-2005/12/27-JonN
if (_aliasedParameters.ContainsKey(bindableParameter.Key))
{
MetadataException exception =
new MetadataException(
"ParameterNameConflictsWithAlias",
null,
Metadata.ParameterNameConflictsWithAlias,
bindableParameter.Key,
RetrieveParameterNameForAlias(bindableParameter.Key, _aliasedParameters));
throw exception;
}
MergedCompiledCommandParameter mergedParameter =
new MergedCompiledCommandParameter(bindableParameter.Value, binderAssociation);
_bindableParameters.Add(bindableParameter.Key, mergedParameter);
result.Add(mergedParameter);
// Merge in the aliases
foreach (string aliasName in bindableParameter.Value.Aliases)
{
if (_aliasedParameters.ContainsKey(aliasName))
{
MetadataException exception =
new MetadataException(
"AliasParameterNameAlreadyExistsForCommand",
null,
Metadata.AliasParameterNameAlreadyExistsForCommand,
aliasName);
throw exception;
}
// NTRAID#Windows Out Of Band Releases-926371-2005/12/27-JonN
if (_bindableParameters.ContainsKey(aliasName))
{
MetadataException exception =
new MetadataException(
"ParameterNameConflictsWithAlias",
null,
Metadata.ParameterNameConflictsWithAlias,
RetrieveParameterNameForAlias(aliasName, _bindableParameters),
bindableParameter.Value.Name);
throw exception;
}
_aliasedParameters.Add(aliasName, mergedParameter);
}
}
return result;
}
/// <summary>
/// The next available parameter set bit. This number increments but the parameter
/// set bit is really 1 shifted left this number of times. This number also acts
/// as the index for the parameter set map.
/// </summary>
private uint _nextAvailableParameterSetIndex;
/// <summary>
/// Gets the number of parameter sets that were declared for the command.
/// </summary>
///
internal int ParameterSetCount
{
get
{
return _parameterSetMap.Count;
}
} // ParameterSetCount
/// <summary>
/// Gets a bit-field representing all valid parameter sets
/// </summary>
internal uint AllParameterSetFlags
{
get
{
return (1u << ParameterSetCount) - 1;
}
}
/// <summary>
/// This is the parameter set map. The index is the number of times 1 gets shifted
/// left to specify the bit field marker for the parameter set.
/// The value is the parameter set name.
/// New parameter sets are added at the nextAvailableParameterSetIndex.
/// </summary>
///
private IList<string> _parameterSetMap = new List<string>();
/// <summary>
/// The name of the default parameter set
/// </summary>
private string _defaultParameterSetName;
/// <summary>
/// Adds the parameter set name to the parameter set map and returns the
/// index. If the parameter set name was already in the map, the index to
/// the existing parameter set name is returned.
/// </summary>
///
/// <param name="parameterSetName">
/// The name of the parameter set to add.
/// </param>
///
/// <returns>
/// The index of the parameter set name. If the name didn't already exist the
/// name gets added and the new index is returned. If the name already exists
/// the index of the existing name is returned.
/// </returns>
///
/// <remarks>
/// The nextAvailableParameterSetIndex is incremented if the parameter set name
/// is added.
/// </remarks>
///
/// <exception cref="ParsingMetadataException">
/// If more than uint.MaxValue parameter-sets are defined for the command.
/// </exception>
private int AddParameterSetToMap(string parameterSetName)
{
int index = -1;
if (!String.IsNullOrEmpty(parameterSetName))
{
index = _parameterSetMap.IndexOf(parameterSetName);
// A parameter set name should only be added once
if (index == -1)
{
if (_nextAvailableParameterSetIndex == uint.MaxValue)
{
// Don't let the parameter set index overflow
ParsingMetadataException parsingException =
new ParsingMetadataException(
"ParsingTooManyParameterSets",
null,
Metadata.ParsingTooManyParameterSets);
throw parsingException;
}
_parameterSetMap.Add(parameterSetName);
index = _parameterSetMap.IndexOf(parameterSetName);
Diagnostics.Assert(
index == _nextAvailableParameterSetIndex,
"AddParameterSetToMap should always add the parameter set name to the map at the nextAvailableParameterSetIndex");
_nextAvailableParameterSetIndex++;
}
}
return index;
} // AddParameterSetToMap
/// <summary>
/// Loops through all the parameters and retrieves the parameter set names. In the process
/// it generates a mapping of parameter set names to the bits in the bit-field and sets
/// the parameter set flags for the parameter.
/// </summary>
///
/// <param name="defaultParameterSetName">
/// The default parameter set name.
/// </param>
///
/// <returns>
/// The bit flag for the default parameter set.
/// </returns>
///
/// <exception cref="ParsingMetadataException">
/// If more than uint.MaxValue parameter-sets are defined for the command.
/// </exception>
///
internal uint GenerateParameterSetMappingFromMetadata(string defaultParameterSetName)
{
// First clear the parameter set map
_parameterSetMap.Clear();
_nextAvailableParameterSetIndex = 0;
uint defaultParameterSetFlag = 0;
if (!String.IsNullOrEmpty(defaultParameterSetName))
{
_defaultParameterSetName = defaultParameterSetName;
// Add the default parameter set to the parameter set map
int index = AddParameterSetToMap(defaultParameterSetName);
defaultParameterSetFlag = (uint)1 << index;
}
// Loop through all the parameters and then each parameter set for each parameter
foreach (MergedCompiledCommandParameter parameter in BindableParameters.Values)
{
// For each parameter we need to generate a bit-field for the parameter sets
// that the parameter is a part of.
uint parameterSetBitField = 0;
foreach (var keyValuePair in parameter.Parameter.ParameterSetData)
{
var parameterSetName = keyValuePair.Key;
var parameterSetData = keyValuePair.Value;
if (String.Equals(parameterSetName, ParameterAttribute.AllParameterSets, StringComparison.OrdinalIgnoreCase))
{
// Don't add the parameter set name but assign the bit field zero and then mark the bool
parameterSetData.ParameterSetFlag = 0;
parameterSetData.IsInAllSets = true;
parameter.Parameter.IsInAllSets = true;
}
else
{
// Add the parameter set name and/or get the index in the map
int index = AddParameterSetToMap(parameterSetName);
Diagnostics.Assert(
index >= 0,
"AddParameterSetToMap should always be able to add the parameter set name, if not it should throw");
// Calculate the bit for this parameter set
uint parameterSetBit = (uint)1 << index;
// Add the bit to the bit-field
parameterSetBitField |= parameterSetBit;
// Add the bit to the parameter set specific data
parameterSetData.ParameterSetFlag = parameterSetBit;
}
}
// Set the bit field in the parameter
parameter.Parameter.ParameterSetFlags = parameterSetBitField;
}
return defaultParameterSetFlag;
} // GenerateParameterSetMappingFromMetadata
/// <summary>
/// Gets the parameter set name for the specified parameter set.
/// </summary>
///
/// <param name="parameterSet">
/// The parameter set to get the name for.
/// </param>
///
/// <returns>
/// The name of the specified parameter set.
/// </returns>
///
internal string GetParameterSetName(uint parameterSet)
{
string result = _defaultParameterSetName;
if (String.IsNullOrEmpty(result))
{
result = ParameterAttribute.AllParameterSets;
}
if (parameterSet != uint.MaxValue && parameterSet != 0)
{
// Count the number of right shifts it takes to hit the parameter set
// This is the index into the parameter set map.
int index = 0;
while (((parameterSet >> index) & 0x1) == 0)
{
++index;
}
// Now check to see if there are any remaining sets passed this bit.
// If so return String.Empty
if (((parameterSet >> (index + 1)) & 0x1) == 0)
{
// Ensure that the bit found was within the map, if not return an empty string
if (index < _parameterSetMap.Count)
{
result = _parameterSetMap[index];
}
else
{
result = String.Empty;
}
}
else
{
result = String.Empty;
}
}
return result;
} // GetParameterSetName
/// <summary>
/// Helper function to retrieve the name of the parameter
/// which defined an alias.
/// </summary>
/// <param name="key"></param>
/// <param name="dict"></param>
/// <returns></returns>
private static string RetrieveParameterNameForAlias(
string key,
IDictionary<string, MergedCompiledCommandParameter> dict)
{
MergedCompiledCommandParameter mergedParam = dict[key];
if (null != mergedParam)
{
CompiledCommandParameter compiledParam = mergedParam.Parameter;
if (null != compiledParam)
{
if (!String.IsNullOrEmpty(compiledParam.Name))
return compiledParam.Name;
}
}
return String.Empty;
}
/// <summary>
/// Gets the parameters by matching its name.
/// </summary>
///
/// <param name="name">
/// The name of the parameter.
/// </param>
///
/// <param name="throwOnParameterNotFound">
/// If true and a matching parameter is not found, an exception will be
/// throw. If false and a matching parameter is not found, null is returned.
/// </param>
///
/// <param name="tryExactMatching">
/// If true we do exact matching, otherwise we do not.
/// </param>
///
/// <param name="invocationInfo">
/// The invocation information about the code being run.
/// </param>
///
/// <returns>
/// The a collection of the metadata associated with the parameters that
/// match the specified name. If no matches were found, an empty collection
/// is returned.
/// </returns>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
///
internal MergedCompiledCommandParameter GetMatchingParameter(
string name,
bool throwOnParameterNotFound,
bool tryExactMatching,
InvocationInfo invocationInfo)
{
if (string.IsNullOrEmpty(name))
{
throw PSTraceSource.NewArgumentException("name");
}
Collection<MergedCompiledCommandParameter> matchingParameters =
new Collection<MergedCompiledCommandParameter>();
// Skip the leading '-' if present
if (name.Length > 0 && SpecialCharacters.IsDash(name[0]))
{
name = name.Substring(1);
}
// First try to match the bindable parameters
foreach (string parameterName in _bindableParameters.Keys)
{
if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase))
{
// If it is an exact match then only return the exact match
// as the result
if (tryExactMatching && String.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase))
{
return _bindableParameters[parameterName];
}
else
{
matchingParameters.Add(_bindableParameters[parameterName]);
}
}
}
// Now check the aliases
foreach (string parameterName in _aliasedParameters.Keys)
{
if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase))
{
// If it is an exact match then only return the exact match
// as the result
if (tryExactMatching && String.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase))
{
return _aliasedParameters[parameterName];
}
else
{
if (!matchingParameters.Contains(_aliasedParameters[parameterName]))
{
matchingParameters.Add(_aliasedParameters[parameterName]);
}
}
}
}
if (matchingParameters.Count > 1)
{
// Prefer parameters in the cmdlet over common parameters
Collection<MergedCompiledCommandParameter> filteredParameters =
new Collection<MergedCompiledCommandParameter>();
foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters)
{
if ((matchingParameter.BinderAssociation == ParameterBinderAssociation.DeclaredFormalParameters) ||
(matchingParameter.BinderAssociation == ParameterBinderAssociation.DynamicParameters))
{
filteredParameters.Add(matchingParameter);
}
}
if (filteredParameters.Count == 1)
{
matchingParameters = filteredParameters;
}
else
{
StringBuilder possibleMatches = new StringBuilder();
foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters)
{
possibleMatches.Append(" -");
possibleMatches.Append(matchingParameter.Parameter.Name);
}
ParameterBindingException exception =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
invocationInfo,
null,
name,
null,
null,
ParameterBinderStrings.AmbiguousParameter,
"AmbiguousParameter",
possibleMatches);
throw exception;
}
}
else if (matchingParameters.Count == 0)
{
if (throwOnParameterNotFound)
{
ParameterBindingException exception =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
invocationInfo,
null,
name,
null,
null,
ParameterBinderStrings.NamedParameterNotFound,
"NamedParameterNotFound");
throw exception;
}
}
MergedCompiledCommandParameter result = null;
if (matchingParameters.Count > 0)
{
result = matchingParameters[0];
}
return result;
} // GetMatchingParameter
/// <summary>
/// Gets a collection of all the parameters that are allowed in the parameter set
/// </summary>
///
/// <param name="parameterSetFlag">
/// The bit representing the parameter set from which the parameters should be retrieved.
/// </param>
///
/// <returns>
/// A collection of all the parameters in the specified parameter set.
/// </returns>
///
internal Collection<MergedCompiledCommandParameter> GetParametersInParameterSet(uint parameterSetFlag)
{
Collection<MergedCompiledCommandParameter> result =
new Collection<MergedCompiledCommandParameter>();
foreach (MergedCompiledCommandParameter parameter in BindableParameters.Values)
{
if ((parameterSetFlag & parameter.Parameter.ParameterSetFlags) != 0 ||
parameter.Parameter.IsInAllSets)
{
result.Add(parameter);
}
}
return result;
} // GetParametersInParameterSet
/// <summary>
/// Gets a dictionary of the compiled parameter metadata for this Type.
/// The dictionary keys are the names of the parameters and
/// the values are the compiled parameter metdata.
/// </summary>
internal IDictionary<string, MergedCompiledCommandParameter> BindableParameters { get { return _bindableParameters; } }
private IDictionary<string, MergedCompiledCommandParameter> _bindableParameters =
new Dictionary<string, MergedCompiledCommandParameter>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets a dictionary of the parameters that have been aliased to other names. The key is
/// the alias name and the value is the MergedCompiledCommandParameter metadata.
/// </summary>
internal IDictionary<string, MergedCompiledCommandParameter> AliasedParameters { get { return _aliasedParameters; } }
private IDictionary<string, MergedCompiledCommandParameter> _aliasedParameters =
new Dictionary<string, MergedCompiledCommandParameter>(StringComparer.OrdinalIgnoreCase);
internal void MakeReadOnly()
{
_bindableParameters = new ReadOnlyDictionary<string, MergedCompiledCommandParameter>(_bindableParameters);
_aliasedParameters = new ReadOnlyDictionary<string, MergedCompiledCommandParameter>(_aliasedParameters);
_parameterSetMap = new ReadOnlyCollection<string>(_parameterSetMap);
}
internal void ResetReadOnly()
{
_bindableParameters = new Dictionary<string, MergedCompiledCommandParameter>(_bindableParameters, StringComparer.OrdinalIgnoreCase);
_aliasedParameters = new Dictionary<string, MergedCompiledCommandParameter>(_aliasedParameters, StringComparer.OrdinalIgnoreCase);
}
} // MergedCommandParameterMetadata
/// <summary>
/// Makes an association between a CompiledCommandParameter and the type
/// of the parameter binder used to bind the parameter.
/// </summary>
///
internal class MergedCompiledCommandParameter
{
/// <summary>
/// Constructs an association between the CompiledCommandParameter and the
/// binder that should be used to bind it.
/// </summary>
///
/// <param name="parameter">
/// The metadata for a parameter.
/// </param>
///
/// <param name="binderAssociation">
/// The type of binder that should be used to bind the parameter.
/// </param>
internal MergedCompiledCommandParameter(
CompiledCommandParameter parameter,
ParameterBinderAssociation binderAssociation)
{
Diagnostics.Assert(parameter != null, "caller to verify parameter is not null");
this.Parameter = parameter;
this.BinderAssociation = binderAssociation;
}
/// <summary>
/// Gets the compiled command parameter for the association
/// </summary>
internal CompiledCommandParameter Parameter { get; private set; }
/// <summary>
/// Gets the type of binder that the compiled command parameter should be bound with.
/// </summary>
internal ParameterBinderAssociation BinderAssociation { get; private set; }
public override string ToString()
{
return Parameter.ToString();
}
}
/// <summary>
/// This enum is used in the MergedCompiledCommandParameter class
/// to associate a particular CompiledCommandParameter with the
/// appropriate ParameterBinder.
/// </summary>
///
internal enum ParameterBinderAssociation
{
/// <summary>
/// The parameter was declared as a formal parameter in the command type.
/// </summary>
DeclaredFormalParameters,
/// <summary>
/// The parameter was declared as a dynamic parameter for the command.
/// </summary>
DynamicParameters,
/// <summary>
/// The parameter is a common parameter found in the CommonParameters class.
/// </summary>
CommonParameters,
/// <summary>
/// The parameter is a ShouldProcess parameter found in the ShouldProcessParameters class.
/// </summary>
ShouldProcessParameters,
/// <summary>
/// The parameter is a transactions parameter found in the TransactionParameters class.
/// </summary>
TransactionParameters,
/// <summary>
/// The parameter is a Paging parameter found in the PagingParameters class.
/// </summary>
PagingParameters,
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyModel;
namespace Estellaris.Core.DI {
public class DependenciesProvider : IDisposable {
static DependenciesProvider _instance { get; set; }
static readonly object _lock = new object();
IServiceProvider _serviceProvider { get; set; }
readonly IServiceCollection _serviceCollection = new ServiceCollection();
public DependenciesProvider Current {
get {
lock(_lock) {
if (_instance == null)
_instance = new DependenciesProvider();
}
return _instance;
}
}
public static DependenciesProvider Create() {
return new DependenciesProvider();
}
public DependenciesProvider AddScopedFromAssemblies(Func<AssemblyName, bool> filters) {
return AddFromAssemblies(filters, DependencyScope.Scoped);
}
public DependenciesProvider AddTransientFromAssemblies(Func<AssemblyName, bool> filters) {
return AddFromAssemblies(filters, DependencyScope.Transient);
}
public DependenciesProvider AddSingletonFromAssemblies(Func<AssemblyName, bool> filters) {
return AddFromAssemblies(filters, DependencyScope.Singleton);
}
public DependenciesProvider AddScopedFromAssemblies(IEnumerable<Assembly> assemblies) {
return AddFromAssemblies(assemblies, DependencyScope.Scoped);
}
public DependenciesProvider AddTransientFromAssemblies(IEnumerable<Assembly> assemblies) {
return AddFromAssemblies(assemblies, DependencyScope.Transient);
}
public DependenciesProvider AddSingletonFromAssemblies(IEnumerable<Assembly> assemblies) {
return AddFromAssemblies(assemblies, DependencyScope.Singleton);
}
DependenciesProvider AddFromAssemblies(Func<AssemblyName, bool> filters, DependencyScope scope) {
var rootAssembly = Assembly.GetEntryAssembly();
var assemblies = rootAssembly.GetReferencedAssemblies()
.Where(filters)
.Select(Assembly.Load).ToList();
if (filters.Invoke(rootAssembly.GetName()))
assemblies.Add(rootAssembly);
return AddFromAssemblies(assemblies, scope);
}
DependenciesProvider AddFromAssemblies(IEnumerable<Assembly> assemblies, DependencyScope scope) {
if (_serviceProvider != null)
return this;
var types = assemblies.SelectMany(_ => _.DefinedTypes).ToList();
var classes = types.Where(_ => _.IsClass).ToList();
var interfaces = types.Where(_ => _.IsInterface).ToList();
foreach(var _interface in interfaces) {
var implementation = classes.FirstOrDefault(_ => _.Name == _interface.Name.TrimStart('I'));
if (implementation != null) {
var interfaceType = _interface.Assembly.GetType(_interface.FullName);
var implementationType = implementation.Assembly.GetType(implementation.FullName);
switch (scope) {
case DependencyScope.Scoped:
_serviceCollection.AddScoped(interfaceType, implementationType);
break;
case DependencyScope.Transient:
_serviceCollection.AddTransient(interfaceType, implementationType);
break;
case DependencyScope.Singleton:
_serviceCollection.AddSingleton(interfaceType, implementationType);
break;
}
}
}
return this;
}
public DependenciesProvider AddScoped(Type implementation) {
return AddScoped(implementation, implementation);
}
public DependenciesProvider AddScoped(Type type, Type implementation) {
if (_serviceProvider != null)
return this;
_serviceCollection.AddScoped(type, implementation);
return this;
}
public DependenciesProvider AddScoped<TImplementation>() {
AddScoped(typeof (TImplementation));
return this;
}
public DependenciesProvider AddScoped<TInterface, TImplementation>() {
AddScoped(typeof (TInterface), typeof (TImplementation));
return this;
}
public DependenciesProvider AddTransient(Type implementation) {
return AddTransient(implementation, implementation);
}
public DependenciesProvider AddTransient(Type type, Type implementation) {
if (_serviceProvider != null)
return this;
_serviceCollection.AddTransient(type, implementation);
return this;
}
public DependenciesProvider AddTransient<TImplementation>() {
AddTransient(typeof (TImplementation));
return this;
}
public DependenciesProvider AddTransient<TInterface, TImplementation>() {
AddTransient(typeof (TInterface), typeof (TImplementation));
return this;
}
public DependenciesProvider AddSingleton(Type implementation) {
return AddSingleton(implementation, implementation);
}
public DependenciesProvider AddSingleton(Type type, Type implementation) {
if (_serviceProvider != null)
return this;
_serviceCollection.AddSingleton(type, implementation);
return this;
}
public DependenciesProvider AddSingleton<TImplementation>() {
AddSingleton(typeof (TImplementation));
return this;
}
public DependenciesProvider AddSingleton<TInterface, TImplementation>() {
AddSingleton(typeof (TInterface), typeof (TImplementation));
return this;
}
public DependenciesProvider AddConfig<T>(string key) where T : class {
if (_serviceProvider != null)
return this;
if (Configs.Configuration == null)
Configs.Init();
return AddConfig<T>(opts => Configs.Configuration.GetSection(key).Bind(opts));
}
public DependenciesProvider AddConfig<T>(Action<T> configureOptions) where T : class {
_serviceCollection.AddOptions().Configure<T>(configureOptions);
return this;
}
public DependenciesProvider Add(Action<IServiceCollection> addAction) {
addAction?.Invoke(_serviceCollection);
return this;
}
public DependenciesProvider Build(IServiceCollection serviceCollection) {
foreach(var serviceDescriptor in _serviceCollection)
serviceCollection.Add(serviceDescriptor);
return this;
}
public DependenciesProvider Build() {
_serviceProvider = _serviceCollection.BuildServiceProvider();
return this;
}
public T GetService<T>() {
return _serviceProvider != null ? _serviceProvider.GetService<T>() : default(T);
}
public void Dispose() {
_serviceProvider = null;
_serviceCollection.Clear();
}
}
}
| |
// 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.Reflection;
using System.Runtime;
using System.ServiceModel.Channels;
namespace System.ServiceModel.Dispatcher
{
internal class ImmutableClientRuntime
{
private int _correlationCount;
private bool _addTransactionFlowProperties;
private IInteractiveChannelInitializer[] _interactiveChannelInitializers;
private IClientOperationSelector _operationSelector;
private IChannelInitializer[] _channelInitializers;
private IClientMessageInspector[] _messageInspectors;
private Dictionary<string, ProxyOperationRuntime> _operations;
private ProxyOperationRuntime _unhandled;
private bool _useSynchronizationContext;
private bool _validateMustUnderstand;
internal ImmutableClientRuntime(ClientRuntime behavior)
{
_channelInitializers = EmptyArray<IChannelInitializer>.ToArray(behavior.ChannelInitializers);
_interactiveChannelInitializers = EmptyArray<IInteractiveChannelInitializer>.ToArray(behavior.InteractiveChannelInitializers);
_messageInspectors = EmptyArray<IClientMessageInspector>.ToArray(behavior.MessageInspectors);
_operationSelector = behavior.OperationSelector;
_useSynchronizationContext = behavior.UseSynchronizationContext;
_validateMustUnderstand = behavior.ValidateMustUnderstand;
_unhandled = new ProxyOperationRuntime(behavior.UnhandledClientOperation, this);
_addTransactionFlowProperties = behavior.AddTransactionFlowProperties;
_operations = new Dictionary<string, ProxyOperationRuntime>();
for (int i = 0; i < behavior.Operations.Count; i++)
{
ClientOperation operation = behavior.Operations[i];
ProxyOperationRuntime operationRuntime = new ProxyOperationRuntime(operation, this);
_operations.Add(operation.Name, operationRuntime);
}
_correlationCount = _messageInspectors.Length + behavior.MaxParameterInspectors;
}
internal int MessageInspectorCorrelationOffset
{
get { return 0; }
}
internal int ParameterInspectorCorrelationOffset
{
get { return _messageInspectors.Length; }
}
internal int CorrelationCount
{
get { return _correlationCount; }
}
internal IClientOperationSelector OperationSelector
{
get { return _operationSelector; }
}
internal ProxyOperationRuntime UnhandledProxyOperation
{
get { return _unhandled; }
}
internal bool UseSynchronizationContext
{
get { return _useSynchronizationContext; }
}
internal bool ValidateMustUnderstand
{
get { return _validateMustUnderstand; }
set { _validateMustUnderstand = value; }
}
internal void AfterReceiveReply(ref ProxyRpc rpc)
{
int offset = this.MessageInspectorCorrelationOffset;
try
{
for (int i = 0; i < _messageInspectors.Length; i++)
{
_messageInspectors[i].AfterReceiveReply(ref rpc.Reply, rpc.Correlation[offset + i]);
if (WcfEventSource.Instance.ClientMessageInspectorAfterReceiveInvokedIsEnabled())
{
WcfEventSource.Instance.ClientMessageInspectorAfterReceiveInvoked(rpc.EventTraceActivity, _messageInspectors[i].GetType().FullName);
}
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
}
}
internal void BeforeSendRequest(ref ProxyRpc rpc)
{
int offset = this.MessageInspectorCorrelationOffset;
try
{
for (int i = 0; i < _messageInspectors.Length; i++)
{
ServiceChannel clientChannel = ServiceChannelFactory.GetServiceChannel(rpc.Channel.Proxy);
rpc.Correlation[offset + i] = _messageInspectors[i].BeforeSendRequest(ref rpc.Request, clientChannel);
if (WcfEventSource.Instance.ClientMessageInspectorBeforeSendInvokedIsEnabled())
{
WcfEventSource.Instance.ClientMessageInspectorBeforeSendInvoked(rpc.EventTraceActivity, _messageInspectors[i].GetType().FullName);
}
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
}
}
internal void DisplayInitializationUI(ServiceChannel channel)
{
EndDisplayInitializationUI(BeginDisplayInitializationUI(channel, null, null));
}
internal IAsyncResult BeginDisplayInitializationUI(ServiceChannel channel, AsyncCallback callback, object state)
{
return new DisplayInitializationUIAsyncResult(channel, _interactiveChannelInitializers, callback, state);
}
internal void EndDisplayInitializationUI(IAsyncResult result)
{
DisplayInitializationUIAsyncResult.End(result);
}
internal void InitializeChannel(IClientChannel channel)
{
try
{
for (int i = 0; i < _channelInitializers.Length; ++i)
{
_channelInitializers[i].Initialize(channel);
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
}
}
internal ProxyOperationRuntime GetOperation(MethodBase methodBase, object[] args, out bool canCacheResult)
{
if (_operationSelector == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException
(string.Format(SRServiceModel.SFxNeedProxyBehaviorOperationSelector2,
methodBase.Name,
methodBase.DeclaringType.Name)));
}
try
{
if (_operationSelector.AreParametersRequiredForSelection)
{
canCacheResult = false;
}
else
{
args = null;
canCacheResult = true;
}
string operationName = _operationSelector.SelectOperation(methodBase, args);
ProxyOperationRuntime operation;
if ((operationName != null) && _operations.TryGetValue(operationName, out operation))
{
return operation;
}
else
{
// did not find the right operation, will not know how
// to invoke the method.
return null;
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
}
}
internal ProxyOperationRuntime GetOperationByName(string operationName)
{
ProxyOperationRuntime operation = null;
if (_operations.TryGetValue(operationName, out operation))
return operation;
else
return null;
}
internal class DisplayInitializationUIAsyncResult : System.Runtime.AsyncResult
{
private ServiceChannel _channel;
private int _index = -1;
private IInteractiveChannelInitializer[] _initializers;
private IClientChannel _proxy;
private static AsyncCallback s_callback = Fx.ThunkCallback(new AsyncCallback(DisplayInitializationUIAsyncResult.Callback));
internal DisplayInitializationUIAsyncResult(ServiceChannel channel,
IInteractiveChannelInitializer[] initializers,
AsyncCallback callback, object state)
: base(callback, state)
{
_channel = channel;
_initializers = initializers;
_proxy = ServiceChannelFactory.GetServiceChannel(channel.Proxy);
this.CallBegin(true);
}
private void CallBegin(bool completedSynchronously)
{
while (++_index < _initializers.Length)
{
IAsyncResult result = null;
Exception exception = null;
try
{
result = _initializers[_index].BeginDisplayInitializationUI(
_proxy,
DisplayInitializationUIAsyncResult.s_callback,
this
);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
exception = e;
}
if (exception == null)
{
if (!result.CompletedSynchronously)
{
return;
}
this.CallEnd(result, out exception);
}
if (exception != null)
{
this.CallComplete(completedSynchronously, exception);
return;
}
}
this.CallComplete(completedSynchronously, null);
}
private static void Callback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
DisplayInitializationUIAsyncResult outer = (DisplayInitializationUIAsyncResult)result.AsyncState;
Exception exception = null;
outer.CallEnd(result, out exception);
if (exception != null)
{
outer.CallComplete(false, exception);
return;
}
outer.CallBegin(false);
}
private void CallEnd(IAsyncResult result, out Exception exception)
{
try
{
_initializers[_index].EndDisplayInitializationUI(result);
exception = null;
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
exception = e;
}
}
private void CallComplete(bool completedSynchronously, Exception exception)
{
this.Complete(completedSynchronously, exception);
}
internal static void End(IAsyncResult result)
{
System.Runtime.AsyncResult.End<DisplayInitializationUIAsyncResult>(result);
}
}
}
}
| |
#region Apache Notice
/*****************************************************************************
*
* Castle.Igloo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using Castle.Core;
using Castle.Igloo.LifestyleManager;
using Castle.Igloo.Util;
using Castle.MicroKernel;
namespace Castle.Igloo.Scopes.Web
{
/// <summary>
/// Implementation of <see cref="IScope"/> that scopes a single component model
/// to the lifecycle of a single HTTP request;
/// </summary>
public sealed class WebRequestScope : IRequestScope
{
public const string REQUEST_SCOPE_SUFFIX = "request.scope.";
private const string INIT_REQUEST_CONTEXT = "_INIT_REQUEST_CONTEXT_";
private const string COMPONENT_NAMES = "_COMPONENT_NAMEs_";
/// <summary>
/// Inits the request context.
/// </summary>
private void InitRequestContext()
{
if (!WebUtil.GetCurrentHttpContext().Items.Contains(INIT_REQUEST_CONTEXT))
{
WebUtil.GetCurrentHttpContext().Items.Add(COMPONENT_NAMES, new StringCollection());
WebUtil.GetCurrentHttpContext().Items.Add(INIT_REQUEST_CONTEXT, INIT_REQUEST_CONTEXT);
}
}
#region IRequestContext Members
/// <summary>
/// Gets a value indicating whether this context is active.
/// </summary>
/// <value><c>true</c> if this instance is active; otherwise, <c>false</c>.</value>
public bool IsActive
{
get { return WebUtil.GetCurrentHttpContext() != null; }
}
/// <summary>
/// Gets or sets the <see cref="Object"/> with the specified name.
/// </summary>
/// <value></value>
public object this[string name]
{
get
{
TraceUtil.Log("Get from request scope : " + name);
InitRequestContext();
return WebUtil.GetCurrentHttpContext().Items[REQUEST_SCOPE_SUFFIX + name];
}
set
{
TraceUtil.Log("Set to request scope : " + name);
InitRequestContext();
if (!ComponentNames.Contains(name))
{
ComponentNames.Add(name);
}
WebUtil.GetCurrentHttpContext().Items[REQUEST_SCOPE_SUFFIX + name] = value;
}
}
/// <summary>
/// Removes the element with the specified name from the IScope object.
/// </summary>
/// <param name="name">The name of the element to remove.</param>
public void Remove(string name)
{
TraceUtil.Log("Remove from request scope : " + name);
InitRequestContext();
ComponentNames.Remove(name);
WebUtil.GetCurrentHttpContext().Items.Remove(REQUEST_SCOPE_SUFFIX + name);
}
/// <summary>
/// Determines whether the IDictionary object contains an element with the specified name.
/// </summary>
/// <param name="name">The name to locate in the IScope object.</param>
/// <returns></returns>
public bool Contains(string name)
{
InitRequestContext();
return ComponentNames.Contains(name);
}
/// <summary>
/// Gets All the objects names contain in the IScope object.
/// </summary>
/// <value>The names.</value>
public ICollection Names
{
get
{
InitRequestContext();
return ComponentNames;
}
}
/// <summary>
/// Removes all the elements from the IScope object.
/// </summary>
public void Flush()
{
TraceUtil.Log("Flush request scope.");
StringCollection toRemove = new StringCollection();
StringCollection names = (StringCollection)WebUtil.GetCurrentHttpContext().Items[COMPONENT_NAMES];
foreach (string name in names)
{
WebUtil.GetCurrentHttpContext().Items.Remove(REQUEST_SCOPE_SUFFIX + name);
toRemove.Remove(name);
}
names.Clear();
}
/// <summary>
/// Registers for eviction.
/// </summary>
/// <param name="manager">The manager.</param>
/// <param name="model">The ComponentModel.</param>
/// <param name="instance">The instance.</param>
public void RegisterForEviction(ILifestyleManager manager, ComponentModel model, object instance)
{
ScopeLifestyleModule.RegisterForRequestEviction((ScopeLifestyleManager)manager, model, instance);
}
/// <summary>
/// Checks the initialisation.
/// </summary>
public void CheckInitialisation()
{
if (!ScopeLifestyleModule.Initialized)
{
string message = "Looks like you forgot to register the http module " +
typeof(ScopeLifestyleModule).FullName +
"\r\nAdd '<add name=\"ScopeLifestyleModule\" type=\"Castle.Igloo.LifestyleManager.ScopeLifestyleModule, Castle.Igloo\" />' " +
"to the <httpModules> section on your web.config";
{
throw new ConfigurationErrorsException(message);
}
}
}
/// <summary>
/// Gets the type of the scope.
/// </summary>
/// <value>The type of the scope.</value>
public string ScopeType
{
get
{
InitRequestContext();
return Igloo.ScopeType.Request;
}
}
#endregion
private StringCollection ComponentNames
{
get
{
StringCollection names = (StringCollection)WebUtil.GetCurrentHttpContext().Items[COMPONENT_NAMES];
if (names == null)
{
names = new StringCollection();
WebUtil.GetCurrentHttpContext().Items.Add(COMPONENT_NAMES, names);
}
return names;
}
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Diagnostics.Tracing
{
[System.FlagsAttribute]
public enum EventActivityOptions
{
Detachable = 8,
Disable = 2,
None = 0,
Recursive = 4,
}
[System.AttributeUsageAttribute((System.AttributeTargets)(64))]
public sealed partial class EventAttribute : System.Attribute
{
public EventAttribute(int eventId) { }
public System.Diagnostics.Tracing.EventActivityOptions ActivityOptions { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventChannel Channel { get { throw null; } set { } }
public int EventId { get { throw null; } }
public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } set { } }
public string Message { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventTask Task { get { throw null; } set { } }
public byte Version { get { throw null; } set { } }
}
public enum EventChannel : byte
{
Admin = (byte)16,
Analytic = (byte)18,
Debug = (byte)19,
None = (byte)0,
Operational = (byte)17,
}
public enum EventCommand
{
Disable = -3,
Enable = -2,
SendManifest = -1,
Update = 0,
}
public partial class EventCommandEventArgs : System.EventArgs
{
internal EventCommandEventArgs() { }
public System.Collections.Generic.IDictionary<string, string> Arguments { get { throw null; } }
public System.Diagnostics.Tracing.EventCommand Command { get { throw null; } }
public bool DisableEvent(int eventId) { throw null; }
public bool EnableEvent(int eventId) { throw null; }
}
public class EventCounter {
public EventCounter(string name, EventSource eventSource) { }
public void WriteMetric(float value) { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(12), Inherited = false)]
public partial class EventDataAttribute : System.Attribute
{
public EventDataAttribute() { }
public string Name { get { throw null; } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(128))]
public partial class EventFieldAttribute : System.Attribute
{
public EventFieldAttribute() { }
public System.Diagnostics.Tracing.EventFieldFormat Format { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventFieldTags Tags { get { throw null; } set { } }
}
public enum EventFieldFormat
{
Boolean = 3,
Default = 0,
Hexadecimal = 4,
HResult = 15,
Json = 12,
String = 2,
Xml = 11,
}
[System.FlagsAttribute]
public enum EventFieldTags
{
None = 0,
}
[System.AttributeUsageAttribute((System.AttributeTargets)(128))]
public partial class EventIgnoreAttribute : System.Attribute
{
public EventIgnoreAttribute() { }
}
[System.FlagsAttribute]
public enum EventKeywords : long
{
All = (long)-1,
AuditFailure = (long)4503599627370496,
AuditSuccess = (long)9007199254740992,
CorrelationHint = (long)4503599627370496,
EventLogClassic = (long)36028797018963968,
None = (long)0,
Sqm = (long)2251799813685248,
WdiContext = (long)562949953421312,
WdiDiagnostic = (long)1125899906842624,
MicrosoftTelemetry = (long)562949953421312,
}
public enum EventLevel
{
Critical = 1,
Error = 2,
Informational = 4,
LogAlways = 0,
Verbose = 5,
Warning = 3,
}
public abstract partial class EventListener : System.IDisposable
{
#if FEATURE_ETLEVENTS
public event EventHandler<EventSourceCreatedEventArgs> EventSourceCreated;
public event EventHandler<EventWrittenEventArgs> EventWritten;
#endif
protected EventListener() { }
public void DisableEvents(System.Diagnostics.Tracing.EventSource eventSource) { }
public virtual void Dispose() { }
public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level) { }
public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword) { }
public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword, System.Collections.Generic.IDictionary<string, string> arguments) { }
protected static int EventSourceIndex(System.Diagnostics.Tracing.EventSource eventSource) { throw null; }
protected internal virtual void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource) { }
#if FEATURE_ETLEVENTS
protected internal virtual void OnEventWritten(System.Diagnostics.Tracing.EventWrittenEventArgs eventData) { }
#else
protected internal abstract void OnEventWritten(System.Diagnostics.Tracing.EventWrittenEventArgs eventData);
#endif
}
[System.FlagsAttribute]
public enum EventManifestOptions
{
AllCultures = 2,
AllowEventSourceOverride = 8,
None = 0,
OnlyIfNeededForRegistration = 4,
Strict = 1,
}
public enum EventOpcode
{
DataCollectionStart = 3,
DataCollectionStop = 4,
Extension = 5,
Info = 0,
Receive = 240,
Reply = 6,
Resume = 7,
Send = 9,
Start = 1,
Stop = 2,
Suspend = 8,
}
public partial class EventSource : System.IDisposable
{
protected EventSource() { }
protected EventSource(bool throwOnEventWriteErrors) { }
protected EventSource(System.Diagnostics.Tracing.EventSourceSettings settings) { }
protected EventSource(System.Diagnostics.Tracing.EventSourceSettings settings, params string[] traits) { }
public EventSource(string eventSourceName) { }
public EventSource(string eventSourceName, System.Diagnostics.Tracing.EventSourceSettings config) { }
public EventSource(string eventSourceName, System.Diagnostics.Tracing.EventSourceSettings config, params string[] traits) { }
public System.Exception ConstructionException { get { throw null; } }
public static System.Guid CurrentThreadActivityId {[System.Security.SecuritySafeCriticalAttribute]get { throw null; } }
public System.Guid Guid { get { throw null; } }
public string Name { get { throw null; } }
public System.Diagnostics.Tracing.EventSourceSettings Settings { get { throw null; } }
public event EventHandler<EventCommandEventArgs> EventCommandExecuted { add {} remove {} }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
~EventSource() { }
public static string GenerateManifest(System.Type eventSourceType, string assemblyPathToIncludeInManifest) { throw null; }
public static string GenerateManifest(System.Type eventSourceType, string assemblyPathToIncludeInManifest, System.Diagnostics.Tracing.EventManifestOptions flags) { throw null; }
public static System.Guid GetGuid(System.Type eventSourceType) { throw null; }
public static string GetName(System.Type eventSourceType) { throw null; }
public static System.Collections.Generic.IEnumerable<System.Diagnostics.Tracing.EventSource> GetSources() { throw null; }
public string GetTrait(string key) { throw null; }
public bool IsEnabled() { throw null; }
public bool IsEnabled(System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords keywords) { throw null; }
public bool IsEnabled(System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords keywords, System.Diagnostics.Tracing.EventChannel channel) { throw null; }
protected virtual void OnEventCommand(System.Diagnostics.Tracing.EventCommandEventArgs command) { }
public static void SendCommand(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventCommand command, System.Collections.Generic.IDictionary<string, string> commandArguments) { }
public static void SetCurrentThreadActivityId(System.Guid activityId) { }
public static void SetCurrentThreadActivityId(System.Guid activityId, out System.Guid oldActivityThatWillContinue) { throw null; }
public override string ToString() { throw null; }
public void Write(string eventName) { }
public void Write(string eventName, System.Diagnostics.Tracing.EventSourceOptions options) { }
public void Write<T>(string eventName, T data) { }
public void Write<T>(string eventName, System.Diagnostics.Tracing.EventSourceOptions options, T data) { }
public void Write<T>(string eventName, ref System.Diagnostics.Tracing.EventSourceOptions options, ref T data) { }
public void Write<T>(string eventName, ref System.Diagnostics.Tracing.EventSourceOptions options, ref System.Guid activityId, ref System.Guid relatedActivityId, ref T data) { }
protected void WriteEvent(int eventId) { }
protected void WriteEvent(int eventId, byte[] arg1) { }
protected void WriteEvent(int eventId, int arg1) { }
protected void WriteEvent(int eventId, int arg1, int arg2) { }
protected void WriteEvent(int eventId, int arg1, int arg2, int arg3) { }
protected void WriteEvent(int eventId, int arg1, string arg2) { }
protected void WriteEvent(int eventId, long arg1) { }
protected void WriteEvent(int eventId, long arg1, byte[] arg2) { }
protected void WriteEvent(int eventId, long arg1, long arg2) { }
protected void WriteEvent(int eventId, long arg1, long arg2, long arg3) { }
protected void WriteEvent(int eventId, long arg1, string arg2) { }
protected void WriteEvent(int eventId, params object[] args) { }
protected void WriteEvent(int eventId, string arg1) { }
protected void WriteEvent(int eventId, string arg1, int arg2) { }
protected void WriteEvent(int eventId, string arg1, int arg2, int arg3) { }
protected void WriteEvent(int eventId, string arg1, long arg2) { }
protected void WriteEvent(int eventId, string arg1, string arg2) { }
protected void WriteEvent(int eventId, string arg1, string arg2, string arg3) { }
[System.CLSCompliantAttribute(false)]
[System.Security.SecurityCriticalAttribute]
protected unsafe void WriteEventCore(int eventId, int eventDataCount, System.Diagnostics.Tracing.EventSource.EventData* data) { }
protected void WriteEventWithRelatedActivityId(int eventId, System.Guid relatedActivityId, params object[] args) { }
[System.CLSCompliantAttribute(false)]
[System.Security.SecurityCriticalAttribute]
protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, System.Guid* relatedActivityId, int eventDataCount, System.Diagnostics.Tracing.EventSource.EventData* data) { }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
protected internal partial struct EventData
{
public System.IntPtr DataPointer { get { throw null; } set { } }
public int Size { get { throw null; } set { } }
}
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4))]
public sealed partial class EventSourceAttribute : System.Attribute
{
public EventSourceAttribute() { }
public string Guid { get { throw null; } set { } }
public string LocalizationResources { get { throw null; } set { } }
public string Name { get { throw null; } set { } }
}
#if FEATURE_ETLEVENTS
public class EventSourceCreatedEventArgs : EventArgs
{
public EventSourceCreatedEventArgs() { }
public EventSource EventSource { get; }
}
#endif
public partial class EventSourceException : System.Exception
{
public EventSourceException() { }
public EventSourceException(string message) { }
public EventSourceException(string message, System.Exception innerException) { }
protected EventSourceException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct EventSourceOptions
{
public System.Diagnostics.Tracing.EventActivityOptions ActivityOptions { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } set { } }
}
[System.FlagsAttribute]
public enum EventSourceSettings
{
Default = 0,
EtwManifestEventFormat = 4,
EtwSelfDescribingEventFormat = 8,
ThrowOnEventWriteErrors = 1,
}
[System.FlagsAttribute]
public enum EventTags
{
None = 0,
}
public enum EventTask
{
None = 0,
}
public partial class EventWrittenEventArgs : System.EventArgs
{
internal EventWrittenEventArgs() { }
public System.Guid ActivityId {[System.Security.SecurityCriticalAttribute]get { throw null; } }
public System.Diagnostics.Tracing.EventChannel Channel { get { throw null; } }
public int EventId { get { throw null; } }
public string EventName { get { throw null; } }
public System.Diagnostics.Tracing.EventSource EventSource { get { throw null; } }
public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } }
public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } }
public string Message { get { throw null; } }
public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<object> Payload { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<string> PayloadNames { get { throw null; } }
public System.Guid RelatedActivityId {[System.Security.SecurityCriticalAttribute]get { throw null; } }
public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } }
public System.Diagnostics.Tracing.EventTask Task { get { throw null; } }
public byte Version { get { throw null; } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(64))]
public sealed partial class NonEventAttribute : System.Attribute
{
public NonEventAttribute() { }
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.ObjectExtensions;
using osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Online.Spectator;
using osu.Game.Replays;
using osu.Game.Rulesets;
using osu.Game.Scoring;
namespace osu.Game.Screens.Spectate
{
/// <summary>
/// A <see cref="OsuScreen"/> which spectates one or more users.
/// </summary>
public abstract class SpectatorScreen : OsuScreen
{
protected IReadOnlyList<int> Users => users;
private readonly List<int> users = new List<int>();
[Resolved]
private BeatmapManager beatmaps { get; set; }
[Resolved]
private RulesetStore rulesets { get; set; }
[Resolved]
private SpectatorClient spectatorClient { get; set; }
[Resolved]
private UserLookupCache userLookupCache { get; set; }
private readonly IBindableDictionary<int, SpectatorState> playingUserStates = new BindableDictionary<int, SpectatorState>();
private readonly Dictionary<int, APIUser> userMap = new Dictionary<int, APIUser>();
private readonly Dictionary<int, SpectatorGameplayState> gameplayStates = new Dictionary<int, SpectatorGameplayState>();
/// <summary>
/// Creates a new <see cref="SpectatorScreen"/>.
/// </summary>
/// <param name="users">The users to spectate.</param>
protected SpectatorScreen(params int[] users)
{
this.users.AddRange(users);
}
protected override void LoadComplete()
{
base.LoadComplete();
userLookupCache.GetUsersAsync(users.ToArray()).ContinueWith(users => Schedule(() =>
{
foreach (var u in users.Result)
{
if (u == null)
continue;
userMap[u.Id] = u;
}
playingUserStates.BindTo(spectatorClient.PlayingUserStates);
playingUserStates.BindCollectionChanged(onPlayingUserStatesChanged, true);
beatmaps.ItemUpdated += beatmapUpdated;
foreach ((int id, var _) in userMap)
spectatorClient.WatchUser(id);
}));
}
private void beatmapUpdated(BeatmapSetInfo beatmapSet)
{
foreach ((int userId, _) in userMap)
{
if (!playingUserStates.TryGetValue(userId, out var userState))
continue;
if (beatmapSet.Beatmaps.Any(b => b.OnlineID == userState.BeatmapID))
updateGameplayState(userId);
}
}
private void onPlayingUserStatesChanged(object sender, NotifyDictionaryChangedEventArgs<int, SpectatorState> e)
{
switch (e.Action)
{
case NotifyDictionaryChangedAction.Add:
foreach ((int userId, var state) in e.NewItems.AsNonNull())
onUserStateAdded(userId, state);
break;
case NotifyDictionaryChangedAction.Remove:
foreach ((int userId, var _) in e.OldItems.AsNonNull())
onUserStateRemoved(userId);
break;
case NotifyDictionaryChangedAction.Replace:
foreach ((int userId, var _) in e.OldItems.AsNonNull())
onUserStateRemoved(userId);
foreach ((int userId, var state) in e.NewItems.AsNonNull())
onUserStateAdded(userId, state);
break;
}
}
private void onUserStateAdded(int userId, SpectatorState state)
{
if (state.RulesetID == null || state.BeatmapID == null)
return;
if (!userMap.ContainsKey(userId))
return;
Schedule(() => OnUserStateChanged(userId, state));
updateGameplayState(userId);
}
private void onUserStateRemoved(int userId)
{
if (!userMap.ContainsKey(userId))
return;
if (!gameplayStates.TryGetValue(userId, out var gameplayState))
return;
gameplayState.Score.Replay.HasReceivedAllFrames = true;
gameplayStates.Remove(userId);
Schedule(() => EndGameplay(userId));
}
private void updateGameplayState(int userId)
{
Debug.Assert(userMap.ContainsKey(userId));
var user = userMap[userId];
var spectatorState = playingUserStates[userId];
var resolvedRuleset = rulesets.AvailableRulesets.FirstOrDefault(r => r.OnlineID == spectatorState.RulesetID)?.CreateInstance();
if (resolvedRuleset == null)
return;
var resolvedBeatmap = beatmaps.QueryBeatmap(b => b.OnlineID == spectatorState.BeatmapID);
if (resolvedBeatmap == null)
return;
var score = new Score
{
ScoreInfo = new ScoreInfo
{
BeatmapInfo = resolvedBeatmap,
User = user,
Mods = spectatorState.Mods.Select(m => m.ToMod(resolvedRuleset)).ToArray(),
Ruleset = resolvedRuleset.RulesetInfo,
},
Replay = new Replay { HasReceivedAllFrames = false },
};
var gameplayState = new SpectatorGameplayState(score, resolvedRuleset, beatmaps.GetWorkingBeatmap(resolvedBeatmap));
gameplayStates[userId] = gameplayState;
Schedule(() => StartGameplay(userId, gameplayState));
}
/// <summary>
/// Invoked when a spectated user's state has changed.
/// </summary>
/// <param name="userId">The user whose state has changed.</param>
/// <param name="spectatorState">The new state.</param>
protected abstract void OnUserStateChanged(int userId, [NotNull] SpectatorState spectatorState);
/// <summary>
/// Starts gameplay for a user.
/// </summary>
/// <param name="userId">The user to start gameplay for.</param>
/// <param name="spectatorGameplayState">The gameplay state.</param>
protected abstract void StartGameplay(int userId, [NotNull] SpectatorGameplayState spectatorGameplayState);
/// <summary>
/// Ends gameplay for a user.
/// </summary>
/// <param name="userId">The user to end gameplay for.</param>
protected abstract void EndGameplay(int userId);
/// <summary>
/// Stops spectating a user.
/// </summary>
/// <param name="userId">The user to stop spectating.</param>
protected void RemoveUser(int userId)
{
onUserStateRemoved(userId);
users.Remove(userId);
userMap.Remove(userId);
spectatorClient.StopWatchingUser(userId);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (spectatorClient != null)
{
foreach ((int userId, var _) in userMap)
spectatorClient.StopWatchingUser(userId);
}
if (beatmaps != null)
beatmaps.ItemUpdated -= beatmapUpdated;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// gRPC server. A single server can serve an arbitrary number of services and can listen on more than one port.
/// </summary>
public class Server
{
const int DefaultRequestCallTokensPerCq = 2000;
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Server>();
readonly AtomicCounter activeCallCounter = new AtomicCounter();
readonly ServiceDefinitionCollection serviceDefinitions;
readonly ServerPortCollection ports;
readonly GrpcEnvironment environment;
readonly List<ChannelOption> options;
readonly ServerSafeHandle handle;
readonly object myLock = new object();
readonly List<ServerServiceDefinition> serviceDefinitionsList = new List<ServerServiceDefinition>();
readonly List<ServerPort> serverPortList = new List<ServerPort>();
readonly Dictionary<string, IServerCallHandler> callHandlers = new Dictionary<string, IServerCallHandler>();
readonly TaskCompletionSource<object> shutdownTcs = new TaskCompletionSource<object>();
bool startRequested;
volatile bool shutdownRequested;
int requestCallTokensPerCq = DefaultRequestCallTokensPerCq;
/// <summary>
/// Creates a new server.
/// </summary>
public Server() : this(null)
{
}
/// <summary>
/// Creates a new server.
/// </summary>
/// <param name="options">Channel options.</param>
public Server(IEnumerable<ChannelOption> options)
{
this.serviceDefinitions = new ServiceDefinitionCollection(this);
this.ports = new ServerPortCollection(this);
this.environment = GrpcEnvironment.AddRef();
this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>();
using (var channelArgs = ChannelOptions.CreateChannelArgs(this.options))
{
this.handle = ServerSafeHandle.NewServer(channelArgs);
}
foreach (var cq in environment.CompletionQueues)
{
this.handle.RegisterCompletionQueue(cq);
}
GrpcEnvironment.RegisterServer(this);
}
/// <summary>
/// Services that will be exported by the server once started. Register a service with this
/// server by adding its definition to this collection.
/// </summary>
public ServiceDefinitionCollection Services
{
get
{
return serviceDefinitions;
}
}
/// <summary>
/// Ports on which the server will listen once started. Register a port with this
/// server by adding its definition to this collection.
/// </summary>
public ServerPortCollection Ports
{
get
{
return ports;
}
}
/// <summary>
/// To allow awaiting termination of the server.
/// </summary>
public Task ShutdownTask
{
get
{
return shutdownTcs.Task;
}
}
/// <summary>
/// Experimental API. Might anytime change without prior notice.
/// Number or calls requested via grpc_server_request_call at any given time for each completion queue.
/// </summary>
public int RequestCallTokensPerCompletionQueue
{
get
{
return requestCallTokensPerCq;
}
set
{
lock (myLock)
{
GrpcPreconditions.CheckState(!startRequested);
GrpcPreconditions.CheckArgument(value > 0);
requestCallTokensPerCq = value;
}
}
}
/// <summary>
/// Starts the server.
/// Throws <c>IOException</c> if not successful.
/// </summary>
public void Start()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!startRequested);
GrpcPreconditions.CheckState(!shutdownRequested);
startRequested = true;
CheckPortsBoundSuccessfully();
handle.Start();
for (int i = 0; i < requestCallTokensPerCq; i++)
{
foreach (var cq in environment.CompletionQueues)
{
AllowOneRpc(cq);
}
}
}
}
/// <summary>
/// Requests server shutdown and when there are no more calls being serviced,
/// cleans up used resources. The returned task finishes when shutdown procedure
/// is complete.
/// </summary>
/// <remarks>
/// It is strongly recommended to shutdown all previously created servers before exiting from the process.
/// </remarks>
public Task ShutdownAsync()
{
return ShutdownInternalAsync(false);
}
/// <summary>
/// Requests server shutdown while cancelling all the in-progress calls.
/// The returned task finishes when shutdown procedure is complete.
/// </summary>
/// <remarks>
/// It is strongly recommended to shutdown all previously created servers before exiting from the process.
/// </remarks>
public Task KillAsync()
{
return ShutdownInternalAsync(true);
}
internal void AddCallReference(object call)
{
activeCallCounter.Increment();
bool success = false;
handle.DangerousAddRef(ref success);
GrpcPreconditions.CheckState(success);
}
internal void RemoveCallReference(object call)
{
handle.DangerousRelease();
activeCallCounter.Decrement();
}
/// <summary>
/// Shuts down the server.
/// </summary>
private async Task ShutdownInternalAsync(bool kill)
{
lock (myLock)
{
GrpcPreconditions.CheckState(!shutdownRequested);
shutdownRequested = true;
}
GrpcEnvironment.UnregisterServer(this);
var cq = environment.CompletionQueues.First(); // any cq will do
handle.ShutdownAndNotify(HandleServerShutdown, cq);
if (kill)
{
handle.CancelAllCalls();
}
await ShutdownCompleteOrEnvironmentDeadAsync().ConfigureAwait(false);
DisposeHandle();
await GrpcEnvironment.ReleaseAsync().ConfigureAwait(false);
}
/// <summary>
/// In case the environment's threadpool becomes dead, the shutdown completion will
/// never be delivered, but we need to release the environment's handle anyway.
/// </summary>
private async Task ShutdownCompleteOrEnvironmentDeadAsync()
{
while (true)
{
var task = await Task.WhenAny(shutdownTcs.Task, Task.Delay(20)).ConfigureAwait(false);
if (shutdownTcs.Task == task)
{
return;
}
if (!environment.IsAlive)
{
return;
}
}
}
/// <summary>
/// Adds a service definition.
/// </summary>
private void AddServiceDefinitionInternal(ServerServiceDefinition serviceDefinition)
{
lock (myLock)
{
GrpcPreconditions.CheckState(!startRequested);
foreach (var entry in serviceDefinition.CallHandlers)
{
callHandlers.Add(entry.Key, entry.Value);
}
serviceDefinitionsList.Add(serviceDefinition);
}
}
/// <summary>
/// Adds a listening port.
/// </summary>
private int AddPortInternal(ServerPort serverPort)
{
lock (myLock)
{
GrpcPreconditions.CheckNotNull(serverPort.Credentials, "serverPort");
GrpcPreconditions.CheckState(!startRequested);
var address = string.Format("{0}:{1}", serverPort.Host, serverPort.Port);
int boundPort;
using (var nativeCredentials = serverPort.Credentials.ToNativeCredentials())
{
if (nativeCredentials != null)
{
boundPort = handle.AddSecurePort(address, nativeCredentials);
}
else
{
boundPort = handle.AddInsecurePort(address);
}
}
var newServerPort = new ServerPort(serverPort, boundPort);
this.serverPortList.Add(newServerPort);
return boundPort;
}
}
/// <summary>
/// Allows one new RPC call to be received by server.
/// </summary>
private void AllowOneRpc(CompletionQueueSafeHandle cq)
{
if (!shutdownRequested)
{
// TODO(jtattermusch): avoid unnecessary delegate allocation
handle.RequestCall((success, ctx) => HandleNewServerRpc(success, ctx, cq), cq);
}
}
/// <summary>
/// Checks that all ports have been bound successfully.
/// </summary>
private void CheckPortsBoundSuccessfully()
{
lock (myLock)
{
var unboundPort = ports.FirstOrDefault(port => port.BoundPort == 0);
if (unboundPort != null)
{
throw new IOException(
string.Format("Failed to bind port \"{0}:{1}\"", unboundPort.Host, unboundPort.Port));
}
}
}
private void DisposeHandle()
{
var activeCallCount = activeCallCounter.Count;
if (activeCallCount > 0)
{
Logger.Warning("Server shutdown has finished but there are still {0} active calls for that server.", activeCallCount);
}
handle.Dispose();
}
/// <summary>
/// Selects corresponding handler for given call and handles the call.
/// </summary>
private async Task HandleCallAsync(ServerRpcNew newRpc, CompletionQueueSafeHandle cq, Action continuation)
{
try
{
IServerCallHandler callHandler;
if (!callHandlers.TryGetValue(newRpc.Method, out callHandler))
{
callHandler = UnimplementedMethodCallHandler.Instance;
}
await callHandler.HandleCall(newRpc, cq).ConfigureAwait(false);
}
catch (Exception e)
{
Logger.Warning(e, "Exception while handling RPC.");
}
finally
{
continuation();
}
}
/// <summary>
/// Handles the native callback.
/// </summary>
private void HandleNewServerRpc(bool success, RequestCallContextSafeHandle ctx, CompletionQueueSafeHandle cq)
{
bool nextRpcRequested = false;
if (success)
{
var newRpc = ctx.GetServerRpcNew(this);
// after server shutdown, the callback returns with null call
if (!newRpc.Call.IsInvalid)
{
nextRpcRequested = true;
// Start asynchronous handler for the call.
// Don't await, the continuations will run on gRPC thread pool once triggered
// by cq.Next().
#pragma warning disable 4014
HandleCallAsync(newRpc, cq, () => AllowOneRpc(cq));
#pragma warning restore 4014
}
}
if (!nextRpcRequested)
{
AllowOneRpc(cq);
}
}
/// <summary>
/// Handles native callback.
/// </summary>
private void HandleServerShutdown(bool success, BatchContextSafeHandle ctx, object state)
{
shutdownTcs.SetResult(null);
}
/// <summary>
/// Collection of service definitions.
/// </summary>
public class ServiceDefinitionCollection : IEnumerable<ServerServiceDefinition>
{
readonly Server server;
internal ServiceDefinitionCollection(Server server)
{
this.server = server;
}
/// <summary>
/// Adds a service definition to the server. This is how you register
/// handlers for a service with the server. Only call this before Start().
/// </summary>
public void Add(ServerServiceDefinition serviceDefinition)
{
server.AddServiceDefinitionInternal(serviceDefinition);
}
/// <summary>
/// Gets enumerator for this collection.
/// </summary>
public IEnumerator<ServerServiceDefinition> GetEnumerator()
{
return server.serviceDefinitionsList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return server.serviceDefinitionsList.GetEnumerator();
}
}
/// <summary>
/// Collection of server ports.
/// </summary>
public class ServerPortCollection : IEnumerable<ServerPort>
{
readonly Server server;
internal ServerPortCollection(Server server)
{
this.server = server;
}
/// <summary>
/// Adds a new port on which server should listen.
/// Only call this before Start().
/// <returns>The port on which server will be listening.</returns>
/// </summary>
public int Add(ServerPort serverPort)
{
return server.AddPortInternal(serverPort);
}
/// <summary>
/// Adds a new port on which server should listen.
/// <returns>The port on which server will be listening.</returns>
/// </summary>
/// <param name="host">the host</param>
/// <param name="port">the port. If zero, an unused port is chosen automatically.</param>
/// <param name="credentials">credentials to use to secure this port.</param>
public int Add(string host, int port, ServerCredentials credentials)
{
return Add(new ServerPort(host, port, credentials));
}
/// <summary>
/// Gets enumerator for this collection.
/// </summary>
public IEnumerator<ServerPort> GetEnumerator()
{
return server.serverPortList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return server.serverPortList.GetEnumerator();
}
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Adxstudio.Xrm.Data;
using Adxstudio.Xrm.Web.UI.WebForms;
using Adxstudio.Xrm.Resources;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
namespace Adxstudio.Xrm.Commerce
{
/// <summary>
/// Implementation of <see cref="IPurchaseDataAdapter"/> that gets purchase information from a Web Form
/// step target, step metadata, and session.
/// </summary>
public class WebFormPurchaseDataAdapter : PurchaseDataAdapter
{
/// <summary>
/// Purchase-related attributes on adx_webformmetadata.
/// </summary>
protected static class PurchaseMetadataAttributes
{
/// <summary>
/// Value of the "Purchase" type in the adx_type option set.
/// </summary>
public const int Type = 100000003;
/// <summary>
/// If provided, this value will dicate the Name of any quotes generated by the given web form step.
/// </summary>
public const string QuoteName = "adx_purchasequotename";
/// <summary>
/// When set to true, forces the purchase system behave as though the purchase requires shipping.
/// </summary>
public const string RequriesShipping = "adx_purchaserequiresshipping";
/// <summary>
/// If provided, this class will use this relationship name to traverse from the web form step target
/// entity to the Purchase Entity. If this value is not provided, it is assumed that the step target
/// is the Purchase Entity.
/// </summary>
public const string TargetEntityRelationship = "adx_purchasetargetentityrelationship";
/// <summary>
/// If provided, specifies a relationship to traverse for Product entities, which will be treated
/// as optional line items for the purchase.
/// </summary>
public const string OptionalProductsRelationship = "adx_purchaseoptionalproductsrelationship";
/// <summary>
/// If provided, specifies a relationship to traverse for Product entities, which will be treated
/// as required (non-optional) line items for the purchase.
/// </summary>
public const string RequiredProductsRelationship = "adx_purchaserequiredproductsrelationship";
/// <summary>
/// If provided, specifies a relationship to traverse for an entity that will act as a Line Item
/// for the purchase. This can be any entity (custom or otherwise), as the following line item
/// schema mapping properties will dictate how to retrieve line item info from this entity.
/// </summary>
public const string LineItemRelationship = "adx_purchaselineitemrelationship";
/// <summary>
/// Attribute logical name for Line Item Entity description. For each line item, this value will
/// be mapped to quotedetail.description.
/// </summary>
public const string LineItemDescription = "adx_purchaselineitemdescriptionattribute";
/// <summary>
/// Attribute logical name for Line Item Entity special instructions. An aggregation of these
/// values for all linte items will be mapped to quote.adx_specialinstructions.
/// </summary>
public const string LineItemInstructions = "adx_purchaselineiteminstructionsattribute";
/// <summary>
/// Attribute logical name for Line Item Entity order. For each line item, this value will be
/// mapped to quotedetail.lineitemnumber.
/// </summary>
public const string LineItemOrder = "adx_purchaselineitemorderattribute";
/// <summary>
/// Attribute logical name for Line Item Entity associated Product. If a valid Product is not
/// associated with a given line item, that line item will be filtered from the purchase. This
/// value is required for the line item mapping system to function.
/// </summary>
public const string LineItemProduct = "adx_purchaselineitemproductattribute";
/// <summary>
/// Attribute logical name for Line Item Entity quantity. For each line item, this value will
/// be mapped to quotedetail.quantity. If this schema mapping is not specified, the quantity
/// for each required line item will be assumed to be 1, while the initial quantity for all
/// optional line items will be 0.
/// </summary>
public const string LineItemQuantity = "adx_purchaselineitemquantityattribute";
/// <summary>
/// Attribute logical name for Line Item Entity "is required" boolean attribute. If this schema
/// mapping is not specified, all line items will be assumed to be required.
/// </summary>
public const string LineItemRequired = "adx_purchaselineitemrequiredattribute";
/// <summary>
/// Attribute logical name for Line Item Entity associated Unit of Measure. If this schema mapping
/// is not specified, a default unit of measure will be determined for the item, from the portal
/// price list.
/// </summary>
public const string LineItemUom = "adx_purchaselineitemuomattribute";
/// <summary>
/// Specifies whether or not to create an invoice when purchase is completed.
/// </summary>
public const string CreateInvoiceOnPayment = "adx_purchasecreateinvoiceonpayment";
/// <summary>
/// Specifies whether or not to set the order as fulfilled when purchase is completed.
/// </summary>
public const string FulfillOrderOnPayment = "adx_purchasefulfillorderonpayment";
/// <summary>
/// Relationship on target entity to invoice that is (optionally) create when the purchase is
/// completed.
/// </summary>
public const string TargetEntityInvoiceRelationship = "adx_purchasetargetentityinvoicerelationship";
/// <summary>
/// Relationship on target entity to order that is created when purchase is completed.
/// </summary>
public const string TargetEntityOrderRelationship = "adx_purchasetargetentityorderrelationship";
}
public WebFormPurchaseDataAdapter(EntityReference target, string targetPrimaryKeyLogicalName, EntityReference webForm, IEnumerable<Entity> webFormMetadata, SessionHistory webFormSession, IDataAdapterDependencies dependencies)
: base(dependencies)
{
if (target == null) throw new ArgumentNullException("target");
if (targetPrimaryKeyLogicalName == null) throw new ArgumentNullException("targetPrimaryKeyLogicalName");
if (webForm == null) throw new ArgumentNullException("webForm");
if (webFormMetadata == null) throw new ArgumentNullException("webFormMetadata");
Target = target;
TargetPrimaryKeyLogicalName = targetPrimaryKeyLogicalName;
WebForm = webForm;
WebFormMetadata = webFormMetadata.ToArray();
WebFormSession = webFormSession;
}
protected EntityReference Target { get; private set; }
protected string TargetPrimaryKeyLogicalName { get; private set; }
protected EntityReference WebForm { get; private set; }
protected IEnumerable<Entity> WebFormMetadata { get; private set; }
protected SessionHistory WebFormSession { get; private set; }
public override void CompletePurchase(bool fulfillOrder = false, bool createInvoice = false)
{
TraceMethodInfo("Start");
var purchaseMetadata = WebFormMetadata.FirstOrDefault(IsPurchaseMetadata);
if (purchaseMetadata == null)
{
return;
}
if (WebFormSession.QuoteId == Guid.Empty)
{
throw new InvalidOperationException("Failed to retrieve purchase quote from web form session.");
}
fulfillOrder = purchaseMetadata.GetAttributeValue<bool?>(PurchaseMetadataAttributes.FulfillOrderOnPayment).GetValueOrDefault(fulfillOrder);
createInvoice = purchaseMetadata.GetAttributeValue<bool?>(PurchaseMetadataAttributes.CreateInvoiceOnPayment).GetValueOrDefault(createInvoice);
var orderRelationshipName = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.TargetEntityOrderRelationship);
var setOrderRelationship = !string.IsNullOrEmpty(orderRelationshipName);
var invoiceRelationshipName = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.TargetEntityInvoiceRelationship);
var setInvoiceRelationship = !string.IsNullOrEmpty(invoiceRelationshipName);
if (!(fulfillOrder || setOrderRelationship || createInvoice || setInvoiceRelationship))
{
// Nothing to do, return.
return;
}
var quote = new EntityReference("quote", WebFormSession.QuoteId);
var serviceContext = Dependencies.GetServiceContext();
var order = serviceContext.CreateQuery("salesorder")
.Where(e => e.GetAttributeValue<EntityReference>("quoteid") == quote)
.OrderByDescending(e => e.GetAttributeValue<DateTime>("createdon"))
.FirstOrDefault();
if (order == null)
{
TraceMethodError("Unable to retrieve associated order for quote {0}.", quote.Id);
return;
}
var serviceContextForUpdates = Dependencies.GetServiceContextForWrite();
var hasUpdates = false;
var targetUpdate = new Entity(Target.LogicalName)
{
Id = Target.Id
};
serviceContextForUpdates.Attach(targetUpdate);
if (setOrderRelationship)
{
var orderUpdate = new Entity(order.LogicalName)
{
Id = order.Id
};
serviceContextForUpdates.Attach(orderUpdate);
serviceContextForUpdates.AddLink(orderUpdate, new Relationship(orderRelationshipName), targetUpdate);
hasUpdates = true;
}
if (createInvoice)
{
var convertOrderRequest = new ConvertSalesOrderToInvoiceRequest()
{
ColumnSet = new ColumnSet("invoiceid"),
SalesOrderId = order.Id
};
var convertOrderResponse = (ConvertSalesOrderToInvoiceResponse)serviceContext.Execute(convertOrderRequest);
var invoice = convertOrderResponse.Entity;
var setStateRequest = new SetStateRequest()
{
EntityMoniker = invoice.ToEntityReference(),
State = new OptionSetValue(2),
Status = new OptionSetValue(100001)
};
var setStateResponse = (SetStateResponse)serviceContext.Execute(setStateRequest);
invoice = serviceContext.CreateQuery("invoice").Where(i => i.GetAttributeValue<Guid>("invoiceid") == convertOrderResponse.Entity.Id).FirstOrDefault();
if (setInvoiceRelationship && convertOrderResponse != null && convertOrderResponse.Entity != null)
{
var invoiceUpdate = new Entity(invoice.LogicalName)
{
Id = convertOrderResponse.Entity.Id
};
serviceContextForUpdates.Attach(invoiceUpdate);
serviceContextForUpdates.AddLink(invoiceUpdate, new Relationship(invoiceRelationshipName), targetUpdate);
hasUpdates = true;
}
}
if (hasUpdates)
{
serviceContextForUpdates.SaveChanges();
}
if (fulfillOrder)
{
var orderClose = new Entity("orderclose");
orderClose["salesorderid"] = order.ToEntityReference();
serviceContext.Execute(new FulfillSalesOrderRequest
{
OrderClose = orderClose,
Status = new OptionSetValue(-1),
});
}
}
public override IPurchasable Select(IEnumerable<IPurchasableItemOptions> options)
{
if (options == null) throw new ArgumentNullException("options");
TraceMethodInfo("Start");
var purchaseMetadata = WebFormMetadata.FirstOrDefault(IsPurchaseMetadata) ?? new Entity();
if (WebFormSession.QuoteId != Guid.Empty)
{
TraceMethodInfo("Web form session has quote {0}. Creating purchasable from quote.", WebFormSession.QuoteId);
return SelectFromQuote(new EntityReference("quote", WebFormSession.QuoteId), purchaseMetadata, options);
}
var serviceContext = Dependencies.GetServiceContext();
Entity purchaseEntity;
if (!TryGetPurchaseEntity(serviceContext, purchaseMetadata, out purchaseEntity))
{
TraceMethodError("Failed to retrieve purchase entity from web form step. Returning null.");
return null;
}
TraceMethodInfo("Found purchase entity: {0}:{1}", purchaseEntity.LogicalName, purchaseEntity.Id);
var requiredProductsRelationship = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.RequiredProductsRelationship);
if (!string.IsNullOrEmpty(requiredProductsRelationship))
{
return SelectFromProductsDirectlyRelatedToPurchaseEntity(serviceContext, purchaseEntity, requiredProductsRelationship, purchaseMetadata, options);
}
var lineItemRelationship = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemRelationship);
if (!string.IsNullOrEmpty(lineItemRelationship))
{
return SelectFromLineItemEntities(serviceContext, purchaseEntity, lineItemRelationship, purchaseMetadata, options);
}
if (purchaseEntity.LogicalName == "product")
{
return SelectFromProduct(purchaseEntity, purchaseMetadata, options);
}
if (purchaseEntity.LogicalName == "quote")
{
return SelectFromQuote(purchaseEntity.ToEntityReference(), purchaseMetadata, options);
}
TraceMethodError("Failed to retrieve purchasable using web form step metadata. Returning null.");
return null;
}
public override void UpdateShipToAddress(IPurchaseAddress address)
{
if (address == null) throw new ArgumentNullException("address");
if (WebFormSession.QuoteId == Guid.Empty)
{
throw new InvalidOperationException("Unable to determine quote from web form session.");
}
var quoteDataAdapter = new QuotePurchaseDataAdapter(new EntityReference("quote", WebFormSession.QuoteId), Dependencies);
quoteDataAdapter.UpdateShipToAddress(address);
}
protected virtual EntityReference CreateQuote(IEnumerable<LineItem> lineItems, Entity purchaseMetadata, EntityReference purchaseEntity)
{
return QuoteFunctions.CreateQuote(lineItems, purchaseEntity, Dependencies.GetServiceContext(), Dependencies.GetServiceContextForWrite(),
Dependencies.GetPortalUser(), Dependencies.GetPriceList(), WebFormSession.AnonymousIdentification, Target, purchaseMetadata);
}
protected virtual EntityReference GetQuoteCustomer(Entity purchaseMetadata)
{
var user = Dependencies.GetPortalUser();
if (user != null)
{
return user;
}
var visitorId = WebFormSession.AnonymousIdentification;
if (string.IsNullOrEmpty(visitorId))
{
throw new InvalidOperationException("Unable to create anonymous quote customer record.");
}
return QuoteFunctions.GetQuoteCustomer(Dependencies.GetServiceContext(), null, visitorId);
}
protected virtual string GetQuoteName(Entity purchaseMetadata)
{
var serviceContext = Dependencies.GetServiceContextForWrite();
var webForm = serviceContext.CreateQuery("adx_webform")
.Where(e => e.GetAttributeValue<Guid>("adx_webformid") == WebForm.Id)
.Select(e => new { Name = e.GetAttributeValue<string>("adx_name") })
.ToArray()
.FirstOrDefault();
return QuoteFunctions.GetQuoteName(serviceContext, purchaseMetadata, webForm.Name);
}
protected virtual IEnumerable<LineItem> GetValidLineItems(IEnumerable<LineItem> lineItems)
{
return lineItems.Where(e =>
{
var state = e.Product.GetAttributeValue<OptionSetValue>("statecode");
return state != null && state.Value == 0;
});
}
protected virtual IPurchasable SelectFromLineItemEntities(OrganizationServiceContext serviceContext, Entity purchaseEntity, string lineItemRelationship,
Entity purchaseMetadata, IEnumerable<IPurchasableItemOptions> options)
{
TraceMethodInfo("Start: purchaseEntity={0}:{1}, lineItemRelationship={2}", purchaseEntity.LogicalName, purchaseEntity.Id, lineItemRelationship);
var productAttribute = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemProduct);
if (string.IsNullOrEmpty(productAttribute))
{
TraceMethodError("Unable to retrieve products from line item entities. {0} not defined in web form step metadata. Returning null.", PurchaseMetadataAttributes.LineItemProduct);
return null;
}
var descriptionAttribute = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemDescription);
var instructionsAttribute = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemInstructions);
var orderAttribute = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemOrder);
var requiredAttribute = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemRequired);
var quantityAttribute = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemQuantity);
var uomAttribute = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.LineItemUom);
var entities = purchaseEntity.GetRelatedEntities(serviceContext, lineItemRelationship).ToArray();
if (!entities.Any())
{
TraceMethodError("Unable to retrieve any line item entities. Returning null.");
return null;
}
var productIds = entities
.Select(e => e.GetAttributeValue<EntityReference>(productAttribute))
.Where(product => product != null)
.Select(product => product.Id)
.ToArray();
if (!productIds.Any())
{
TraceMethodError("Unable to retrieve any products from line item entities. Returning null.");
return null;
}
var products = serviceContext.CreateQuery("product")
.WhereIn(e => e.GetAttributeValue<Guid>("productid"), productIds)
.ToDictionary(e => e.Id, e => e);
var lineItems = entities
.Select(e => LineItem.GetLineItemFromLineItemEntity(e, productAttribute, descriptionAttribute, instructionsAttribute, orderAttribute, requiredAttribute, quantityAttribute, uomAttribute, products))
.Where(lineItem => lineItem != null);
var quote = QuoteFunctions.CreateQuote(lineItems, purchaseEntity.ToEntityReference(), serviceContext, Dependencies.GetServiceContextForWrite(), Dependencies.GetPortalUser(),
Dependencies.GetPriceList(), WebFormSession.AnonymousIdentification, Target, purchaseMetadata);
var purchasable = quote == null
? null
: SelectFromQuote(quote, purchaseMetadata, options);
TraceMethodInfo("End");
return purchasable;
}
protected virtual IPurchasable SelectFromProduct(Entity product, Entity purchaseMetadata, IEnumerable<IPurchasableItemOptions> options)
{
TraceMethodInfo("Start: product={0}:{1}", product.LogicalName, product.Id);
var lineItems = new[]
{
new LineItem(product, null, 1, false, product.GetAttributeValue<string>("description"), null, 1)
};
var quote = QuoteFunctions.CreateQuote(lineItems, Target, Dependencies.GetServiceContext(), Dependencies.GetServiceContextForWrite(), Dependencies.GetPortalUser(),
Dependencies.GetPriceList(), WebFormSession.AnonymousIdentification, Target, purchaseMetadata);
var purchasable = quote == null
? null
: SelectFromQuote(quote, purchaseMetadata, options);
TraceMethodInfo("End");
return purchasable;
}
protected virtual IPurchasable SelectFromProductsDirectlyRelatedToPurchaseEntity(OrganizationServiceContext serviceContext, Entity purchaseEntity, string requiredProductsRelationship, Entity purchaseMetadata, IEnumerable<IPurchasableItemOptions> options)
{
TraceMethodInfo("Start: purchaseEntity={0}:{1}, requiredProductsRelationship={2}", purchaseEntity.LogicalName, purchaseEntity.Id, requiredProductsRelationship);
var requiredProducts = purchaseEntity.GetRelatedEntities(serviceContext, requiredProductsRelationship);
var optionalProductsRelationship = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.OptionalProductsRelationship);
var optionalProducts = string.IsNullOrEmpty(optionalProductsRelationship)
? Enumerable.Empty<Entity>()
: purchaseEntity.GetRelatedEntities(serviceContext, optionalProductsRelationship);
var requiredLineItems = requiredProducts.Select(e => new LineItem(e, null, 1, false, e.GetAttributeValue<string>("description"), null, 1));
var optionalLineItems = optionalProducts.Select(e => new LineItem(e, null, 0, true, e.GetAttributeValue<string>("description"), null, 2));
var lineItems = requiredLineItems.Union(optionalLineItems);
var quote = QuoteFunctions.CreateQuote(lineItems, purchaseEntity.ToEntityReference(), serviceContext, Dependencies.GetServiceContextForWrite(), Dependencies.GetPortalUser(),
Dependencies.GetPriceList(), WebFormSession.AnonymousIdentification, Target, purchaseMetadata);
var purchasable = quote == null
? null
: SelectFromQuote(quote, purchaseMetadata, options);
TraceMethodInfo("End");
return purchasable;
}
protected virtual IPurchasable SelectFromQuote(EntityReference quote, Entity purchaseMetadata = null, IEnumerable<IPurchasableItemOptions> options = null)
{
var requiresShipping = purchaseMetadata != null && purchaseMetadata.GetAttributeValue<bool?>(PurchaseMetadataAttributes.RequriesShipping).GetValueOrDefault(false);
var quoteDataAdapter = new QuotePurchaseDataAdapter(quote, Dependencies, requiresShipping);
return quoteDataAdapter.Select(options ?? Enumerable.Empty<IPurchasableItemOptions>());
}
private bool TryGetPurchaseEntity(OrganizationServiceContext serviceContext, Entity purchaseMetadata, out Entity purchaseEntity)
{
purchaseEntity = null;
var targetEntity = serviceContext.CreateQuery(Target.LogicalName)
.FirstOrDefault(e => e.GetAttributeValue<Guid>(TargetPrimaryKeyLogicalName) == Target.Id);
if (targetEntity == null)
{
return false;
}
var purchaseEntityRelationship = purchaseMetadata.GetAttributeValue<string>(PurchaseMetadataAttributes.TargetEntityRelationship);
if (string.IsNullOrEmpty(purchaseEntityRelationship))
{
purchaseEntity = targetEntity;
return true;
}
purchaseEntity = targetEntity.GetRelatedEntity(serviceContext, purchaseEntityRelationship);
return purchaseEntity != null;
}
private static bool IsPurchaseMetadata(Entity webFormMetadata)
{
if (webFormMetadata == null)
{
return false;
}
var optionSetValue = webFormMetadata.GetAttributeValue<OptionSetValue>("adx_type");
return optionSetValue != null && optionSetValue.Value == PurchaseMetadataAttributes.Type;
}
}
}
| |
/*
* 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 copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenSim.Framework;
using OMV = OpenMetaverse;
namespace OpenSim.Region.PhysicsModule.BulletS
{
public class BSPrimLinkable : BSPrimDisplaced
{
// The purpose of this subclass is to add linkset functionality to the prim. This overrides
// operations necessary for keeping the linkset created and, additionally, this
// calls the linkset implementation for its creation and management.
#pragma warning disable 414
private static readonly string LogHeader = "[BULLETS PRIMLINKABLE]";
#pragma warning restore 414
// This adds the overrides for link() and delink() so the prim is linkable.
public BSLinkset Linkset { get; set; }
// The index of this child prim.
public int LinksetChildIndex { get; set; }
public BSLinkset.LinksetImplementation LinksetType { get; set; }
public BSPrimLinkable(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size,
OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical)
: base(localID, primName, parent_scene, pos, size, rotation, pbs, pisPhysical)
{
// Default linkset implementation for this prim
LinksetType = (BSLinkset.LinksetImplementation)BSParam.LinksetImplementation;
Linkset = BSLinkset.Factory(PhysScene, this);
Linkset.Refresh(this);
}
public override void Destroy()
{
Linkset = Linkset.RemoveMeFromLinkset(this, false /* inTaintTime */);
base.Destroy();
}
public override void link(OpenSim.Region.PhysicsModules.SharedBase.PhysicsActor obj)
{
BSPrimLinkable parent = obj as BSPrimLinkable;
if (parent != null)
{
BSPhysObject parentBefore = Linkset.LinksetRoot; // DEBUG
int childrenBefore = Linkset.NumberOfChildren; // DEBUG
Linkset = parent.Linkset.AddMeToLinkset(this);
DetailLog("{0},BSPrimLinkable.link,call,parentBefore={1}, childrenBefore=={2}, parentAfter={3}, childrenAfter={4}",
LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren);
}
return;
}
public override void delink()
{
// TODO: decide if this parent checking needs to happen at taint time
// Race condition here: if link() and delink() in same simulation tick, the delink will not happen
BSPhysObject parentBefore = Linkset.LinksetRoot; // DEBUG
int childrenBefore = Linkset.NumberOfChildren; // DEBUG
Linkset = Linkset.RemoveMeFromLinkset(this, false /* inTaintTime*/);
DetailLog("{0},BSPrimLinkable.delink,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}, ",
LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren);
return;
}
// When simulator changes position, this might be moving a child of the linkset.
public override OMV.Vector3 Position
{
get { return base.Position; }
set
{
base.Position = value;
PhysScene.TaintedObject(LocalID, "BSPrimLinkable.setPosition", delegate()
{
Linkset.UpdateProperties(UpdatedProperties.Position, this);
});
}
}
// When simulator changes orientation, this might be moving a child of the linkset.
public override OMV.Quaternion Orientation
{
get { return base.Orientation; }
set
{
base.Orientation = value;
PhysScene.TaintedObject(LocalID, "BSPrimLinkable.setOrientation", delegate()
{
Linkset.UpdateProperties(UpdatedProperties.Orientation, this);
});
}
}
public override float TotalMass
{
get { return Linkset.LinksetMass; }
}
public override OMV.Vector3 CenterOfMass
{
get { return Linkset.CenterOfMass; }
}
public override OMV.Vector3 GeometricCenter
{
get { return Linkset.GeometricCenter; }
}
// Refresh the linkset structure and parameters when the prim's physical parameters are changed.
public override void UpdatePhysicalParameters()
{
base.UpdatePhysicalParameters();
// Recompute any linkset parameters.
// When going from non-physical to physical, this re-enables the constraints that
// had been automatically disabled when the mass was set to zero.
// For compound based linksets, this enables and disables interactions of the children.
if (Linkset != null) // null can happen during initialization
Linkset.Refresh(this);
}
// When the prim is made dynamic or static, the linkset needs to change.
protected override void MakeDynamic(bool makeStatic)
{
base.MakeDynamic(makeStatic);
if (Linkset != null) // null can happen during initialization
{
if (makeStatic)
Linkset.MakeStatic(this);
else
Linkset.MakeDynamic(this);
}
}
// Body is being taken apart. Remove physical dependencies and schedule a rebuild.
protected override void RemoveDependencies()
{
Linkset.RemoveDependencies(this);
base.RemoveDependencies();
}
// Called after a simulation step for the changes in physical object properties.
// Do any filtering/modification needed for linksets.
public override void UpdateProperties(EntityProperties entprop)
{
if (Linkset.IsRoot(this) || Linkset.ShouldReportPropertyUpdates(this))
{
// Properties are only updated for the roots of a linkset.
// TODO: this will have to change when linksets are articulated.
base.UpdateProperties(entprop);
}
/*
else
{
// For debugging, report the movement of children
DetailLog("{0},BSPrim.UpdateProperties,child,pos={1},orient={2},vel={3},accel={4},rotVel={5}",
LocalID, entprop.Position, entprop.Rotation, entprop.Velocity,
entprop.Acceleration, entprop.RotationalVelocity);
}
*/
// The linkset might like to know about changing locations
Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this);
}
// Called after a simulation step to post a collision with this object.
// This returns 'true' if the collision has been queued and the SendCollisions call must
// be made at the end of the simulation step.
public override bool Collide(BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth)
{
bool ret = false;
// Ask the linkset if it wants to handle the collision
if (!Linkset.HandleCollide(this, collidee, contactPoint, contactNormal, pentrationDepth))
{
// The linkset didn't handle it so pass the collision through normal processing
ret = base.Collide(collidee, contactPoint, contactNormal, pentrationDepth);
}
return ret;
}
// A linkset reports any collision on any part of the linkset.
public long SomeCollisionSimulationStep = 0;
public override bool HasSomeCollision
{
get
{
return (SomeCollisionSimulationStep == PhysScene.SimulationStep) || base.IsColliding;
}
set
{
if (value)
SomeCollisionSimulationStep = PhysScene.SimulationStep;
else
SomeCollisionSimulationStep = 0;
base.HasSomeCollision = value;
}
}
// Convert the existing linkset of this prim into a new type.
public bool ConvertLinkset(BSLinkset.LinksetImplementation newType)
{
bool ret = false;
if (LinksetType != newType)
{
DetailLog("{0},BSPrimLinkable.ConvertLinkset,oldT={1},newT={2}", LocalID, LinksetType, newType);
// Set the implementation type first so the call to BSLinkset.Factory gets the new type.
this.LinksetType = newType;
BSLinkset oldLinkset = this.Linkset;
BSLinkset newLinkset = BSLinkset.Factory(PhysScene, this);
this.Linkset = newLinkset;
// Pick up any physical dependencies this linkset might have in the physics engine.
oldLinkset.RemoveDependencies(this);
// Create a list of the children (mainly because can't interate through a list that's changing)
List<BSPrimLinkable> children = new List<BSPrimLinkable>();
oldLinkset.ForEachMember((child) =>
{
if (!oldLinkset.IsRoot(child))
children.Add(child);
return false; // 'false' says to continue to next member
});
// Remove the children from the old linkset and add to the new (will be a new instance from the factory)
foreach (BSPrimLinkable child in children)
{
oldLinkset.RemoveMeFromLinkset(child, true /*inTaintTime*/);
}
foreach (BSPrimLinkable child in children)
{
newLinkset.AddMeToLinkset(child);
child.Linkset = newLinkset;
}
// Force the shape and linkset to get reconstructed
newLinkset.Refresh(this);
this.ForceBodyShapeRebuild(true /* inTaintTime */);
}
return ret;
}
#region Extension
public override object Extension(string pFunct, params object[] pParams)
{
DetailLog("{0} BSPrimLinkable.Extension,op={1},nParam={2}", LocalID, pFunct, pParams.Length);
object ret = null;
switch (pFunct)
{
// physGetLinksetType();
// pParams = [ BSPhysObject root, null ]
case ExtendedPhysics.PhysFunctGetLinksetType:
{
ret = (object)LinksetType;
DetailLog("{0},BSPrimLinkable.Extension.physGetLinksetType,type={1}", LocalID, ret);
break;
}
// physSetLinksetType(type);
// pParams = [ BSPhysObject root, null, integer type ]
case ExtendedPhysics.PhysFunctSetLinksetType:
{
if (pParams.Length > 2)
{
BSLinkset.LinksetImplementation linksetType = (BSLinkset.LinksetImplementation)pParams[2];
if (Linkset.IsRoot(this))
{
PhysScene.TaintedObject(LocalID, "BSPrim.PhysFunctSetLinksetType", delegate()
{
// Cause the linkset type to change
DetailLog("{0},BSPrimLinkable.Extension.physSetLinksetType, oldType={1},newType={2}",
LocalID, Linkset.LinksetImpl, linksetType);
ConvertLinkset(linksetType);
});
}
ret = (object)(int)linksetType;
}
break;
}
// physChangeLinkType(linknum, typeCode);
// pParams = [ BSPhysObject root, BSPhysObject child, integer linkType ]
case ExtendedPhysics.PhysFunctChangeLinkType:
{
ret = Linkset.Extension(pFunct, pParams);
break;
}
// physGetLinkType(linknum);
// pParams = [ BSPhysObject root, BSPhysObject child ]
case ExtendedPhysics.PhysFunctGetLinkType:
{
ret = Linkset.Extension(pFunct, pParams);
break;
}
// physChangeLinkParams(linknum, [code, value, code, value, ...]);
// pParams = [ BSPhysObject root, BSPhysObject child, object[] [ string op, object opParam, string op, object opParam, ... ] ]
case ExtendedPhysics.PhysFunctChangeLinkParams:
{
ret = Linkset.Extension(pFunct, pParams);
break;
}
default:
ret = base.Extension(pFunct, pParams);
break;
}
return ret;
}
#endregion // Extension
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Daniel Kollmann
// 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 Daniel Kollmann 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 Brainiac.Design
{
partial class ExportDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExportDialog));
this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
this.exportButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.textBox = new System.Windows.Forms.TextBox();
this.browseButton = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.formatComboBox = new System.Windows.Forms.ComboBox();
this.treeView = new System.Windows.Forms.TreeView();
this.imageList = new System.Windows.Forms.ImageList(this.components);
this.groupsCheckBox = new System.Windows.Forms.CheckBox();
this.SuspendLayout();
//
// folderBrowserDialog
//
this.folderBrowserDialog.Description = "Select Export Folder";
this.folderBrowserDialog.RootFolder = System.Environment.SpecialFolder.MyComputer;
//
// exportButton
//
this.exportButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.exportButton.Location = new System.Drawing.Point(12, 433);
this.exportButton.Name = "exportButton";
this.exportButton.Size = new System.Drawing.Size(140, 21);
this.exportButton.TabIndex = 5;
this.exportButton.Text = "Export Selected";
this.exportButton.UseVisualStyleBackColor = true;
//
// cancelButton
//
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Location = new System.Drawing.Point(212, 433);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(140, 21);
this.cancelButton.TabIndex = 6;
this.cancelButton.Text = "Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
//
// textBox
//
this.textBox.Location = new System.Drawing.Point(12, 376);
this.textBox.Name = "textBox";
this.textBox.Size = new System.Drawing.Size(256, 21);
this.textBox.TabIndex = 2;
//
// browseButton
//
this.browseButton.Location = new System.Drawing.Point(274, 373);
this.browseButton.Name = "browseButton";
this.browseButton.Size = new System.Drawing.Size(75, 21);
this.browseButton.TabIndex = 3;
this.browseButton.Text = "Browse";
this.browseButton.UseVisualStyleBackColor = true;
this.browseButton.Click += new System.EventHandler(this.browseButton_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(9, 361);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(82, 13);
this.label1.TabIndex = 5;
this.label1.Text = "Export Folder";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(12, 8);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(122, 13);
this.label2.TabIndex = 6;
this.label2.Text = "Behaviors To Export";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(9, 318);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(85, 13);
this.label3.TabIndex = 7;
this.label3.Text = "Export Format";
//
// formatComboBox
//
this.formatComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.formatComboBox.FormattingEnabled = true;
this.formatComboBox.Location = new System.Drawing.Point(12, 332);
this.formatComboBox.Name = "formatComboBox";
this.formatComboBox.Size = new System.Drawing.Size(337, 20);
this.formatComboBox.TabIndex = 1;
//
// treeView
//
this.treeView.CheckBoxes = true;
this.treeView.ImageIndex = 0;
this.treeView.ImageList = this.imageList;
this.treeView.Location = new System.Drawing.Point(15, 23);
this.treeView.Name = "treeView";
this.treeView.SelectedImageIndex = 0;
this.treeView.Size = new System.Drawing.Size(337, 282);
this.treeView.TabIndex = 0;
this.treeView.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(this.treeView_AfterCheck);
//
// imageList
//
this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream")));
this.imageList.TransparentColor = System.Drawing.Color.Magenta;
this.imageList.Images.SetKeyName(0, "VSFolder_closed.bmp");
this.imageList.Images.SetKeyName(1, "DocumentHS.png");
//
// groupsCheckBox
//
this.groupsCheckBox.AutoSize = true;
this.groupsCheckBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.groupsCheckBox.Location = new System.Drawing.Point(15, 408);
this.groupsCheckBox.Name = "groupsCheckBox";
this.groupsCheckBox.Size = new System.Drawing.Size(145, 17);
this.groupsCheckBox.TabIndex = 4;
this.groupsCheckBox.Text = "Do not export groups";
this.groupsCheckBox.UseVisualStyleBackColor = true;
//
// ExportDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(364, 465);
this.ControlBox = false;
this.Controls.Add(this.groupsCheckBox);
this.Controls.Add(this.treeView);
this.Controls.Add(this.formatComboBox);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.browseButton);
this.Controls.Add(this.textBox);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.exportButton);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "ExportDialog";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Export Behaviors";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog;
private System.Windows.Forms.Button exportButton;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button browseButton;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
internal System.Windows.Forms.ComboBox formatComboBox;
internal System.Windows.Forms.TextBox textBox;
internal System.Windows.Forms.TreeView treeView;
private System.Windows.Forms.ImageList imageList;
internal System.Windows.Forms.CheckBox groupsCheckBox;
}
}
| |
using System;
using System.Diagnostics;
using Htc.Vita.Core.Log;
using Htc.Vita.Core.Runtime;
using Htc.Vita.Core.Util;
using Xunit;
namespace Htc.Vita.Core.Tests
{
public static class RegistryTest
{
#pragma warning disable CS0618
[Fact]
public static void Default_0_GetStringValue32_UnderHKCR()
{
if (!Platform.IsWindows)
{
return;
}
Assert.NotNull(Registry.GetStringValue32(Registry.Hive.ClassesRoot, ".bat", null));
Assert.NotNull(Registry.GetStringValue32(Registry.Hive.ClassesRoot, "CLSID\\{0000002F-0000-0000-C000-000000000046}\\InprocServer32", "ThreadingModel"));
Assert.Null(Registry.GetStringValue32(Registry.Hive.ClassesRoot, "textfile\\shell\\open", null));
Assert.Null(Registry.GetStringValue32(Registry.Hive.ClassesRoot, "CLSID\\{0000002F-0000-0000-C000-000000000046}\\InprocServer32", "ThreadingModel2"));
}
[Fact]
public static void Default_0_GetStringValue32_UnderHKLM()
{
if (!Platform.IsWindows)
{
return;
}
Assert.NotNull(Registry.GetStringValue32(Registry.Hive.LocalMachine, "SOFTWARE\\Classes\\CLSID\\{0000002F-0000-0000-C000-000000000046}", null));
Assert.NotNull(Registry.GetStringValue32(Registry.Hive.LocalMachine, "SOFTWARE\\Classes\\CLSID\\{0000002F-0000-0000-C000-000000000046}\\InprocServer32", "ThreadingModel"));
Assert.Null(Registry.GetStringValue32(Registry.Hive.LocalMachine, "SOFTWARE\\Classes\\CLSID\\{0000002F-0000-0000-C000-000000000046}\\InprocServer32", "ThreadingModel2"));
}
[Fact]
public static void Default_0_GetStringValue64_UnderHKCR()
{
if (!Platform.IsWindows)
{
return;
}
Assert.NotNull(Registry.GetStringValue64(Registry.Hive.ClassesRoot, ".bat", null));
Assert.NotNull(Registry.GetStringValue64(Registry.Hive.ClassesRoot, "CLSID\\{0000002F-0000-0000-C000-000000000046}\\InprocServer32", "ThreadingModel"));
Assert.Null(Registry.GetStringValue64(Registry.Hive.ClassesRoot, "textfile\\shell\\open", null));
Assert.Null(Registry.GetStringValue64(Registry.Hive.ClassesRoot, "CLSID\\{0000002F-0000-0000-C000-000000000046}\\InprocServer32", "ThreadingModel2"));
}
[Fact]
public static void Default_0_GetStringValue64_UnderHKLM()
{
if (!Platform.IsWindows)
{
return;
}
Assert.NotNull(Registry.GetStringValue64(Registry.Hive.LocalMachine, "SOFTWARE\\Classes\\CLSID\\{0000002F-0000-0000-C000-000000000046}", null));
Assert.NotNull(Registry.GetStringValue64(Registry.Hive.LocalMachine, "SOFTWARE\\Classes\\CLSID\\{0000002F-0000-0000-C000-000000000046}\\InprocServer32", "ThreadingModel"));
Assert.Null(Registry.GetStringValue64(Registry.Hive.LocalMachine, "SOFTWARE\\Classes", null));
Assert.Null(Registry.GetStringValue64(Registry.Hive.LocalMachine, "SOFTWARE\\Classes\\CLSID\\{0000002F-0000-0000-C000-000000000046}\\InprocServer32", "ThreadingModel2"));
}
[Fact]
public static void Default_0_GetStringValue_UnderHKCR()
{
if (!Platform.IsWindows)
{
return;
}
Assert.NotNull(Registry.GetStringValue(Registry.Hive.ClassesRoot, ".bat", null));
Assert.NotNull(Registry.GetStringValue(Registry.Hive.ClassesRoot, "CLSID\\{0000002F-0000-0000-C000-000000000046}\\InprocServer32", "ThreadingModel"));
Assert.Null(Registry.GetStringValue(Registry.Hive.ClassesRoot, "textfile\\shell\\open", null));
Assert.Null(Registry.GetStringValue(Registry.Hive.ClassesRoot, "CLSID\\{0000002F-0000-0000-C000-000000000046}\\InprocServer32", "ThreadingModel2"));
}
[Fact]
public static void Default_0_GetStringValue_UnderHKLM()
{
if (!Platform.IsWindows)
{
return;
}
Assert.NotNull(Registry.GetStringValue(Registry.Hive.LocalMachine, "SOFTWARE\\Classes\\CLSID\\{0000002F-0000-0000-C000-000000000046}", null));
Assert.NotNull(Registry.GetStringValue(Registry.Hive.LocalMachine, "SOFTWARE\\Classes\\CLSID\\{0000002F-0000-0000-C000-000000000046}\\InprocServer32", "ThreadingModel"));
Assert.Null(Registry.GetStringValue(Registry.Hive.LocalMachine, "SOFTWARE\\Classes\\CLSID\\{0000002F-0000-0000-C000-000000000046}\\InprocServer32", "ThreadingModel2"));
}
[Fact]
public static void Default_1_SetStringValue_UnderHKCU()
{
if (!Platform.IsWindows)
{
return;
}
var valueName = Guid.NewGuid().ToString();
var valueData = valueName;
Registry.SetStringValue(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", valueName, valueData);
Assert.Equal(valueData, Registry.GetStringValue(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", valueName));
}
[Fact]
public static void Default_1_SetStringValue_UnderHKLM()
{
if (!Platform.IsWindows)
{
return;
}
if (!ProcessManager.IsElevatedProcess(Process.GetCurrentProcess()))
{
Logger.GetInstance(typeof(RegistryTest)).Warn("This API should be invoked by elevated user process");
return;
}
var valueName = Guid.NewGuid().ToString();
var valueData = valueName;
Registry.SetStringValue(Registry.Hive.LocalMachine, "SOFTWARE\\HTC\\Test", valueName, valueData);
Assert.Equal(valueData, Registry.GetStringValue(Registry.Hive.LocalMachine, "SOFTWARE\\HTC\\Test", valueName));
}
[Fact]
public static void Default_2_DeleteValue32_UnderHKCU()
{
if (!Platform.IsWindows)
{
return;
}
var valueName = "ffcc27a9-c3bb-463a-8716-3e2e5f2b85a1";
var valueData = valueName;
Registry.SetStringValue(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", valueName, valueData);
Assert.Equal(valueData, Registry.GetStringValue(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", valueName));
Assert.True(Registry.DeleteValue32(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", valueName));
}
[Fact]
public static void Default_2_DeleteValue64_UnderHKCU()
{
if (!Platform.IsWindows)
{
return;
}
var valueName = "083c3747-6834-4ee7-b9af-e66eb9925c2a";
var valueData = valueName;
Registry.SetStringValue(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", valueName, valueData);
Assert.Equal(valueData, Registry.GetStringValue(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", valueName));
Assert.True(Registry.DeleteValue64(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", valueName));
}
[Fact]
public static void Default_2_DeleteValue_UnderHKCU()
{
if (!Platform.IsWindows)
{
return;
}
var valueName = "2f937f96-aecd-477d-a204-d9ff67bdd8ba";
var valueData = valueName;
Registry.SetStringValue(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", valueName, valueData);
Assert.Equal(valueData, Registry.GetStringValue(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", valueName));
Assert.True(Registry.DeleteValue(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", valueName));
}
[Fact]
public static void Default_3_DeleteKey32_UnderHKCU()
{
if (!Platform.IsWindows)
{
return;
}
var keyName = "0a9d53eb-36bb-4859-80d0-0816d47580af";
var valueName = "valueName";
var valueData = "valueData";
Registry.SetStringValue(Registry.Hive.CurrentUser, $"SOFTWARE\\HTC\\Test\\{keyName}", valueName, valueData);
Assert.Equal(valueData, Registry.GetStringValue(Registry.Hive.CurrentUser, $"SOFTWARE\\HTC\\Test\\{keyName}", valueName));
Assert.True(Registry.DeleteKey32(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", keyName));
}
[Fact]
public static void Default_3_DeleteKey64_UnderHKCU()
{
if (!Platform.IsWindows)
{
return;
}
var keyName = "20a3c3e3-9feb-4bd8-b451-1e357a6f9d98";
var valueName = "valueName";
var valueData = "valueData";
Registry.SetStringValue(Registry.Hive.CurrentUser, $"SOFTWARE\\HTC\\Test\\{keyName}", valueName, valueData);
Assert.Equal(valueData, Registry.GetStringValue(Registry.Hive.CurrentUser, $"SOFTWARE\\HTC\\Test\\{keyName}", valueName));
Assert.True(Registry.DeleteKey64(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", keyName));
}
[Fact]
public static void Default_3_DeleteKey_UnderHKCU()
{
if (!Platform.IsWindows)
{
return;
}
var keyName = "7a8dd5f9-9347-40b6-8511-3220af3cd429";
var valueName = "valueName";
var valueData = "valueData";
Registry.SetStringValue(Registry.Hive.CurrentUser, $"SOFTWARE\\HTC\\Test\\{keyName}", valueName, valueData);
Assert.Equal(valueData, Registry.GetStringValue(Registry.Hive.CurrentUser, $"SOFTWARE\\HTC\\Test\\{keyName}", valueName));
Assert.True(Registry.DeleteKey(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", keyName));
}
[Fact]
public static void Default_4_GetIntValue32_UnderHKCR()
{
if (!Platform.IsWindows)
{
return;
}
Assert.True(Registry.GetDwordValue32(Registry.Hive.ClassesRoot, "telnet", "EditFlags") != 0);
Assert.True(Registry.GetDwordValue32(Registry.Hive.ClassesRoot, "telnet", "EditFlags1") == 0);
}
[Fact]
public static void Default_4_GetIntValue64_UnderHKCR()
{
if (!Platform.IsWindows)
{
return;
}
Assert.True(Registry.GetDwordValue64(Registry.Hive.ClassesRoot, "telnet", "EditFlags") != 0);
Assert.True(Registry.GetDwordValue64(Registry.Hive.ClassesRoot, "telnet", "EditFlags1") == 0);
}
[Fact]
public static void Default_4_GetIntValue_UnderHKCR()
{
if (!Platform.IsWindows)
{
return;
}
Assert.True(Registry.GetIntValue(Registry.Hive.ClassesRoot, "telnet", "EditFlags") != 0);
Assert.True(Registry.GetIntValue(Registry.Hive.ClassesRoot, "telnet", "EditFlags1") == 0);
}
[Fact]
public static void Default_5_SetDwordValue_UnderHKCU()
{
if (!Platform.IsWindows)
{
return;
}
var valueData = Guid.NewGuid().GetHashCode();
var valueName = $"{valueData}";
Registry.SetDwordValue(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", valueName, valueData);
Assert.Equal(valueData, Registry.GetIntValue(Registry.Hive.CurrentUser, "SOFTWARE\\HTC\\Test", valueName));
}
#pragma warning restore CS0618
}
}
| |
// 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.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.BlogClient.Providers;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.BlogClient.Detection;
using OpenLiveWriter.CoreServices.Diagnostics;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.Localization;
namespace OpenLiveWriter.PostEditor.Configuration.Settings
{
/// <summary>
/// Summary description for EditingPanel.
/// </summary>
public class EditingPanel : WeblogSettingsPanel
{
private System.Windows.Forms.GroupBox groupBoxWeblogStyle;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label labelEditUsingStyle;
private System.Windows.Forms.Button buttonUpdateStyle;
private System.Windows.Forms.Panel panelBrowserParent;
private GroupBox groupBoxRTL;
private Label labelRTL;
private ComboBox comboBoxRTL;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public EditingPanel()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
UpdateStrings();
}
public EditingPanel(TemporaryBlogSettings targetBlogSettings, TemporaryBlogSettings editableBlogSettings)
: base(targetBlogSettings, editableBlogSettings)
{
InitializeComponent();
UpdateStrings();
PanelBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Configuration.Settings.Images.EditingPanelBitmap.png");
labelEditUsingStyle.Text = String.Format(CultureInfo.CurrentCulture, labelEditUsingStyle.Text, ApplicationEnvironment.ProductName);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!DesignMode)
{
DisplayHelper.AutoFitSystemButton(buttonUpdateStyle);
// add some padding to the button, otherwise it looks crowded
buttonUpdateStyle.Width += (int)Math.Ceiling(DisplayHelper.ScaleX(14));
comboBoxRTL.Left = buttonUpdateStyle.Left + 1;
LayoutHelper.FixupGroupBox(groupBoxWeblogStyle);
LayoutHelper.FixupGroupBox(groupBoxRTL);
LayoutHelper.DistributeVertically(8, groupBoxWeblogStyle, groupBoxRTL);
int maxWidth = groupBoxRTL.Width - comboBoxRTL.Left - 8;
DisplayHelper.AutoFitSystemCombo(comboBoxRTL, comboBoxRTL.Width, maxWidth, false);
}
}
private void UpdateStrings()
{
groupBoxWeblogStyle.Text = Res.Get(StringId.EditingStyle);
label1.Text = Res.Get(StringId.EditingText);
labelEditUsingStyle.Text = Res.Get(StringId.EditingUsing);
buttonUpdateStyle.Text = Res.Get(StringId.EditingUpdate);
PanelName = Res.Get(StringId.EditingName);
groupBoxRTL.Text = Res.Get(StringId.EditingRTLName);
labelRTL.Text = Res.Get(StringId.EditingRTLExplanation);
bool? useRTL = TemporaryBlogSettings.HomePageOverrides.Contains(BlogClientOptions.TEMPLATE_IS_RTL)
? (bool?)StringHelper.ToBool(TemporaryBlogSettings.HomePageOverrides[BlogClientOptions.TEMPLATE_IS_RTL].ToString(), false)
: null;
useRTL = TemporaryBlogSettings.OptionOverrides.Contains(BlogClientOptions.TEMPLATE_IS_RTL)
? StringHelper.ToBool(TemporaryBlogSettings.OptionOverrides[BlogClientOptions.TEMPLATE_IS_RTL].ToString(), false)
: useRTL;
// The default setting only comes from the homepage or manifest
comboBoxRTL.Items.Add(String.Format(CultureInfo.CurrentUICulture, Res.Get(StringId.EditingRTLDefault), (useRTL == true ? Res.Get(StringId.EditingRTLYes) : Res.Get(StringId.EditingRTLNo))));
comboBoxRTL.Items.Add(Res.Get(StringId.EditingRTLYes));
comboBoxRTL.Items.Add(Res.Get(StringId.EditingRTLNo));
// Though the value of the combo box can come from homepage/manifest/user options
if (TemporaryBlogSettings.UserOptionOverrides.Contains(BlogClientOptions.TEMPLATE_IS_RTL))
{
// Select the correct option from the combobox
if (StringHelper.ToBool(TemporaryBlogSettings.UserOptionOverrides[BlogClientOptions.TEMPLATE_IS_RTL].ToString(), false))
comboBoxRTL.SelectedIndex = 1;
else
comboBoxRTL.SelectedIndex = 2;
}
else
{
comboBoxRTL.SelectedIndex = 0;
}
}
private void buttonUpdateStyle_Click(object sender, System.EventArgs e)
{
try
{
using (Blog blog = new Blog(TemporaryBlogSettings))
{
if (blog.VerifyCredentials())
{
BlogClientUIContextImpl uiContext = new BlogClientUIContextImpl(FindForm());
Color? backgroundColor;
BlogEditingTemplateFile[] editingTemplates = BlogEditingTemplateDetector.DetectTemplate(
uiContext,
panelBrowserParent,
TemporaryBlogSettings,
!BlogIsAutoUpdatable(blog),
out backgroundColor); // only probe for manifest if blog is not auto-updatable
if (editingTemplates.Length != 0)
{
TemporaryBlogSettings.TemplateFiles = editingTemplates;
if (backgroundColor != null)
TemporaryBlogSettings.UpdatePostBodyBackgroundColor(backgroundColor.Value);
TemporaryBlogSettingsModified = true;
}
}
}
}
catch (Exception ex)
{
UnexpectedErrorMessage.Show(FindForm(), ex, "Unexpected Error Updating Style");
}
}
private bool BlogIsAutoUpdatable(Blog blog)
{
return PostEditorSettings.AllowSettingsAutoUpdate && blog.ClientOptions.SupportsAutoUpdate;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBoxWeblogStyle = new System.Windows.Forms.GroupBox();
this.panelBrowserParent = new System.Windows.Forms.Panel();
this.label1 = new System.Windows.Forms.Label();
this.labelEditUsingStyle = new System.Windows.Forms.Label();
this.buttonUpdateStyle = new System.Windows.Forms.Button();
this.groupBoxRTL = new System.Windows.Forms.GroupBox();
this.comboBoxRTL = new System.Windows.Forms.ComboBox();
this.labelRTL = new System.Windows.Forms.Label();
this.groupBoxWeblogStyle.SuspendLayout();
this.groupBoxRTL.SuspendLayout();
this.SuspendLayout();
//
// groupBoxWeblogStyle
//
this.groupBoxWeblogStyle.Controls.Add(this.panelBrowserParent);
this.groupBoxWeblogStyle.Controls.Add(this.label1);
this.groupBoxWeblogStyle.Controls.Add(this.labelEditUsingStyle);
this.groupBoxWeblogStyle.Controls.Add(this.buttonUpdateStyle);
this.groupBoxWeblogStyle.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.groupBoxWeblogStyle.Location = new System.Drawing.Point(8, 32);
this.groupBoxWeblogStyle.Name = "groupBoxWeblogStyle";
this.groupBoxWeblogStyle.Size = new System.Drawing.Size(352, 152);
this.groupBoxWeblogStyle.TabIndex = 1;
this.groupBoxWeblogStyle.TabStop = false;
this.groupBoxWeblogStyle.Text = "Weblog Style";
//
// panelBrowserParent
//
this.panelBrowserParent.Location = new System.Drawing.Point(232, 110);
this.panelBrowserParent.Name = "panelBrowserParent";
this.panelBrowserParent.Size = new System.Drawing.Size(32, 24);
this.panelBrowserParent.TabIndex = 7;
this.panelBrowserParent.Visible = false;
//
// label1
//
this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label1.Location = new System.Drawing.Point(16, 72);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(320, 32);
this.label1.TabIndex = 5;
this.label1.Text = "If you have changed the visual style of your weblog you can update your local edi" +
"ting template by using the button below.";
//
// labelEditUsingStyle
//
this.labelEditUsingStyle.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelEditUsingStyle.Location = new System.Drawing.Point(16, 21);
this.labelEditUsingStyle.Name = "labelEditUsingStyle";
this.labelEditUsingStyle.Size = new System.Drawing.Size(320, 40);
this.labelEditUsingStyle.TabIndex = 4;
this.labelEditUsingStyle.Text = "{0} enables you to edit using the visual style of your weblog. This enables you t" +
"o see what your posts will look like online while you are editing them.";
//
// buttonUpdateStyle
//
this.buttonUpdateStyle.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonUpdateStyle.Location = new System.Drawing.Point(16, 110);
this.buttonUpdateStyle.Name = "buttonUpdateStyle";
this.buttonUpdateStyle.Size = new System.Drawing.Size(131, 23);
this.buttonUpdateStyle.TabIndex = 6;
this.buttonUpdateStyle.Text = "&Update Style";
this.buttonUpdateStyle.Click += new System.EventHandler(this.buttonUpdateStyle_Click);
//
// groupBoxRTL
//
this.groupBoxRTL.Controls.Add(this.comboBoxRTL);
this.groupBoxRTL.Controls.Add(this.labelRTL);
this.groupBoxRTL.Location = new System.Drawing.Point(8, 191);
this.groupBoxRTL.Name = "groupBoxRTL";
this.groupBoxRTL.Size = new System.Drawing.Size(348, 91);
this.groupBoxRTL.TabIndex = 2;
this.groupBoxRTL.TabStop = false;
this.groupBoxRTL.Text = "Text Direction";
//
// comboBoxRTL
//
this.comboBoxRTL.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxRTL.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.comboBoxRTL.FormattingEnabled = true;
this.comboBoxRTL.Location = new System.Drawing.Point(16, 54);
this.comboBoxRTL.Name = "comboBoxRTL";
this.comboBoxRTL.Size = new System.Drawing.Size(195, 23);
this.comboBoxRTL.TabIndex = 2;
this.comboBoxRTL.SelectedIndexChanged += new System.EventHandler(this.comboBoxRTL_SelectedIndexChanged);
//
// labelRTL
//
this.labelRTL.Location = new System.Drawing.Point(16, 21);
this.labelRTL.Name = "labelRTL";
this.labelRTL.Size = new System.Drawing.Size(320, 40);
this.labelRTL.TabIndex = 0;
this.labelRTL.Text = "Writer detects whether the template for your blog uses right-to-left text.";
//
// EditingPanel
//
this.AccessibleName = "Editing";
this.Controls.Add(this.groupBoxRTL);
this.Controls.Add(this.groupBoxWeblogStyle);
this.Name = "EditingPanel";
this.PanelName = "Editing";
this.Controls.SetChildIndex(this.groupBoxWeblogStyle, 0);
this.Controls.SetChildIndex(this.groupBoxRTL, 0);
this.groupBoxWeblogStyle.ResumeLayout(false);
this.groupBoxRTL.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void comboBoxRTL_SelectedIndexChanged(object sender, EventArgs e)
{
bool? useRTL = null;
// Check to see if it is anything besides default
if (comboBoxRTL.Text == Res.Get(StringId.EditingRTLYes))
useRTL = true;
else if (comboBoxRTL.Text == Res.Get(StringId.EditingRTLNo))
useRTL = false;
// If the setting is default we remove it
if (useRTL != null)
TemporaryBlogSettings.UserOptionOverrides[BlogClientOptions.TEMPLATE_IS_RTL] = useRTL;
else
TemporaryBlogSettings.UserOptionOverrides.Remove(BlogClientOptions.TEMPLATE_IS_RTL);
TemporaryBlogSettingsModified = true;
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Structure;
namespace Revit.SDK.Samples.Reinforcement.CS
{
using GeoElement = Autodesk.Revit.DB.GeometryElement;
using Element = Autodesk.Revit.DB.Element;
/// <summary>
/// The class which give the base geometry operation, it is a static class.
/// </summary>
static class GeomUtil
{
// Private members
const double Precision = 0.00001; //precision when judge whether two doubles are equal
/// <summary>
/// Judge whether the two double data are equal
/// </summary>
/// <param name="d1">The first double data</param>
/// <param name="d2">The second double data</param>
/// <returns>true if two double data is equal, otherwise false</returns>
public static bool IsEqual(double d1, double d2)
{
//get the absolute value;
double diff = Math.Abs(d1 - d2);
return diff < Precision;
}
/// <summary>
/// Judge whether the two Autodesk.Revit.DB.XYZ point are equal
/// </summary>
/// <param name="first">The first Autodesk.Revit.DB.XYZ point</param>
/// <param name="second">The second Autodesk.Revit.DB.XYZ point</param>
/// <returns>true if two Autodesk.Revit.DB.XYZ point is equal, otherwise false</returns>
public static bool IsEqual(Autodesk.Revit.DB.XYZ first, Autodesk.Revit.DB.XYZ second)
{
bool flag = true;
flag = flag && IsEqual(first.X, second.X);
flag = flag && IsEqual(first.Y, second.Y);
flag = flag && IsEqual(first.Z, second.Z);
return flag;
}
/// <param name="face"></param>
/// <param name="line"></param>
/// <returns>return true when line is perpendicular to the face</returns>
/// <summary>
/// Judge whether the line is perpendicular to the face
/// </summary>
/// <param name="face">the face reference</param>
/// <param name="line">the line reference</param>
/// <param name="faceTrans">the transform for the face</param>
/// <param name="lineTrans">the transform for the line</param>
/// <returns>true if line is perpendicular to the face, otherwise false</returns>
public static bool IsVertical(Face face, Line line,
Transform faceTrans, Transform lineTrans)
{
//get points which the face contains
List<XYZ> points = face.Triangulate().Vertices as List<XYZ>;
if (3 > points.Count) // face's point number should be above 2
{
return false;
}
// get three points from the face points
Autodesk.Revit.DB.XYZ first = points[0];
Autodesk.Revit.DB.XYZ second = points[1];
Autodesk.Revit.DB.XYZ third = points[2];
// get start and end point of line
Autodesk.Revit.DB.XYZ lineStart = line.get_EndPoint(0);
Autodesk.Revit.DB.XYZ lineEnd = line.get_EndPoint(1);
// transForm the three points if necessary
if (null != faceTrans)
{
first = TransformPoint(first, faceTrans);
second = TransformPoint(second, faceTrans);
third = TransformPoint(third, faceTrans);
}
// transform the start and end points if necessary
if (null != lineTrans)
{
lineStart = TransformPoint(lineStart, lineTrans);
lineEnd = TransformPoint(lineEnd, lineTrans);
}
// form two vectors from the face and a vector stand for the line
// Use SubXYZ() method to get the vectors
Autodesk.Revit.DB.XYZ vector1 = SubXYZ(first, second); // first vector of face
Autodesk.Revit.DB.XYZ vector2 = SubXYZ(first, third); // second vector of face
Autodesk.Revit.DB.XYZ vector3 = SubXYZ(lineStart, lineEnd); // line vector
// get two dot products of the face vectors and line vector
double result1 = DotMatrix(vector1, vector3);
double result2 = DotMatrix(vector2, vector3);
// if two dot products are all zero, the line is perpendicular to the face
return (IsEqual(result1, 0) && IsEqual(result2, 0));
}
/// <summary>
/// judge whether the two vectors have the same direction
/// </summary>
/// <param name="firstVec">the first vector</param>
/// <param name="secondVec">the second vector</param>
/// <returns>true if the two vector is in same direction, otherwise false</returns>
public static bool IsSameDirection(Autodesk.Revit.DB.XYZ firstVec, Autodesk.Revit.DB.XYZ secondVec)
{
// get the unit vector for two vectors
Autodesk.Revit.DB.XYZ first = UnitVector(firstVec);
Autodesk.Revit.DB.XYZ second = UnitVector(secondVec);
// if the dot product of two unit vectors is equal to 1, return true
double dot = DotMatrix(first, second);
return (IsEqual(dot, 1));
}
/// <summary>
/// Judge whether the two vectors have the opposite direction
/// </summary>
/// <param name="firstVec">the first vector</param>
/// <param name="secondVec">the second vector</param>
/// <returns>true if the two vector is in opposite direction, otherwise false</returns>
public static bool IsOppositeDirection(Autodesk.Revit.DB.XYZ firstVec, Autodesk.Revit.DB.XYZ secondVec)
{
// get the unit vector for two vectors
Autodesk.Revit.DB.XYZ first = UnitVector(firstVec);
Autodesk.Revit.DB.XYZ second = UnitVector(secondVec);
// if the dot product of two unit vectors is equal to -1, return true
double dot = DotMatrix(first, second);
return (IsEqual(dot, -1));
}
/// <summary>
/// multiplication cross of two Autodesk.Revit.DB.XYZ as Matrix
/// </summary>
/// <param name="p1">The first XYZ</param>
/// <param name="p2">The second XYZ</param>
/// <returns>the normal vector of the face which first and secend vector lie on</returns>
public static Autodesk.Revit.DB.XYZ CrossMatrix(Autodesk.Revit.DB.XYZ p1, Autodesk.Revit.DB.XYZ p2)
{
//get the coordinate of the XYZ
double u1 = p1.X;
double u2 = p1.Y;
double u3 = p1.Z;
double v1 = p2.X;
double v2 = p2.Y;
double v3 = p2.Z;
double x = v3 * u2 - v2 * u3;
double y = v1 * u3 - v3 * u1;
double z = v2 * u1 - v1 * u2;
return new Autodesk.Revit.DB.XYZ (x, y, z);
}
/// <summary>
/// Set the vector into unit length
/// </summary>
/// <param name="vector">the input vector</param>
/// <returns>the vector in unit length</returns>
public static Autodesk.Revit.DB.XYZ UnitVector(Autodesk.Revit.DB.XYZ vector)
{
// calculate the distance from grid origin to the XYZ
double length = GetLength(vector);
// changed the vector into the unit length
double x = vector.X / length;
double y = vector.Y / length;
double z = vector.Z / length;
return new Autodesk.Revit.DB.XYZ (x, y, z);
}
/// <summary>
/// calculate the distance from grid origin to the XYZ(vector length)
/// </summary>
/// <param name="vector">the input vector</param>
/// <returns>the length of the vector</returns>
public static double GetLength(Autodesk.Revit.DB.XYZ vector)
{
double x = vector.X;
double y = vector.Y;
double z = vector.Z;
return Math.Sqrt(x * x + y * y + z * z);
}
/// <summary>
/// Subtraction of two points(or vectors), get a new vector
/// </summary>
/// <param name="p1">the first point(vector)</param>
/// <param name="p2">the second point(vector)</param>
/// <returns>return a new vector from point p2 to p1</returns>
public static Autodesk.Revit.DB.XYZ SubXYZ(Autodesk.Revit.DB.XYZ p1, Autodesk.Revit.DB.XYZ p2)
{
double x = p1.X - p2.X;
double y = p1.Y - p2.Y;
double z = p1.Z - p2.Z;
return new Autodesk.Revit.DB.XYZ (x, y, z);
}
/// <summary>
/// Add of two points(or vectors), get a new point(vector)
/// </summary>
/// <param name="p1">the first point(vector)</param>
/// <param name="p2">the first point(vector)</param>
/// <returns>a new vector(point)</returns>
public static Autodesk.Revit.DB.XYZ AddXYZ(Autodesk.Revit.DB.XYZ p1, Autodesk.Revit.DB.XYZ p2)
{
double x = p1.X + p2.X;
double y = p1.Y + p2.Y;
double z = p1.Z + p2.Z;
return new Autodesk.Revit.DB.XYZ (x, y, z);
}
/// <summary>
/// Multiply a verctor with a number
/// </summary>
/// <param name="vector">a vector</param>
/// <param name="rate">the rate number</param>
/// <returns></returns>
public static Autodesk.Revit.DB.XYZ MultiplyVector(Autodesk.Revit.DB.XYZ vector, double rate)
{
double x = vector.X * rate;
double y = vector.Y * rate;
double z = vector.Z * rate;
return new Autodesk.Revit.DB.XYZ (x, y, z);
}
/// <summary>
/// Transform old coordinate system in the new coordinate system
/// </summary>
/// <param name="point">the Autodesk.Revit.DB.XYZ which need to be transformed</param>
/// <param name="transform">the value of the coordinate system to be transformed</param>
/// <returns>the new Autodesk.Revit.DB.XYZ which has been transformed</returns>
public static Autodesk.Revit.DB.XYZ TransformPoint(Autodesk.Revit.DB.XYZ point, Transform transform)
{
//get the coordinate value in X, Y, Z axis
double x = point.X;
double y = point.Y;
double z = point.Z;
//transform basis of the old coordinate system in the new coordinate system
Autodesk.Revit.DB.XYZ b0 = transform.get_Basis(0);
Autodesk.Revit.DB.XYZ b1 = transform.get_Basis(1);
Autodesk.Revit.DB.XYZ b2 = transform.get_Basis(2);
Autodesk.Revit.DB.XYZ origin = transform.Origin;
//transform the origin of the old coordinate system in the new coordinate system
double xTemp = x * b0.X + y * b1.X + z * b2.X + origin.X;
double yTemp = x * b0.Y + y * b1.Y + z * b2.Y + origin.Y;
double zTemp = x * b0.Z + y * b1.Z + z * b2.Z + origin.Z;
return new Autodesk.Revit.DB.XYZ (xTemp, yTemp, zTemp);
}
/// <summary>
/// Move a point a give offset along a given direction
/// </summary>
/// <param name="point">the point need to move</param>
/// <param name="direction">the direction the point move to</param>
/// <param name="offset">indicate how long to move</param>
/// <returns>the moved point</returns>
public static Autodesk.Revit.DB.XYZ OffsetPoint(Autodesk.Revit.DB.XYZ point, Autodesk.Revit.DB.XYZ direction, double offset)
{
Autodesk.Revit.DB.XYZ directUnit = UnitVector(direction);
Autodesk.Revit.DB.XYZ offsetVect = MultiplyVector(directUnit, offset);
return AddXYZ(point, offsetVect);
}
/// <summary>
/// get the orient of hook accroding to curve direction, rebar normal and hook direction
/// </summary>
/// <param name="curveVec">the curve direction</param>
/// <param name="normal">rebar normal direction</param>
/// <param name="hookVec">the hook direction</param>
/// <returns>the orient of the hook</returns>
public static RebarHookOrientation GetHookOrient(Autodesk.Revit.DB.XYZ curveVec, Autodesk.Revit.DB.XYZ normal, Autodesk.Revit.DB.XYZ hookVec)
{
Autodesk.Revit.DB.XYZ tempVec = normal;
for (int i = 0; i < 4; i++)
{
tempVec = GeomUtil.CrossMatrix(tempVec, curveVec);
if (GeomUtil.IsSameDirection(tempVec, hookVec))
{
if (i == 0)
{
return RebarHookOrientation.Right;
}
else if (i == 2)
{
return RebarHookOrientation.Left;
}
}
}
throw new Exception("Can't find the hook orient according to hook direction.");
}
/// <summary>
/// Judge the vector is in right or left direction
/// </summary>
/// <param name="normal">The unit vector need to be judged its direction</param>
/// <returns>if in right dircetion return true, otherwise return false</returns>
public static bool IsInRightDir(Autodesk.Revit.DB.XYZ normal)
{
double eps = 1.0e-8;
if (Math.Abs(normal.X) <= eps)
{
if (normal.Y > 0) return false;
else return true;
}
if (normal.X > 0) return true;
if (normal.X < 0) return false;
return true;
}
/// <summary>
/// dot product of two Autodesk.Revit.DB.XYZ as Matrix
/// </summary>
/// <param name="p1">The first XYZ</param>
/// <param name="p2">The second XYZ</param>
/// <returns>the cosine value of the angle between vector p1 an p2</returns>
private static double DotMatrix(Autodesk.Revit.DB.XYZ p1, Autodesk.Revit.DB.XYZ p2)
{
//get the coordinate of the Autodesk.Revit.DB.XYZ
double v1 = p1.X;
double v2 = p1.Y;
double v3 = p1.Z;
double u1 = p2.X;
double u2 = p2.Y;
double u3 = p2.Z;
return v1 * u1 + v2 * u2 + v3 * u3;
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Threading;
namespace WebsitePanel.Import.Enterprise
{
/// <summary>
/// Animated Icon.
/// </summary>
[ToolboxItem(true)]
public class ProgressIcon : System.Windows.Forms.UserControl
{
private Thread thread = null;
private int currentFrame = 0;
private int delayInterval = 50;
private int pause = 0;
private int loopCount = 0;
private int currentLoop = 0;
private int firstFrame = 0;
private int lastFrame = 13;
private ImageList images;
private IContainer components;
/// <summary>Initializes a new instance of the <b>AnimatedIcon</b> class.
/// </summary>
public ProgressIcon()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
}
#region Dispose
/// <summary>Clean up any resources being used.</summary>
/// <param name="disposing"><see langword="true"/> to release both managed
/// and unmanaged resources; <see langword="false"/> to release
/// only unmanaged resources.</param>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
if( thread != null )
thread.Abort();
}
base.Dispose( disposing );
}
#endregion
#region Component Designer generated code
/// <summary>Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ProgressIcon));
this.images = new System.Windows.Forms.ImageList(this.components);
this.SuspendLayout();
//
// images
//
this.images.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("images.ImageStream")));
this.images.TransparentColor = System.Drawing.Color.Transparent;
this.images.Images.SetKeyName(0, "ProgressImage00.bmp");
this.images.Images.SetKeyName(1, "ProgressImage01.bmp");
this.images.Images.SetKeyName(2, "ProgressImage02.bmp");
this.images.Images.SetKeyName(3, "ProgressImage03.bmp");
this.images.Images.SetKeyName(4, "ProgressImage04.bmp");
this.images.Images.SetKeyName(5, "ProgressImage05.bmp");
this.images.Images.SetKeyName(6, "ProgressImage06.bmp");
this.images.Images.SetKeyName(7, "ProgressImage07.bmp");
this.images.Images.SetKeyName(8, "ProgressImage08.bmp");
this.images.Images.SetKeyName(9, "ProgressImage09.bmp");
this.images.Images.SetKeyName(10, "ProgressImage10.bmp");
this.images.Images.SetKeyName(11, "ProgressImage11.bmp");
this.images.Images.SetKeyName(12, "ProgressImage12.bmp");
//
// ProgressIcon
//
this.Name = "ProgressIcon";
this.Size = new System.Drawing.Size(30, 30);
this.ResumeLayout(false);
}
#endregion
/// <summary>Starts animation from the beginning.
/// </summary>
public void StartAnimation()
{
StopAnimation();
CheckRange(); // Check the first and the last frames
thread = new Thread( new ThreadStart( threadFunc ) );
thread.IsBackground = true;
thread.Start();
}
/// <summary>Stops animation not changing current frame number.
/// </summary>
public void StopAnimation()
{
if( thread != null )
{
thread.Abort();
thread = null;
}
currentLoop = 0;
}
/// <summary>Displays the specified frame.</summary>
/// <param name="frame">An index of the image stored in the <see cref="ImageList"/>.</param>
public void ShowFrame2(int frame)
{
StopAnimation();
if( frame >= 0 && frame < images.Images.Count )
currentFrame = frame;
else
currentFrame = 0;
Refresh();
}
/// <summary>Occurs when the control is redrawn.</summary>
/// <param name="e">A <see cref="PaintEventArgs"/> that contains
/// the event data.</param>
/// <remarks>The <b>OnPaint</b> method draws current image from
/// the <see cref="ImageList"/> if exists.</remarks>
protected override void OnPaint(PaintEventArgs e)
{
// Draw a crossed rectangle if there is no frame to display
if( images == null ||
currentFrame < 0 ||
currentFrame >= images.Images.Count )
{
if( this.Size.Width == 0 || this.Size.Height == 0 )
return;
Pen pen = new Pen( SystemColors.ControlText );
e.Graphics.DrawRectangle( pen, 0, 0, this.Size.Width-1, this.Size.Height-1 );
e.Graphics.DrawLine( pen, 0, 0, this.Size.Width, this.Size.Height );
e.Graphics.DrawLine( pen, 0, this.Size.Height-1, this.Size.Width-1, 0 );
pen.Dispose();
}
else
{
// Draw the current frame
e.Graphics.DrawImage( images.Images[currentFrame], 0, 0, this.Size.Width, this.Size.Height );
}
}
/// <summary>The method to be invoked when the thread begins executing.
/// </summary>
private void threadFunc()
{
bool wasPause = false;
currentFrame = firstFrame;
while( thread != null && thread.IsAlive )
{
Refresh(); // Redraw the current frame
wasPause = false;
if( images != null )
{
currentFrame++;
if( currentFrame > lastFrame ||
currentFrame >= images.Images.Count )
{
if( pause > 0 ) // Sleep after every loop
{
Thread.Sleep( pause );
wasPause = true;
}
currentFrame = firstFrame;
if( loopCount != 0 ) // 0 is infinitive loop
{
currentLoop++;
}
}
if( loopCount != 0 && currentLoop >= loopCount )
{
StopAnimation(); // The loop is completed
}
}
if( !wasPause ) // That prevents summation (pause + delayInterval)
Thread.Sleep( delayInterval );
}
}
/// <summary>Check if the last frame is no less than the first one.
/// Otherwise, swap them.</summary>
private void CheckRange()
{
if( lastFrame < firstFrame )
{
int tmp = firstFrame;
firstFrame = lastFrame;
lastFrame = tmp;
}
}
}
}
| |
#region License
//
// Copyright (c) 2018, Fluent Migrator 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.
//
#endregion
using System;
using System.Linq;
using FluentMigrator.Expressions;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.VersionTableInfo;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit
{
[TestFixture]
public class VersionLoaderTests
{
[Test]
public void CanLoadCustomVersionTableMetaData()
{
var processor = new Mock<IMigrationProcessor>();
var serviceProvider = ServiceCollectionExtensions.CreateServices()
.WithProcessor(processor)
.AddScoped(_ => ConventionSets.NoSchemaName)
.AddScoped<IMigrationRunnerConventionsAccessor>(sp => new PassThroughMigrationRunnerConventionsAccessor(new MigrationRunnerConventions()))
.AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader("No connection"))
.BuildServiceProvider();
var loader = serviceProvider.GetRequiredService<IVersionLoader>();
var versionTableMetaData = loader.GetVersionTableMetaData();
versionTableMetaData.ShouldBeOfType<TestVersionTableMetaData>();
}
[Test]
public void CanLoadDefaultVersionTableMetaData()
{
var asm = "s".GetType().Assembly;
var processor = new Mock<IMigrationProcessor>();
var serviceProvider = ServiceCollectionExtensions.CreateServices(false)
.WithProcessor(processor)
.AddSingleton<IAssemblySourceItem>(new AssemblySourceItem(asm))
.AddScoped(_ => ConventionSets.NoSchemaName)
.AddScoped<IMigrationRunnerConventionsAccessor>(
_ => new PassThroughMigrationRunnerConventionsAccessor(new MigrationRunnerConventions()))
.AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader("No connection"))
.BuildServiceProvider();
var loader = serviceProvider.GetRequiredService<IVersionLoader>();
var versionTableMetaData = loader.GetVersionTableMetaData();
versionTableMetaData.ShouldBeOfType<DefaultVersionTableMetaData>();
}
[Test]
[Obsolete("Use dependency injection to access 'application state'.")]
public void CanSetupApplicationContext()
{
var applicationContext = "Test context";
var processor = new Mock<IMigrationProcessor>();
var serviceProvider = ServiceCollectionExtensions.CreateServices()
.WithProcessor(processor)
.AddScoped(_ => ConventionSets.NoSchemaName)
.AddScoped<IMigrationRunnerConventionsAccessor>(
_ => new PassThroughMigrationRunnerConventionsAccessor(new MigrationRunnerConventions()))
.AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader("No connection"))
.Configure<RunnerOptions>(opt => opt.ApplicationContext = applicationContext)
.BuildServiceProvider();
var loader = serviceProvider.GetRequiredService<IVersionLoader>();
var versionTableMetaData = loader.GetVersionTableMetaData();
versionTableMetaData.ApplicationContext.ShouldBe(applicationContext);
}
[Test]
public void DeleteVersionShouldExecuteDeleteDataExpression()
{
var processor = new Mock<IMigrationProcessor>();
var serviceProvider = ServiceCollectionExtensions.CreateServices()
.WithProcessor(processor)
.AddScoped(_ => ConventionSets.NoSchemaName)
.AddScoped<IMigrationRunnerConventionsAccessor>(
_ => new PassThroughMigrationRunnerConventionsAccessor(new MigrationRunnerConventions()))
.AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader("No connection"))
.BuildServiceProvider();
var loader = serviceProvider.GetRequiredService<IVersionLoader>();
processor.Setup(p => p.Process(It.Is<DeleteDataExpression>(expression =>
expression.SchemaName == loader.VersionTableMetaData.SchemaName
&& expression.TableName == loader.VersionTableMetaData.TableName
&& expression.Rows.All(
definition =>
definition.All(
pair =>
pair.Key == loader.VersionTableMetaData.ColumnName && pair.Value.Equals(1L))))))
.Verifiable();
loader.DeleteVersion(1);
processor.VerifyAll();
}
[Test]
public void RemoveVersionTableShouldBehaveAsExpected()
{
var processor = new Mock<IMigrationProcessor>();
var serviceProvider = ServiceCollectionExtensions.CreateServices()
.WithProcessor(processor)
.AddScoped(_ => ConventionSets.NoSchemaName)
.AddScoped<IMigrationRunnerConventionsAccessor>(
_ => new PassThroughMigrationRunnerConventionsAccessor(new MigrationRunnerConventions()))
.AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader("No connection"))
.BuildServiceProvider();
var loader = serviceProvider.GetRequiredService<IVersionLoader>();
processor.Setup(p => p.Process(It.Is<DeleteTableExpression>(expression =>
expression.SchemaName == loader.VersionTableMetaData.SchemaName
&& expression.TableName == loader.VersionTableMetaData.TableName)))
.Verifiable();
processor.Setup(p => p.Process(It.Is<DeleteSchemaExpression>(expression =>
expression.SchemaName == loader.VersionTableMetaData.SchemaName)))
.Verifiable();
loader.RemoveVersionTable();
processor.VerifyAll();
}
[Test]
public void RemoveVersionTableShouldNotRemoveSchemaIfItDidNotOwnTheSchema()
{
var processor = new Mock<IMigrationProcessor>();
var serviceProvider = ServiceCollectionExtensions.CreateServices()
.WithProcessor(processor)
.AddScoped(_ => ConventionSets.NoSchemaName)
.AddScoped<IMigrationRunnerConventionsAccessor>(
_ => new PassThroughMigrationRunnerConventionsAccessor(new MigrationRunnerConventions()))
.AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader("No connection"))
.BuildServiceProvider();
var loader = serviceProvider.GetRequiredService<IVersionLoader>();
((TestVersionTableMetaData) loader.VersionTableMetaData).OwnsSchema = false;
processor.Setup(p => p.Process(It.Is<DeleteTableExpression>(expression =>
expression.SchemaName == loader.VersionTableMetaData.SchemaName
&& expression.TableName == loader.VersionTableMetaData.TableName)))
.Verifiable();
loader.RemoveVersionTable();
processor.Verify(p => p.Process(It.IsAny<DeleteSchemaExpression>()), Times.Never());
}
[Test]
public void UpdateVersionShouldExecuteInsertDataExpression()
{
var processor = new Mock<IMigrationProcessor>();
var serviceProvider = ServiceCollectionExtensions.CreateServices()
.WithProcessor(processor)
.AddScoped(_ => ConventionSets.NoSchemaName)
.AddScoped<IMigrationRunnerConventionsAccessor>(
_ => new PassThroughMigrationRunnerConventionsAccessor(new MigrationRunnerConventions()))
.AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader("No connection"))
.BuildServiceProvider();
var loader = serviceProvider.GetRequiredService<IVersionLoader>();
processor.Setup(p => p.Process(It.Is<InsertDataExpression>(expression =>
expression.SchemaName == loader.VersionTableMetaData.SchemaName
&& expression.TableName == loader.VersionTableMetaData.TableName
&& expression.Rows.Any(
definition =>
definition.Any(
pair =>
pair.Key == loader.VersionTableMetaData.ColumnName && pair.Value.Equals(1L))))))
.Verifiable();
loader.UpdateVersionInfo(1);
processor.VerifyAll();
}
[Test]
public void VersionSchemaMigrationOnlyRunOnceEvenIfExistenceChecksReturnFalse()
{
var processor = new Mock<IMigrationProcessor>();
var runner = new Mock<IMigrationRunner>();
runner.SetupGet(r => r.Processor).Returns(processor.Object);
processor.Setup(p => p.SchemaExists(It.IsAny<string>())).Returns(false);
var serviceProvider = ServiceCollectionExtensions.CreateServices()
.WithProcessor(processor)
.AddScoped(_ => ConventionSets.NoSchemaName)
.AddScoped<IMigrationRunnerConventionsAccessor>(
_ => new PassThroughMigrationRunnerConventionsAccessor(new MigrationRunnerConventions()))
.AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader("No connection"))
.AddScoped<IVersionLoader, VersionLoader>()
.AddScoped(_ => runner.Object)
.BuildServiceProvider();
var loader = (VersionLoader) serviceProvider.GetRequiredService<IVersionLoader>();
loader.LoadVersionInfo();
runner.Verify(r => r.Up(loader.VersionSchemaMigration), Times.Once());
}
[Test]
public void VersionMigrationOnlyRunOnceEvenIfExistenceChecksReturnFalse()
{
var processor = new Mock<IMigrationProcessor>();
var runner = new Mock<IMigrationRunner>();
runner.SetupGet(r => r.Processor).Returns(processor.Object);
processor.Setup(
p => p.TableExists(new TestVersionTableMetaData().SchemaName, TestVersionTableMetaData.TABLE_NAME))
.Returns(false);
var serviceProvider = ServiceCollectionExtensions.CreateServices()
.WithProcessor(processor)
.AddScoped(_ => ConventionSets.NoSchemaName)
.AddScoped<IMigrationRunnerConventionsAccessor>(
_ => new PassThroughMigrationRunnerConventionsAccessor(new MigrationRunnerConventions()))
.AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader("No connection"))
.AddScoped<IVersionLoader, VersionLoader>()
.AddScoped(_ => runner.Object)
.BuildServiceProvider();
var loader = (VersionLoader) serviceProvider.GetRequiredService<IVersionLoader>();
loader.LoadVersionInfo();
runner.Verify(r => r.Up(loader.VersionMigration), Times.Once());
}
[Test]
public void VersionUniqueMigrationOnlyRunOnceEvenIfExistenceChecksReturnFalse()
{
var processor = new Mock<IMigrationProcessor>();
var runner = new Mock<IMigrationRunner>();
runner.SetupGet(r => r.Processor).Returns(processor.Object);
processor.Setup(p => p.ColumnExists(new TestVersionTableMetaData().SchemaName, TestVersionTableMetaData.TABLE_NAME, TestVersionTableMetaData.APPLIED_ON_COLUMN_NAME)).Returns(false);
var serviceProvider = ServiceCollectionExtensions.CreateServices()
.WithProcessor(processor)
.AddScoped(_ => ConventionSets.NoSchemaName)
.AddScoped<IMigrationRunnerConventionsAccessor>(
_ => new PassThroughMigrationRunnerConventionsAccessor(new MigrationRunnerConventions()))
.AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader("No connection"))
.AddScoped<IVersionLoader, VersionLoader>()
.AddScoped(_ => runner.Object)
.BuildServiceProvider();
var loader = (VersionLoader) serviceProvider.GetRequiredService<IVersionLoader>();
loader.LoadVersionInfo();
runner.Verify(r => r.Up(loader.VersionUniqueMigration), Times.Once());
}
[Test]
public void VersionDescriptionMigrationOnlyRunOnceEvenIfExistenceChecksReturnFalse()
{
var processor = new Mock<IMigrationProcessor>();
var runner = new Mock<IMigrationRunner>();
runner.SetupGet(r => r.Processor).Returns(processor.Object);
processor.Setup(p => p.ColumnExists(new TestVersionTableMetaData().SchemaName, TestVersionTableMetaData.TABLE_NAME, TestVersionTableMetaData.APPLIED_ON_COLUMN_NAME)).Returns(false);
var serviceProvider = ServiceCollectionExtensions.CreateServices()
.WithProcessor(processor)
.AddScoped(_ => ConventionSets.NoSchemaName)
.AddScoped<IMigrationRunnerConventionsAccessor>(
_ => new PassThroughMigrationRunnerConventionsAccessor(new MigrationRunnerConventions()))
.AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader("No connection"))
.AddScoped<IVersionLoader, VersionLoader>()
.AddScoped(_ => runner.Object)
.BuildServiceProvider();
var loader = (VersionLoader) serviceProvider.GetRequiredService<IVersionLoader>();
loader.LoadVersionInfo();
runner.Verify(r => r.Up(loader.VersionDescriptionMigration), Times.Once());
}
}
}
| |
namespace KabMan.Forms
{
partial class RackManagerForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.CBarManager = new DevExpress.XtraBars.BarManager(this.components);
this.CStatusBar = new DevExpress.XtraBars.Bar();
this.itemCount = new DevExpress.XtraBars.BarStaticItem();
this.bar1 = new DevExpress.XtraBars.Bar();
this.itemNew = new DevExpress.XtraBars.BarButtonItem();
this.itemDelete = new DevExpress.XtraBars.BarButtonItem();
this.itemDetails = new DevExpress.XtraBars.BarButtonItem();
this.itemExit = new DevExpress.XtraBars.BarButtonItem();
this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.CRackGrid = new DevExpress.XtraGrid.GridControl();
this.CRackView = new DevExpress.XtraGrid.Views.Grid.GridView();
this.gridColumn7 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn2 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn3 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn4 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn5 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn6 = new DevExpress.XtraGrid.Columns.GridColumn();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
((System.ComponentModel.ISupportInitialize)(this.CBarManager)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.CRackGrid)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CRackView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
this.SuspendLayout();
//
// CBarManager
//
this.CBarManager.AllowCustomization = false;
this.CBarManager.AllowQuickCustomization = false;
this.CBarManager.AllowShowToolbarsPopup = false;
this.CBarManager.Bars.AddRange(new DevExpress.XtraBars.Bar[] {
this.CStatusBar,
this.bar1});
this.CBarManager.DockControls.Add(this.barDockControlTop);
this.CBarManager.DockControls.Add(this.barDockControlBottom);
this.CBarManager.DockControls.Add(this.barDockControlLeft);
this.CBarManager.DockControls.Add(this.barDockControlRight);
this.CBarManager.Form = this;
this.CBarManager.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.itemCount,
this.itemNew,
this.itemDelete,
this.itemDetails,
this.itemExit});
this.CBarManager.MaxItemId = 9;
this.CBarManager.StatusBar = this.CStatusBar;
//
// CStatusBar
//
this.CStatusBar.BarName = "Status Bar";
this.CStatusBar.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.Bottom;
this.CStatusBar.DockCol = 0;
this.CStatusBar.DockRow = 0;
this.CStatusBar.DockStyle = DevExpress.XtraBars.BarDockStyle.Bottom;
this.CStatusBar.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.itemCount)});
this.CStatusBar.OptionsBar.AllowQuickCustomization = false;
this.CStatusBar.OptionsBar.DrawDragBorder = false;
this.CStatusBar.OptionsBar.UseWholeRow = true;
this.CStatusBar.Text = "Status Bar";
//
// itemCount
//
this.itemCount.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Right;
this.itemCount.Caption = "0";
this.itemCount.Id = 4;
this.itemCount.Name = "itemCount";
this.itemCount.TextAlignment = System.Drawing.StringAlignment.Near;
//
// bar1
//
this.bar1.BarName = "Custom 4";
this.bar1.DockCol = 0;
this.bar1.DockRow = 0;
this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.itemNew),
new DevExpress.XtraBars.LinkPersistInfo(this.itemDelete),
new DevExpress.XtraBars.LinkPersistInfo(this.itemDetails, true),
new DevExpress.XtraBars.LinkPersistInfo(this.itemExit, true)});
this.bar1.OptionsBar.AllowQuickCustomization = false;
this.bar1.OptionsBar.DrawDragBorder = false;
this.bar1.OptionsBar.UseWholeRow = true;
this.bar1.Text = "Custom 4";
//
// itemNew
//
this.itemNew.Caption = "New";
this.itemNew.Id = 5;
this.itemNew.Name = "itemNew";
this.itemNew.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
this.itemNew.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemNew_ItemClick);
//
// itemDelete
//
this.itemDelete.Caption = "Delete";
this.itemDelete.Id = 6;
this.itemDelete.Name = "itemDelete";
this.itemDelete.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
//
// itemDetails
//
this.itemDetails.Caption = "View Details";
this.itemDetails.Id = 7;
this.itemDetails.Name = "itemDetails";
this.itemDetails.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
this.itemDetails.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemDetails_ItemClick);
//
// itemExit
//
this.itemExit.Caption = "Exit";
this.itemExit.Id = 8;
this.itemExit.Name = "itemExit";
this.itemExit.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
this.itemExit.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemExit_ItemClick);
//
// layoutControl1
//
this.layoutControl1.AllowCustomizationMenu = false;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true;
this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true;
this.layoutControl1.Controls.Add(this.CRackGrid);
this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutControl1.Location = new System.Drawing.Point(0, 24);
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.layoutControlGroup1;
this.layoutControl1.Size = new System.Drawing.Size(556, 533);
this.layoutControl1.TabIndex = 4;
this.layoutControl1.Text = "layoutControl1";
//
// CRackGrid
//
this.CRackGrid.Location = new System.Drawing.Point(7, 7);
this.CRackGrid.MainView = this.CRackView;
this.CRackGrid.Name = "CRackGrid";
this.CRackGrid.Size = new System.Drawing.Size(543, 520);
this.CRackGrid.TabIndex = 4;
this.CRackGrid.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] {
this.CRackView});
this.CRackGrid.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.CRackGrid_MouseDoubleClick);
//
// CRackView
//
this.CRackView.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.CRackView.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray;
this.CRackView.Appearance.ColumnFilterButton.Options.UseBackColor = true;
this.CRackView.Appearance.ColumnFilterButton.Options.UseBorderColor = true;
this.CRackView.Appearance.ColumnFilterButton.Options.UseForeColor = true;
this.CRackView.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.CRackView.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223)))));
this.CRackView.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.CRackView.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue;
this.CRackView.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true;
this.CRackView.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true;
this.CRackView.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true;
this.CRackView.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
this.CRackView.Appearance.Empty.Options.UseBackColor = true;
this.CRackView.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223)))));
this.CRackView.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite;
this.CRackView.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.CRackView.Appearance.EvenRow.Options.UseBackColor = true;
this.CRackView.Appearance.EvenRow.Options.UseForeColor = true;
this.CRackView.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CRackView.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225)))));
this.CRackView.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CRackView.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.CRackView.Appearance.FilterCloseButton.Options.UseBackColor = true;
this.CRackView.Appearance.FilterCloseButton.Options.UseBorderColor = true;
this.CRackView.Appearance.FilterCloseButton.Options.UseForeColor = true;
this.CRackView.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135)))));
this.CRackView.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CRackView.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White;
this.CRackView.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.CRackView.Appearance.FilterPanel.Options.UseBackColor = true;
this.CRackView.Appearance.FilterPanel.Options.UseForeColor = true;
this.CRackView.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58)))));
this.CRackView.Appearance.FixedLine.Options.UseBackColor = true;
this.CRackView.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225)))));
this.CRackView.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.FocusedCell.Options.UseBackColor = true;
this.CRackView.Appearance.FocusedCell.Options.UseForeColor = true;
this.CRackView.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy;
this.CRackView.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178)))));
this.CRackView.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White;
this.CRackView.Appearance.FocusedRow.Options.UseBackColor = true;
this.CRackView.Appearance.FocusedRow.Options.UseForeColor = true;
this.CRackView.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.FooterPanel.Options.UseBackColor = true;
this.CRackView.Appearance.FooterPanel.Options.UseBorderColor = true;
this.CRackView.Appearance.FooterPanel.Options.UseForeColor = true;
this.CRackView.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.GroupButton.Options.UseBackColor = true;
this.CRackView.Appearance.GroupButton.Options.UseBorderColor = true;
this.CRackView.Appearance.GroupButton.Options.UseForeColor = true;
this.CRackView.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202)))));
this.CRackView.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202)))));
this.CRackView.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.GroupFooter.Options.UseBackColor = true;
this.CRackView.Appearance.GroupFooter.Options.UseBorderColor = true;
this.CRackView.Appearance.GroupFooter.Options.UseForeColor = true;
this.CRackView.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165)))));
this.CRackView.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White;
this.CRackView.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.CRackView.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White;
this.CRackView.Appearance.GroupPanel.Options.UseBackColor = true;
this.CRackView.Appearance.GroupPanel.Options.UseFont = true;
this.CRackView.Appearance.GroupPanel.Options.UseForeColor = true;
this.CRackView.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray;
this.CRackView.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.GroupRow.Options.UseBackColor = true;
this.CRackView.Appearance.GroupRow.Options.UseForeColor = true;
this.CRackView.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.CRackView.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.HeaderPanel.Options.UseBackColor = true;
this.CRackView.Appearance.HeaderPanel.Options.UseBorderColor = true;
this.CRackView.Appearance.HeaderPanel.Options.UseFont = true;
this.CRackView.Appearance.HeaderPanel.Options.UseForeColor = true;
this.CRackView.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray;
this.CRackView.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CRackView.Appearance.HideSelectionRow.Options.UseBackColor = true;
this.CRackView.Appearance.HideSelectionRow.Options.UseForeColor = true;
this.CRackView.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.HorzLine.Options.UseBackColor = true;
this.CRackView.Appearance.OddRow.BackColor = System.Drawing.Color.White;
this.CRackView.Appearance.OddRow.BackColor2 = System.Drawing.Color.White;
this.CRackView.Appearance.OddRow.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal;
this.CRackView.Appearance.OddRow.Options.UseBackColor = true;
this.CRackView.Appearance.OddRow.Options.UseForeColor = true;
this.CRackView.Appearance.Preview.BackColor = System.Drawing.Color.White;
this.CRackView.Appearance.Preview.ForeColor = System.Drawing.Color.Navy;
this.CRackView.Appearance.Preview.Options.UseBackColor = true;
this.CRackView.Appearance.Preview.Options.UseForeColor = true;
this.CRackView.Appearance.Row.BackColor = System.Drawing.Color.White;
this.CRackView.Appearance.Row.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.Row.Options.UseBackColor = true;
this.CRackView.Appearance.Row.Options.UseForeColor = true;
this.CRackView.Appearance.RowSeparator.BackColor = System.Drawing.Color.White;
this.CRackView.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
this.CRackView.Appearance.RowSeparator.Options.UseBackColor = true;
this.CRackView.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138)))));
this.CRackView.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White;
this.CRackView.Appearance.SelectedRow.Options.UseBackColor = true;
this.CRackView.Appearance.SelectedRow.Options.UseForeColor = true;
this.CRackView.Appearance.VertLine.BackColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.VertLine.Options.UseBackColor = true;
this.CRackView.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
this.gridColumn7,
this.gridColumn1,
this.gridColumn2,
this.gridColumn3,
this.gridColumn4,
this.gridColumn5,
this.gridColumn6});
this.CRackView.GridControl = this.CRackGrid;
this.CRackView.Name = "CRackView";
this.CRackView.OptionsBehavior.AllowIncrementalSearch = true;
this.CRackView.OptionsBehavior.Editable = false;
this.CRackView.OptionsView.EnableAppearanceEvenRow = true;
this.CRackView.OptionsView.EnableAppearanceOddRow = true;
this.CRackView.OptionsView.ShowAutoFilterRow = true;
this.CRackView.OptionsView.ShowGroupPanel = false;
this.CRackView.OptionsView.ShowIndicator = false;
//
// gridColumn7
//
this.gridColumn7.Caption = "ID";
this.gridColumn7.FieldName = "ID";
this.gridColumn7.Name = "gridColumn7";
//
// gridColumn1
//
this.gridColumn1.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn1.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn1.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn1.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn1.Caption = "Name";
this.gridColumn1.FieldName = "Name";
this.gridColumn1.Name = "gridColumn1";
this.gridColumn1.Visible = true;
this.gridColumn1.VisibleIndex = 0;
//
// gridColumn2
//
this.gridColumn2.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn2.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn2.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn2.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn2.Caption = "Location";
this.gridColumn2.FieldName = "LocationName";
this.gridColumn2.Name = "gridColumn2";
this.gridColumn2.Visible = true;
this.gridColumn2.VisibleIndex = 1;
//
// gridColumn3
//
this.gridColumn3.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn3.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn3.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn3.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn3.Caption = "Data Center";
this.gridColumn3.FieldName = "DataCenterName";
this.gridColumn3.Name = "gridColumn3";
this.gridColumn3.Visible = true;
this.gridColumn3.VisibleIndex = 2;
//
// gridColumn4
//
this.gridColumn4.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn4.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn4.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn4.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn4.Caption = "Coordinate";
this.gridColumn4.FieldName = "CoordinateName";
this.gridColumn4.Name = "gridColumn4";
this.gridColumn4.Visible = true;
this.gridColumn4.VisibleIndex = 3;
//
// gridColumn5
//
this.gridColumn5.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn5.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn5.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn5.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn5.Caption = "Operating System";
this.gridColumn5.FieldName = "OSName";
this.gridColumn5.Name = "gridColumn5";
this.gridColumn5.Visible = true;
this.gridColumn5.VisibleIndex = 4;
//
// gridColumn6
//
this.gridColumn6.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn6.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn6.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn6.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn6.Caption = "Port Count";
this.gridColumn6.FieldName = "PortCount";
this.gridColumn6.Name = "gridColumn6";
this.gridColumn6.Visible = true;
this.gridColumn6.VisibleIndex = 5;
//
// layoutControlGroup1
//
this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1";
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem1});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "layoutControlGroup1";
this.layoutControlGroup1.Size = new System.Drawing.Size(556, 533);
this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup1.Text = "layoutControlGroup1";
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.CRackGrid;
this.layoutControlItem1.CustomizationFormText = "layoutControlItem1";
this.layoutControlItem1.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(554, 531);
this.layoutControlItem1.Text = "layoutControlItem1";
this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem1.TextToControlDistance = 0;
this.layoutControlItem1.TextVisible = false;
//
// RackManagerForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(556, 582);
this.Controls.Add(this.layoutControl1);
this.Controls.Add(this.barDockControlLeft);
this.Controls.Add(this.barDockControlRight);
this.Controls.Add(this.barDockControlBottom);
this.Controls.Add(this.barDockControlTop);
this.Name = "RackManagerForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Rack Management";
this.Load += new System.EventHandler(this.RackManagerForm_Load);
((System.ComponentModel.ISupportInitialize)(this.CBarManager)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.CRackGrid)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CRackView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraBars.BarManager CBarManager;
private DevExpress.XtraBars.Bar CStatusBar;
private DevExpress.XtraBars.BarDockControl barDockControlTop;
private DevExpress.XtraBars.BarDockControl barDockControlBottom;
private DevExpress.XtraBars.BarDockControl barDockControlLeft;
private DevExpress.XtraBars.BarDockControl barDockControlRight;
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraGrid.GridControl CRackGrid;
private DevExpress.XtraGrid.Views.Grid.GridView CRackView;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraBars.BarStaticItem itemCount;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn1;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn2;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn3;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn4;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn5;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn6;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn7;
private DevExpress.XtraBars.Bar bar1;
private DevExpress.XtraBars.BarButtonItem itemNew;
private DevExpress.XtraBars.BarButtonItem itemDelete;
private DevExpress.XtraBars.BarButtonItem itemDetails;
private DevExpress.XtraBars.BarButtonItem itemExit;
}
}
| |
//
// System.Web.TraceData
//
// Author(s):
// Jackson Harper (jackson@ximian.com)
//
// (C) 2004 Novell, Inc (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace System.Web {
internal class TraceData {
private bool is_first_time;
private DateTime first_time;
private double prev_time;
private DataTable info;
private DataTable control_data;
private DataTable cookie_data;
private DataTable header_data;
private DataTable servervar_data;
private string request_path;
private string session_id;
private DateTime request_time;
private Encoding request_encoding;
private Encoding response_encoding;
private string request_type;
private int status_code;
public TraceData ()
{
info = new DataTable ();
info.Columns.Add (new DataColumn ("Category", typeof (string)));
info.Columns.Add (new DataColumn ("Message", typeof (string)));
info.Columns.Add (new DataColumn ("Exception", typeof (string)));
info.Columns.Add (new DataColumn ("TimeSinceFirst", typeof (double)));
info.Columns.Add (new DataColumn ("IsWarning", typeof (bool)));
control_data = new DataTable ();
control_data.Columns.Add (new DataColumn ("ControlId", typeof (string)));
control_data.Columns.Add (new DataColumn ("Type", typeof (System.Type)));
control_data.Columns.Add (new DataColumn ("RenderSize", typeof (int)));
control_data.Columns.Add (new DataColumn ("ViewstateSize", typeof (int)));
control_data.Columns.Add (new DataColumn ("Depth", typeof (int)));
cookie_data = new DataTable ();
cookie_data.Columns.Add (new DataColumn ("Name", typeof (string)));
cookie_data.Columns.Add (new DataColumn ("Value", typeof (string)));
header_data = new DataTable ();
header_data.Columns.Add (new DataColumn ("Name", typeof (string)));
header_data.Columns.Add (new DataColumn ("Value", typeof (string)));
servervar_data = new DataTable ();
servervar_data.Columns.Add (new DataColumn ("Name", typeof (string)));
servervar_data.Columns.Add (new DataColumn ("Value", typeof (string)));
is_first_time = true;
}
public string RequestPath {
get { return request_path; }
set { request_path = value; }
}
public string SessionID {
get { return session_id; }
set { session_id = value; }
}
public DateTime RequestTime {
get { return request_time; }
set { request_time = value; }
}
public Encoding RequestEncoding {
get { return request_encoding; }
set { request_encoding = value; }
}
public Encoding ResponseEncoding {
get { return response_encoding; }
set { response_encoding = value; }
}
public string RequestType {
get { return request_type; }
set { request_type = value; }
}
public int StatusCode {
get { return status_code; }
set { status_code = value; }
}
public void Write (string category, string msg, Exception error, bool Warning)
{
double time;
if (is_first_time) {
time = 0;
is_first_time = false;
first_time = DateTime.Now;
} else
time = (DateTime.Now - first_time).TotalSeconds;
DataRow r = info.NewRow ();
r ["Category"] = category;
r ["Message"] = HtmlEncode (msg);
r ["Exception"] = (error != null ? error.ToString () : null);
r ["TimeSinceFirst"] = time;
r ["IsWarning"] = Warning;
info.Rows.Add (r);
}
static string HtmlEncode (string s)
{
if (s == null)
return "";
string res = HttpUtility.HtmlEncode (s);
res = res.Replace ("\n", "<br>");
return res.Replace (" ", " ");
}
public void AddControlTree (Page page)
{
AddControl (page, 0);
}
private void AddControl (Control c, int control_pos)
{
DataRow r = control_data.NewRow ();
r ["ControlId"] = c.UniqueID;
r ["Type"] = c.GetType ();
r ["Depth"] = control_pos;
control_data.Rows.Add (r);
foreach (Control child in c.Controls)
AddControl (child, control_pos + 1);
}
public void AddCookie (string name, string value)
{
DataRow r = cookie_data.NewRow ();
r ["Name"] = name;
r ["Value"] = value;
cookie_data.Rows.Add (r);
}
public void AddHeader (string name, string value)
{
DataRow r = header_data.NewRow ();
r ["Name"] = name;
r ["Value"] = value;
header_data.Rows.Add (r);
}
public void AddServerVar (string name, string value)
{
DataRow r = servervar_data.NewRow ();
r ["Name"] = name;
r ["Value"] = value;
servervar_data.Rows.Add (r);
}
public void Render (HtmlTextWriter output)
{
output.AddAttribute ("id", "__asptrace");
output.RenderBeginTag (HtmlTextWriterTag.Div);
RenderStyleSheet (output);
output.AddAttribute ("class", "tracecontent");
output.RenderBeginTag (HtmlTextWriterTag.Span);
RenderRequestDetails (output);
RenderTraceInfo (output);
RenderControlTree (output);
RenderCookies (output);
RenderHeaders (output);
RenderServerVars (output);
output.RenderEndTag ();
output.RenderEndTag ();
}
private void RenderRequestDetails (HtmlTextWriter output)
{
Table table = CreateTable ();
table.Rows.Add (AltRow ("Request Details:"));
table.Rows.Add (InfoRow2 ("Session Id:", session_id,
"Request Type", request_type));
table.Rows.Add (InfoRow2 ("Time of Request:", request_time.ToString (),
"State Code:", status_code.ToString ()));
table.Rows.Add (InfoRow2 ("Request Encoding:", request_encoding.EncodingName,
"Response Encoding:", response_encoding.EncodingName));
table.RenderControl (output);
}
private void RenderTraceInfo (HtmlTextWriter output)
{
Table table = CreateTable ();
table.Rows.Add (AltRow ("Trace Information"));
table.Rows.Add (SubHeadRow ("Category", "Message", "From First(s)", "From Lasts(s)"));
int pos = 0;
foreach (DataRow r in info.Rows)
RenderTraceInfoRow (table, r, pos++);
table.RenderControl (output);
}
private void RenderControlTree (HtmlTextWriter output)
{
Table table = CreateTable ();
table.Rows.Add (AltRow ("Control Tree"));
table.Rows.Add (SubHeadRow ("Control Id", "Type",
"Render Size Bytes (including children)",
"View state Size Bytes (excluding children)"));
int pos = 0;
foreach (DataRow r in control_data.Rows) {
int depth = (int) r ["Depth"];
string prefix = String.Empty;
for (int i=0; i<depth; i++)
prefix += " ";
RenderAltRow (table, pos++, prefix + r ["ControlId"],
r ["Type"].ToString (), " ", " ");
}
table.RenderControl (output);
}
private void RenderCookies (HtmlTextWriter output)
{
Table table = CreateTable ();
table.Rows.Add (AltRow ("Cookies Collection"));
table.Rows.Add (SubHeadRow ("Name", "Value", "Size"));
int pos = 0;
foreach (DataRow r in cookie_data.Rows) {
string name = r ["Name"].ToString ();
string value = r ["Value"].ToString ();
int length = name.Length + (value == null ? 0 : value.Length);
RenderAltRow (table, pos++, name, value, length.ToString ());
}
table.RenderControl (output);
}
private void RenderHeaders (HtmlTextWriter output)
{
Table table = CreateTable ();
table.Rows.Add (AltRow ("Headers Collection"));
table.Rows.Add (SubHeadRow ("Name", "Value"));
int pos = 0;
foreach (DataRow r in header_data.Rows)
RenderAltRow (table, pos++, r ["Name"].ToString (), r ["Value"].ToString ());
table.RenderControl (output);
}
private void RenderServerVars (HtmlTextWriter output)
{
Table table = CreateTable ();
table.Rows.Add (AltRow ("Server Variables"));
table.Rows.Add (SubHeadRow ("Name", "Value"));
int pos = 0;
foreach (DataRow r in servervar_data.Rows)
RenderAltRow (table, pos++, r ["Name"].ToString (), r ["Value"].ToString ());
table.RenderControl (output);
}
internal static TableRow AltRow (string title)
{
TableRow row = new TableRow ();
TableHeaderCell header = new TableHeaderCell ();
header.CssClass = "alt";
header.HorizontalAlign = HorizontalAlign.Left;
header.Attributes [" colspan"] = "10";
header.Text = "<h3><b>" + title + "</b></h3>";
row.Cells.Add (header);
return row;
}
private TableRow RenderTraceInfoRow (Table table, DataRow r, int pos)
{
string open, close;
open = close = String.Empty;
if ((bool) r ["IsWarning"]) {
open = "<font color=\"Red\">";
close = "</font>";
}
double t = (double) r ["TimeSinceFirst"];
string t1, t2;
if (t == 0) {
t1 = t2 = String.Empty;
prev_time = 0;
} else {
t1 = t.ToString ("0.000000");
t2 = (t - prev_time).ToString ("0.000000");
prev_time = t;
}
return RenderAltRow (table, pos, open + (string) r ["Category"] + close,
open + (string) r ["Message"] + close, t1, t2);
}
internal static TableRow SubHeadRow (params string[] cells)
{
TableRow row = new TableRow ();
foreach (string s in cells) {
TableHeaderCell cell = new TableHeaderCell ();
cell.Text = s;
row.Cells.Add (cell);
}
row.CssClass = "subhead";
row.HorizontalAlign = HorizontalAlign.Left;
return row;
}
internal static TableRow RenderAltRow (Table table, int pos, params string[] cells)
{
TableRow row = new TableRow ();
foreach (string s in cells) {
TableCell cell = new TableCell ();
cell.Text = s;
row.Cells.Add (cell);
}
if ((pos % 2) != 0)
row.CssClass = "alt";
table.Rows.Add (row);
return row;
}
private TableRow InfoRow2 (string title1, string info1, string title2, string info2)
{
TableRow row = new TableRow ();
TableHeaderCell header1 = new TableHeaderCell ();
TableHeaderCell header2 = new TableHeaderCell ();
TableCell cell1 = new TableCell ();
TableCell cell2 = new TableCell ();
header1.Text = title1;
header2.Text = title2;
cell1.Text = info1;
cell2.Text = info2;
row.Cells.Add (header1);
row.Cells.Add (cell1);
row.Cells.Add (header2);
row.Cells.Add (cell2);
row.HorizontalAlign = HorizontalAlign.Left;
return row;
}
internal static Table CreateTable ()
{
Table table = new Table ();
table.Width = Unit.Percentage (100);
table.CellSpacing = 0;
table.CellPadding = 0;
return table;
}
internal static void RenderStyleSheet (HtmlTextWriter o)
{
o.WriteLine ("<style type=\"text/css\">");
o.Write ("span.tracecontent { background-color:white; ");
o.WriteLine ("color:black;font: 10pt verdana, arial; }");
o.Write ("span.tracecontent table { font: 10pt verdana, ");
o.WriteLine ("arial; cellspacing:0; cellpadding:0; margin-bottom:25}");
o.WriteLine ("span.tracecontent tr.subhead { background-color:cccccc;}");
o.WriteLine ("span.tracecontent th { padding:0,3,0,3 }");
o.WriteLine ("span.tracecontent th.alt { background-color:black; color:white; padding:3,3,2,3; }");
o.WriteLine ("span.tracecontent td { padding:0,3,0,3 }");
o.WriteLine ("span.tracecontent tr.alt { background-color:eeeeee }");
o.WriteLine ("span.tracecontent h1 { font: 24pt verdana, arial; margin:0,0,0,0}");
o.WriteLine ("span.tracecontent h2 { font: 18pt verdana, arial; margin:0,0,0,0}");
o.WriteLine ("span.tracecontent h3 { font: 12pt verdana, arial; margin:0,0,0,0}");
o.WriteLine ("span.tracecontent th a { color:darkblue; font: 8pt verdana, arial; }");
o.WriteLine ("span.tracecontent a { color:darkblue;text-decoration:none }");
o.WriteLine ("span.tracecontent a:hover { color:darkblue;text-decoration:underline; }");
o.WriteLine ("span.tracecontent div.outer { width:90%; margin:15,15,15,15}");
o.Write ("span.tracecontent table.viewmenu td { background-color:006699; ");
o.WriteLine ("color:white; padding:0,5,0,5; }");
o.WriteLine ("span.tracecontent table.viewmenu td.end { padding:0,0,0,0; }");
o.WriteLine ("span.tracecontent table.viewmenu a {color:white; font: 8pt verdana, arial; }");
o.WriteLine ("span.tracecontent table.viewmenu a:hover {color:white; font: 8pt verdana, arial; }");
o.WriteLine ("span.tracecontent a.tinylink {color:darkblue; font: 8pt verdana, ");
o.WriteLine ("arial;text-decoration:underline;}");
o.WriteLine ("span.tracecontent a.link {color:darkblue; text-decoration:underline;}");
o.WriteLine ("span.tracecontent div.buffer {padding-top:7; padding-bottom:17;}");
o.WriteLine ("span.tracecontent .small { font: 8pt verdana, arial }");
o.WriteLine ("span.tracecontent table td { padding-right:20 }");
o.WriteLine ("span.tracecontent table td.nopad { padding-right:5 }");
o.WriteLine ("</style>");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.