context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers;
using Google.ProtocolBuffers.TestProtos;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Google.ProtocolBuffers
{
[TestClass]
public class AbstractBuilderLiteTest
{
[TestMethod]
public void TestMergeFromCodedInputStream()
{
TestAllTypesLite copy,
msg = TestAllTypesLite.CreateBuilder()
.SetOptionalUint32(uint.MaxValue).Build();
copy = TestAllTypesLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
using (MemoryStream ms = new MemoryStream(msg.ToByteArray()))
{
CodedInputStream ci = CodedInputStream.CreateInstance(ms);
copy = copy.ToBuilder().MergeFrom(ci).Build();
}
TestUtil.AssertBytesEqual(msg.ToByteArray(), copy.ToByteArray());
}
[TestMethod]
public void TestIBuilderLiteWeakClear()
{
TestAllTypesLite copy, msg = TestAllTypesLite.DefaultInstance;
copy = msg.ToBuilder().SetOptionalString("Should be removed.").Build();
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
copy = (TestAllTypesLite) ((IBuilderLite) copy.ToBuilder()).WeakClear().WeakBuild();
TestUtil.AssertBytesEqual(msg.ToByteArray(), copy.ToByteArray());
}
[TestMethod]
public void TestBuilderLiteMergeFromCodedInputStream()
{
TestAllTypesLite copy,
msg = TestAllTypesLite.CreateBuilder()
.SetOptionalString("Should be merged.").Build();
copy = TestAllTypesLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
copy =
copy.ToBuilder().MergeFrom(CodedInputStream.CreateInstance(new MemoryStream(msg.ToByteArray()))).Build();
TestUtil.AssertBytesEqual(msg.ToByteArray(), copy.ToByteArray());
}
[TestMethod]
public void TestBuilderLiteMergeDelimitedFrom()
{
TestAllTypesLite copy,
msg = TestAllTypesLite.CreateBuilder()
.SetOptionalString("Should be merged.").Build();
copy = TestAllTypesLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
Stream s = new MemoryStream();
msg.WriteDelimitedTo(s);
s.Position = 0;
copy = copy.ToBuilder().MergeDelimitedFrom(s).Build();
TestUtil.AssertBytesEqual(msg.ToByteArray(), copy.ToByteArray());
}
[TestMethod]
public void TestBuilderLiteMergeDelimitedFromExtensions()
{
TestAllExtensionsLite copy,
msg = TestAllExtensionsLite.CreateBuilder()
.SetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite,
"Should be merged.").Build();
copy = TestAllExtensionsLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
Stream s = new MemoryStream();
msg.WriteDelimitedTo(s);
s.Position = 0;
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestLiteProtoFile.RegisterAllExtensions(registry);
copy = copy.ToBuilder().MergeDelimitedFrom(s, registry).Build();
TestUtil.AssertBytesEqual(msg.ToByteArray(), copy.ToByteArray());
Assert.AreEqual("Should be merged.", copy.GetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite));
}
[TestMethod]
public void TestBuilderLiteMergeFromStream()
{
TestAllTypesLite copy,
msg = TestAllTypesLite.CreateBuilder()
.SetOptionalString("Should be merged.").Build();
copy = TestAllTypesLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
Stream s = new MemoryStream();
msg.WriteTo(s);
s.Position = 0;
copy = copy.ToBuilder().MergeFrom(s).Build();
TestUtil.AssertBytesEqual(msg.ToByteArray(), copy.ToByteArray());
}
[TestMethod]
public void TestBuilderLiteMergeFromStreamExtensions()
{
TestAllExtensionsLite copy,
msg = TestAllExtensionsLite.CreateBuilder()
.SetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite,
"Should be merged.").Build();
copy = TestAllExtensionsLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
Stream s = new MemoryStream();
msg.WriteTo(s);
s.Position = 0;
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestLiteProtoFile.RegisterAllExtensions(registry);
copy = copy.ToBuilder().MergeFrom(s, registry).Build();
TestUtil.AssertBytesEqual(msg.ToByteArray(), copy.ToByteArray());
Assert.AreEqual("Should be merged.", copy.GetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite));
}
[TestMethod]
public void TestIBuilderLiteWeakMergeFromIMessageLite()
{
TestAllTypesLite copy,
msg = TestAllTypesLite.CreateBuilder()
.SetOptionalString("Should be merged.").Build();
copy = TestAllTypesLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
copy = (TestAllTypesLite) ((IBuilderLite) copy.ToBuilder()).WeakMergeFrom((IMessageLite) msg).WeakBuild();
TestUtil.AssertBytesEqual(msg.ToByteArray(), copy.ToByteArray());
}
[TestMethod]
public void TestIBuilderLiteWeakMergeFromByteString()
{
TestAllTypesLite copy,
msg = TestAllTypesLite.CreateBuilder()
.SetOptionalString("Should be merged.").Build();
copy = TestAllTypesLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
copy = (TestAllTypesLite) ((IBuilderLite) copy.ToBuilder()).WeakMergeFrom(msg.ToByteString()).WeakBuild();
TestUtil.AssertBytesEqual(msg.ToByteArray(), copy.ToByteArray());
}
[TestMethod]
public void TestIBuilderLiteWeakMergeFromByteStringExtensions()
{
TestAllExtensionsLite copy,
msg = TestAllExtensionsLite.CreateBuilder()
.SetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite,
"Should be merged.").Build();
copy = TestAllExtensionsLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
copy =
(TestAllExtensionsLite)
((IBuilderLite) copy.ToBuilder()).WeakMergeFrom(msg.ToByteString(), ExtensionRegistry.Empty).WeakBuild();
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestLiteProtoFile.RegisterAllExtensions(registry);
copy =
(TestAllExtensionsLite)
((IBuilderLite) copy.ToBuilder()).WeakMergeFrom(msg.ToByteString(), registry).WeakBuild();
TestUtil.AssertBytesEqual(msg.ToByteArray(), copy.ToByteArray());
Assert.AreEqual("Should be merged.", copy.GetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite));
}
[TestMethod]
public void TestIBuilderLiteWeakMergeFromCodedInputStream()
{
TestAllTypesLite copy,
msg = TestAllTypesLite.CreateBuilder()
.SetOptionalUint32(uint.MaxValue).Build();
copy = TestAllTypesLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
using (MemoryStream ms = new MemoryStream(msg.ToByteArray()))
{
CodedInputStream ci = CodedInputStream.CreateInstance(ms);
copy = (TestAllTypesLite) ((IBuilderLite) copy.ToBuilder()).WeakMergeFrom(ci).WeakBuild();
}
TestUtil.AssertBytesEqual(msg.ToByteArray(), copy.ToByteArray());
}
[TestMethod]
public void TestIBuilderLiteWeakBuildPartial()
{
IBuilderLite builder = TestRequiredLite.CreateBuilder();
Assert.IsFalse(builder.IsInitialized);
IMessageLite msg = builder.WeakBuildPartial();
Assert.IsFalse(msg.IsInitialized);
TestUtil.AssertBytesEqual(msg.ToByteArray(), TestRequiredLite.DefaultInstance.ToByteArray());
}
[TestMethod, ExpectedException(typeof(UninitializedMessageException))]
public void TestIBuilderLiteWeakBuildUninitialized()
{
IBuilderLite builder = TestRequiredLite.CreateBuilder();
Assert.IsFalse(builder.IsInitialized);
builder.WeakBuild();
}
[TestMethod]
public void TestIBuilderLiteWeakBuild()
{
IBuilderLite builder = TestRequiredLite.CreateBuilder()
.SetD(0)
.SetEn(ExtraEnum.EXLITE_BAZ);
Assert.IsTrue(builder.IsInitialized);
builder.WeakBuild();
}
[TestMethod]
public void TestIBuilderLiteWeakClone()
{
TestRequiredLite msg = TestRequiredLite.CreateBuilder()
.SetD(1).SetEn(ExtraEnum.EXLITE_BAR).Build();
Assert.IsTrue(msg.IsInitialized);
IMessageLite copy = ((IBuilderLite) msg.ToBuilder()).WeakClone().WeakBuild();
TestUtil.AssertBytesEqual(msg.ToByteArray(), copy.ToByteArray());
}
[TestMethod]
public void TestIBuilderLiteWeakDefaultInstance()
{
Assert.IsTrue(ReferenceEquals(TestRequiredLite.DefaultInstance,
((IBuilderLite) TestRequiredLite.CreateBuilder()).WeakDefaultInstanceForType));
}
[TestMethod]
public void TestGeneratedBuilderLiteAddRange()
{
TestAllTypesLite copy,
msg = TestAllTypesLite.CreateBuilder()
.SetOptionalUint32(123)
.AddRepeatedInt32(1)
.AddRepeatedInt32(2)
.AddRepeatedInt32(3)
.Build();
copy = msg.DefaultInstanceForType.ToBuilder().MergeFrom(msg).Build();
TestUtil.AssertBytesEqual(msg.ToByteArray(), copy.ToByteArray());
}
// ROK 5/7/2013 Issue #54: should retire all bytes in buffer (bufferSize)
[TestMethod]
public void TestBufferRefillIssue()
{
var ms = new MemoryStream();
BucketOfBytes.CreateBuilder()
.SetValue(ByteString.CopyFrom(new byte[3000]))
.Build().WriteDelimitedTo(ms);
BucketOfBytesEx.CreateBuilder()
.SetValue(ByteString.CopyFrom(new byte[1000]))
.SetValue2(ByteString.CopyFrom(new byte[1100]))
.Build().WriteDelimitedTo(ms);
BucketOfBytes.CreateBuilder()
.SetValue(ByteString.CopyFrom(new byte[100]))
.Build().WriteDelimitedTo(ms);
ms.Position = 0;
var input = CodedInputStream.CreateInstance(ms);
var builder = BucketOfBytes.CreateBuilder();
input.ReadMessage(builder, ExtensionRegistry.Empty);
Assert.AreEqual(3005L, input.Position);
Assert.AreEqual(3000, builder.Value.Length);
input.ReadMessage(builder, ExtensionRegistry.Empty);
Assert.AreEqual(5114, input.Position);
Assert.AreEqual(1000, builder.Value.Length);
input.ReadMessage(builder, ExtensionRegistry.Empty);
Assert.AreEqual(5217L, input.Position);
Assert.AreEqual(input.Position, ms.Length);
Assert.AreEqual(100, builder.Value.Length);
}
}
}
| |
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 SWP.Backend.Areas.HelpPage.ModelDescriptions;
using SWP.Backend.Areas.HelpPage.Models;
namespace SWP.Backend.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);
}
}
}
}
| |
// 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: This class implements a set of methods for comparing
// strings.
//
//
////////////////////////////////////////////////////////////////////////////
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace System.Globalization
{
[Flags]
public enum CompareOptions
{
None = 0x00000000,
IgnoreCase = 0x00000001,
IgnoreNonSpace = 0x00000002,
IgnoreSymbols = 0x00000004,
IgnoreKanaType = 0x00000008, // ignore kanatype
IgnoreWidth = 0x00000010, // ignore width
OrdinalIgnoreCase = 0x10000000, // This flag can not be used with other flags.
StringSort = 0x20000000, // use string sort method
Ordinal = 0x40000000, // This flag can not be used with other flags.
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public partial class CompareInfo : IDeserializationCallback
{
// Mask used to check if IndexOf()/LastIndexOf()/IsPrefix()/IsPostfix() has the right flags.
private const CompareOptions ValidIndexMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType);
// Mask used to check if Compare() has the right flags.
private const CompareOptions ValidCompareMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
// Mask used to check if GetHashCodeOfString() has the right flags.
private const CompareOptions ValidHashCodeOfStringMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType);
// Mask used to check if we have the right flags.
private const CompareOptions ValidSortkeyCtorMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
// Cache the invariant CompareInfo
internal static readonly CompareInfo Invariant = CultureInfo.InvariantCulture.CompareInfo;
//
// CompareInfos have an interesting identity. They are attached to the locale that created them,
// ie: en-US would have an en-US sort. For haw-US (custom), then we serialize it as haw-US.
// The interesting part is that since haw-US doesn't have its own sort, it has to point at another
// locale, which is what SCOMPAREINFO does.
[OptionalField(VersionAdded = 2)]
private string m_name; // The name used to construct this CompareInfo. Do not rename (binary serialization)
[NonSerialized]
private string _sortName; // The name that defines our behavior
[OptionalField(VersionAdded = 3)]
private SortVersion m_SortVersion; // Do not rename (binary serialization)
// _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant
[NonSerialized]
private readonly bool _invariantMode = GlobalizationMode.Invariant;
private int culture; // Do not rename (binary serialization). The fields sole purpose is to support Desktop serialization.
internal CompareInfo(CultureInfo culture)
{
m_name = culture._name;
InitSort(culture);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture.
** Warning: The assembly versioning mechanism is dead!
**Returns: The CompareInfo for the specified culture.
**Arguments:
** culture the ID of the culture
** assembly the assembly which contains the sorting table.
**Exceptions:
** ArugmentNullException when the assembly is null
** ArgumentException if culture is invalid.
============================================================================*/
// Assembly constructor should be deprecated, we don't act on the assembly information any more
public static CompareInfo GetCompareInfo(int culture, Assembly assembly)
{
// Parameter checking.
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
if (assembly != typeof(Object).Module.Assembly)
{
throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
return GetCompareInfo(culture);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture.
** The purpose of this method is to provide version for CompareInfo tables.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** name the name of the culture
** assembly the assembly which contains the sorting table.
**Exceptions:
** ArugmentNullException when the assembly is null
** ArgumentException if name is invalid.
============================================================================*/
// Assembly constructor should be deprecated, we don't act on the assembly information any more
public static CompareInfo GetCompareInfo(string name, Assembly assembly)
{
if (name == null || assembly == null)
{
throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly));
}
if (assembly != typeof(Object).Module.Assembly)
{
throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
return GetCompareInfo(name);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo for the specified culture.
** This method is provided for ease of integration with NLS-based software.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** culture the ID of the culture.
**Exceptions:
** ArgumentException if culture is invalid.
============================================================================*/
// People really shouldn't be calling LCID versions, no custom support
public static CompareInfo GetCompareInfo(int culture)
{
if (CultureData.IsCustomCultureId(culture))
{
// Customized culture cannot be created by the LCID.
throw new ArgumentException(SR.Argument_CustomCultureCannotBePassedByNumber, nameof(culture));
}
return CultureInfo.GetCultureInfo(culture).CompareInfo;
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo for the specified culture.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** name the name of the culture.
**Exceptions:
** ArgumentException if name is invalid.
============================================================================*/
public static CompareInfo GetCompareInfo(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
return CultureInfo.GetCultureInfo(name).CompareInfo;
}
public static unsafe bool IsSortable(char ch)
{
if (GlobalizationMode.Invariant)
{
return true;
}
char *pChar = &ch;
return IsSortable(pChar, 1);
}
public static unsafe bool IsSortable(string text)
{
if (text == null)
{
// A null param is invalid here.
throw new ArgumentNullException(nameof(text));
}
if (text.Length == 0)
{
// A zero length string is not invalid, but it is also not sortable.
return (false);
}
if (GlobalizationMode.Invariant)
{
return true;
}
fixed (char *pChar = text)
{
return IsSortable(pChar, text.Length);
}
}
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
m_name = null;
}
void IDeserializationCallback.OnDeserialization(object sender)
{
OnDeserialized();
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
OnDeserialized();
}
private void OnDeserialized()
{
// If we didn't have a name, use the LCID
if (m_name == null)
{
// From whidbey, didn't have a name
CultureInfo ci = CultureInfo.GetCultureInfo(this.culture);
m_name = ci._name;
}
else
{
InitSort(CultureInfo.GetCultureInfo(m_name));
}
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
{
// This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more.
culture = CultureInfo.GetCultureInfo(this.Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort)
Debug.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already");
}
///////////////////////////----- Name -----/////////////////////////////////
//
// Returns the name of the culture (well actually, of the sort).
// Very important for providing a non-LCID way of identifying
// what the sort is.
//
// Note that this name isn't dereferenced in case the CompareInfo is a different locale
// which is consistent with the behaviors of earlier versions. (so if you ask for a sort
// and the locale's changed behavior, then you'll get changed behavior, which is like
// what happens for a version update)
//
////////////////////////////////////////////////////////////////////////
public virtual string Name
{
get
{
Debug.Assert(m_name != null, "CompareInfo.Name Expected _name to be set");
if (m_name == "zh-CHT" || m_name == "zh-CHS")
{
return m_name;
}
return _sortName;
}
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the two strings with the given options. Returns 0 if the
// two strings are equal, a number less than 0 if string1 is less
// than string2, and a number greater than 0 if string1 is greater
// than string2.
//
////////////////////////////////////////////////////////////////////////
public virtual int Compare(string string1, string string2)
{
return (Compare(string1, string2, CompareOptions.None));
}
public unsafe virtual int Compare(string string1, string string2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
return String.Compare(string1, string2, StringComparison.OrdinalIgnoreCase);
}
// Verify the options before we do any real comparison.
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options));
}
return String.CompareOrdinal(string1, string2);
}
if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
//Our paradigm is that null sorts less than any other string and
//that two nulls sort as equal.
if (string1 == null)
{
if (string2 == null)
{
return (0); // Equal
}
return (-1); // null < non-null
}
if (string2 == null)
{
return (1); // non-null > null
}
if (_invariantMode)
{
if ((options & CompareOptions.IgnoreCase) != 0)
return CompareOrdinalIgnoreCase(string1, 0, string1.Length, string2, 0, string2.Length);
return String.CompareOrdinal(string1, string2);
}
return CompareString(string1.AsReadOnlySpan(), string2.AsReadOnlySpan(), options);
}
// TODO https://github.com/dotnet/coreclr/issues/13827:
// This method shouldn't be necessary, as we should be able to just use the overload
// that takes two spans. But due to this issue, that's adding significant overhead.
internal unsafe int Compare(ReadOnlySpan<char> string1, string string2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
return CompareOrdinalIgnoreCase(string1, string2.AsReadOnlySpan());
}
// Verify the options before we do any real comparison.
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options));
}
return string.CompareOrdinal(string1, string2.AsReadOnlySpan());
}
if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
// null sorts less than any other string.
if (string2 == null)
{
return 1;
}
if (_invariantMode)
{
return (options & CompareOptions.IgnoreCase) != 0 ?
CompareOrdinalIgnoreCase(string1, string2.AsReadOnlySpan()) :
string.CompareOrdinal(string1, string2.AsReadOnlySpan());
}
return CompareString(string1, string2, options);
}
// TODO https://github.com/dotnet/corefx/issues/21395: Expose this publicly?
internal unsafe virtual int Compare(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
return CompareOrdinalIgnoreCase(string1, string2);
}
// Verify the options before we do any real comparison.
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options));
}
return string.CompareOrdinal(string1, string2);
}
if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
if (_invariantMode)
{
return (options & CompareOptions.IgnoreCase) != 0 ?
CompareOrdinalIgnoreCase(string1, string2) :
string.CompareOrdinal(string1, string2);
}
return CompareString(string1, string2, options);
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the specified regions of the two strings with the given
// options.
// Returns 0 if the two strings are equal, a number less than 0 if
// string1 is less than string2, and a number greater than 0 if
// string1 is greater than string2.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2)
{
return Compare(string1, offset1, length1, string2, offset2, length2, 0);
}
public virtual int Compare(string string1, int offset1, string string2, int offset2, CompareOptions options)
{
return Compare(string1, offset1, string1 == null ? 0 : string1.Length - offset1,
string2, offset2, string2 == null ? 0 : string2.Length - offset2, options);
}
public virtual int Compare(string string1, int offset1, string string2, int offset2)
{
return Compare(string1, offset1, string2, offset2, 0);
}
public virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
int result = String.Compare(string1, offset1, string2, offset2, length1 < length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase);
if ((length1 != length2) && result == 0)
return (length1 > length2 ? 1 : -1);
return (result);
}
// Verify inputs
if (length1 < 0 || length2 < 0)
{
throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 < 0 || offset2 < 0)
{
throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 > (string1 == null ? 0 : string1.Length) - length1)
{
throw new ArgumentOutOfRangeException(nameof(string1), SR.ArgumentOutOfRange_OffsetLength);
}
if (offset2 > (string2 == null ? 0 : string2.Length) - length2)
{
throw new ArgumentOutOfRangeException(nameof(string2), SR.ArgumentOutOfRange_OffsetLength);
}
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal,
nameof(options));
}
}
else if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
//
// Check for the null case.
//
if (string1 == null)
{
if (string2 == null)
{
return (0);
}
return (-1);
}
if (string2 == null)
{
return (1);
}
if (options == CompareOptions.Ordinal)
{
return CompareOrdinal(string1, offset1, length1,
string2, offset2, length2);
}
if (_invariantMode)
{
if ((options & CompareOptions.IgnoreCase) != 0)
return CompareOrdinalIgnoreCase(string1, offset1, length1, string2, offset2, length2);
return CompareOrdinal(string1, offset1, length1, string2, offset2, length2);
}
return CompareString(
string1.AsReadOnlySpan().Slice(offset1, length1),
string2.AsReadOnlySpan().Slice(offset2, length2),
options);
}
private static int CompareOrdinal(string string1, int offset1, int length1, string string2, int offset2, int length2)
{
int result = String.CompareOrdinal(string1, offset1, string2, offset2,
(length1 < length2 ? length1 : length2));
if ((length1 != length2) && result == 0)
{
return (length1 > length2 ? 1 : -1);
}
return (result);
}
//
// CompareOrdinalIgnoreCase compare two string ordinally with ignoring the case.
// it assumes the strings are Ascii string till we hit non Ascii character in strA or strB and then we continue the comparison by
// calling the OS.
//
internal static unsafe int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB)
{
Debug.Assert(indexA + lengthA <= strA.Length);
Debug.Assert(indexB + lengthB <= strB.Length);
return CompareOrdinalIgnoreCase(strA.AsReadOnlySpan().Slice(indexA, lengthA), strB.AsReadOnlySpan().Slice(indexB, lengthB));
}
internal static unsafe int CompareOrdinalIgnoreCase(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB)
{
int length = Math.Min(strA.Length, strB.Length);
int range = length;
fixed (char* ap = &MemoryMarshal.GetReference(strA))
fixed (char* bp = &MemoryMarshal.GetReference(strB))
{
char* a = ap;
char* b = bp;
// in InvariantMode we support all range and not only the ascii characters.
char maxChar = (char) (GlobalizationMode.Invariant ? 0xFFFF : 0x80);
while (length != 0 && (*a <= maxChar) && (*b <= maxChar))
{
int charA = *a;
int charB = *b;
if (charA == charB)
{
a++; b++;
length--;
continue;
}
// uppercase both chars - notice that we need just one compare per char
if ((uint)(charA - 'a') <= 'z' - 'a') charA -= 0x20;
if ((uint)(charB - 'a') <= 'z' - 'a') charB -= 0x20;
// Return the (case-insensitive) difference between them.
if (charA != charB)
return charA - charB;
// Next char
a++; b++;
length--;
}
if (length == 0)
return strA.Length - strB.Length;
Debug.Assert(!GlobalizationMode.Invariant);
range -= length;
return CompareStringOrdinalIgnoreCase(a, strA.Length - range, b, strB.Length - range);
}
}
////////////////////////////////////////////////////////////////////////
//
// IsPrefix
//
// Determines whether prefix is a prefix of string. If prefix equals
// String.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
public virtual bool IsPrefix(string source, string prefix, CompareOptions options)
{
if (source == null || prefix == null)
{
throw new ArgumentNullException((source == null ? nameof(source) : nameof(prefix)),
SR.ArgumentNull_String);
}
if (prefix.Length == 0)
{
return (true);
}
if (source.Length == 0)
{
return false;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
}
if (options == CompareOptions.Ordinal)
{
return source.StartsWith(prefix, StringComparison.Ordinal);
}
if ((options & ValidIndexMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
if (_invariantMode)
{
return source.StartsWith(prefix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
return StartsWith(source, prefix, options);
}
public virtual bool IsPrefix(string source, string prefix)
{
return (IsPrefix(source, prefix, 0));
}
////////////////////////////////////////////////////////////////////////
//
// IsSuffix
//
// Determines whether suffix is a suffix of string. If suffix equals
// String.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
public virtual bool IsSuffix(string source, string suffix, CompareOptions options)
{
if (source == null || suffix == null)
{
throw new ArgumentNullException((source == null ? nameof(source) : nameof(suffix)),
SR.ArgumentNull_String);
}
if (suffix.Length == 0)
{
return (true);
}
if (source.Length == 0)
{
return false;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.EndsWith(suffix, StringComparison.OrdinalIgnoreCase);
}
if (options == CompareOptions.Ordinal)
{
return source.EndsWith(suffix, StringComparison.Ordinal);
}
if ((options & ValidIndexMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
if (_invariantMode)
{
return source.EndsWith(suffix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
return EndsWith(source, suffix, options);
}
public virtual bool IsSuffix(string source, string suffix)
{
return (IsSuffix(source, suffix, 0));
}
////////////////////////////////////////////////////////////////////////
//
// IndexOf
//
// Returns the first index where value is found in string. The
// search starts from startIndex and ends at endIndex. Returns -1 if
// the specified value is not found. If value equals String.Empty,
// startIndex is returned. Throws IndexOutOfRange if startIndex or
// endIndex is less than zero or greater than the length of string.
// Throws ArgumentException if value is null.
//
////////////////////////////////////////////////////////////////////////
public virtual int IndexOf(string source, char value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
public virtual int IndexOf(string source, string value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
public virtual int IndexOf(string source, char value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, options);
}
public virtual int IndexOf(string source, string value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, options);
}
public virtual int IndexOf(string source, char value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
public virtual int IndexOf(string source, string value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
public virtual int IndexOf(string source, char value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public virtual int IndexOf(string source, string value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public virtual int IndexOf(string source, char value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public virtual int IndexOf(string source, string value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public unsafe virtual int IndexOf(string source, char value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
if (source == null)
throw new ArgumentNullException(nameof(source));
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || startIndex > source.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.IndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase);
}
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
if (_invariantMode)
return IndexOfOrdinal(source, new string(value, 1), startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return IndexOfCore(source, new string(value, 1), startIndex, count, options, null);
}
public unsafe virtual int IndexOf(string source, string value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
if (source == null)
throw new ArgumentNullException(nameof(source));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex > source.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
// In Everett we used to return -1 for empty string even if startIndex is negative number so we keeping same behavior here.
// We return 0 if both source and value are empty strings for Everett compatibility too.
if (source.Length == 0)
{
if (value.Length == 0)
{
return 0;
}
return -1;
}
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
if (count < 0 || startIndex > source.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
if (_invariantMode)
return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return IndexOfCore(source, value, startIndex, count, options, null);
}
// The following IndexOf overload is mainly used by String.Replace. This overload assumes the parameters are already validated
// and the caller is passing a valid matchLengthPtr pointer.
internal unsafe int IndexOf(string source, string value, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
Debug.Assert(startIndex >= 0);
Debug.Assert(matchLengthPtr != null);
*matchLengthPtr = 0;
if (source.Length == 0)
{
if (value.Length == 0)
{
return 0;
}
return -1;
}
if (startIndex >= source.Length)
{
return -1;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
if (res >= 0)
{
*matchLengthPtr = value.Length;
}
return res;
}
if (_invariantMode)
{
int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
if (res >= 0)
{
*matchLengthPtr = value.Length;
}
return res;
}
return IndexOfCore(source, value, startIndex, count, options, matchLengthPtr);
}
internal int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
if (_invariantMode)
{
return InvariantIndexOf(source, value, startIndex, count, ignoreCase);
}
return IndexOfOrdinalCore(source, value, startIndex, count, ignoreCase);
}
////////////////////////////////////////////////////////////////////////
//
// LastIndexOf
//
// Returns the last index where value is found in string. The
// search starts from startIndex and ends at endIndex. Returns -1 if
// the specified value is not found. If value equals String.Empty,
// endIndex is returned. Throws IndexOutOfRange if startIndex or
// endIndex is less than zero or greater than the length of string.
// Throws ArgumentException if value is null.
//
////////////////////////////////////////////////////////////////////////
public virtual int LastIndexOf(String source, char value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1, source.Length, CompareOptions.None);
}
public virtual int LastIndexOf(string source, string value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, CompareOptions.None);
}
public virtual int LastIndexOf(string source, char value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, options);
}
public virtual int LastIndexOf(string source, string value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1, source.Length, options);
}
public virtual int LastIndexOf(string source, char value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
public virtual int LastIndexOf(string source, string value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
public virtual int LastIndexOf(string source, char value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
public virtual int LastIndexOf(string source, string value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
public virtual int LastIndexOf(string source, char value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
public virtual int LastIndexOf(string source, string value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
public virtual int LastIndexOf(string source, char value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
if (source == null)
throw new ArgumentNullException(nameof(source));
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
return -1;
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
{
startIndex--;
if (count > 0)
count--;
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.LastIndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase);
}
if (_invariantMode)
return InvariantLastIndexOf(source, new string(value, 1), startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return LastIndexOfCore(source, value.ToString(), startIndex, count, options);
}
public virtual int LastIndexOf(string source, string value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
if (source == null)
throw new ArgumentNullException(nameof(source));
if (value == null)
throw new ArgumentNullException(nameof(value));
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
return (value.Length == 0) ? 0 : -1;
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
{
startIndex--;
if (count > 0)
count--;
// If we are looking for nothing, just return 0
if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0)
return startIndex;
}
// 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
if (_invariantMode)
return InvariantLastIndexOf(source, value, startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return LastIndexOfCore(source, value, startIndex, count, options);
}
internal int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
if (_invariantMode)
{
return InvariantLastIndexOf(source, value, startIndex, count, ignoreCase);
}
return LastIndexOfOrdinalCore(source, value, startIndex, count, ignoreCase);
}
////////////////////////////////////////////////////////////////////////
//
// GetSortKey
//
// Gets the SortKey for the given string with the given options.
//
////////////////////////////////////////////////////////////////////////
public virtual SortKey GetSortKey(string source, CompareOptions options)
{
if (_invariantMode)
return InvariantCreateSortKey(source, options);
return CreateSortKey(source, options);
}
public virtual SortKey GetSortKey(string source)
{
if (_invariantMode)
return InvariantCreateSortKey(source, CompareOptions.None);
return CreateSortKey(source, CompareOptions.None);
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CompareInfo as the current
// instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
CompareInfo that = value as CompareInfo;
if (that != null)
{
return this.Name == that.Name;
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CompareInfo. The hash code is guaranteed to be the same for
// CompareInfo A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.Name.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCodeOfString
//
// This internal method allows a method that allows the equivalent of creating a Sortkey for a
// string from CompareInfo, and generate a hashcode value from it. It is not very convenient
// to use this method as is and it creates an unnecessary Sortkey object that will be GC'ed.
//
// The hash code is guaranteed to be the same for string A and B where A.Equals(B) is true and both
// the CompareInfo and the CompareOptions are the same. If two different CompareInfo objects
// treat the string the same way, this implementation will treat them differently (the same way that
// Sortkey does at the moment).
//
// This method will never be made public itself, but public consumers of it could be created, e.g.:
//
// string.GetHashCode(CultureInfo)
// string.GetHashCode(CompareInfo)
// string.GetHashCode(CultureInfo, CompareOptions)
// string.GetHashCode(CompareInfo, CompareOptions)
// etc.
//
// (the methods above that take a CultureInfo would use CultureInfo.CompareInfo)
//
////////////////////////////////////////////////////////////////////////
internal int GetHashCodeOfString(string source, CompareOptions options)
{
//
// Parameter validation
//
if (null == source)
{
throw new ArgumentNullException(nameof(source));
}
if ((options & ValidHashCodeOfStringMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
return GetHashCodeOfStringCore(source, options);
}
public virtual int GetHashCode(string source, CompareOptions options)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (options == CompareOptions.Ordinal)
{
return source.GetHashCode();
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return TextInfo.GetHashCodeOrdinalIgnoreCase(source);
}
//
// GetHashCodeOfString does more parameters validation. basically will throw when
// having Ordinal, OrdinalIgnoreCase and StringSort
//
return GetHashCodeOfString(source, options);
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// CompareInfo.
//
////////////////////////////////////////////////////////////////////////
public override string ToString()
{
return ("CompareInfo - " + this.Name);
}
public SortVersion Version
{
get
{
if (m_SortVersion == null)
{
if (_invariantMode)
{
m_SortVersion = new SortVersion(0, CultureInfo.LOCALE_INVARIANT, new Guid(0, 0, 0, 0, 0, 0, 0,
(byte) (CultureInfo.LOCALE_INVARIANT >> 24),
(byte) ((CultureInfo.LOCALE_INVARIANT & 0x00FF0000) >> 16),
(byte) ((CultureInfo.LOCALE_INVARIANT & 0x0000FF00) >> 8),
(byte) (CultureInfo.LOCALE_INVARIANT & 0xFF)));
}
else
{
m_SortVersion = GetSortVersion();
}
}
return m_SortVersion;
}
}
public int LCID
{
get
{
return CultureInfo.GetCultureInfo(Name).LCID;
}
}
}
}
| |
// AGUITextEditor.cs
//
// Author:
// Atte Vuorinen <[email protected]>
//
// Copyright (c) 2014 Atte Vuorinen
//
// 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 UnityEditor;
using UnityEngine;
using System.Text.RegularExpressions;
[CustomEditor(typeof(AGUIText))]
public class AGUITextEditor : Editor
{
private const float MAX_SIZE = 100;
public Color color = Color.white;
public float fontSize = 15;
public override void OnInspectorGUI ()
{
AGUIText aText = (AGUIText)target;
base.OnInspectorGUI ();
GUIStyle textAreaStyle = new GUIStyle(GUI.skin.textArea);
textAreaStyle.richText = true;
GUIStyle buttonStyle = new GUIStyle(GUI.skin.button);
buttonStyle.richText = true;
//GUI//
EditorGUILayout.Separator();
string noSizeText = aText.text;
noSizeText = Regex.Replace(noSizeText,"</size>","",RegexOptions.IgnoreCase);
noSizeText = Regex.Replace(noSizeText,"<size=(.*?)>","",RegexOptions.IgnoreCase);
EditorGUILayout.LabelField("Preview");
EditorGUILayout.TextArea(noSizeText,textAreaStyle);
EditorGUILayout.Separator();
EditorGUILayout.LabelField("Edit");
aText.text = EditorGUILayout.TextArea(aText.text);
//Size
GUILayout.BeginHorizontal();
fontSize = EditorGUILayout.FloatField("Size",fontSize);
if(GUILayout.Button("Size"))
{
aText.text += "<size=" + fontSize + ">Size</size>";
Repaint();
EditorUtility.SetDirty (target);
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if(GUILayout.Button("<b>Bold</b>",buttonStyle))
{
aText.text += "<b>Bold</b>";
Repaint();
EditorUtility.SetDirty (target);
}
if(GUILayout.Button("<i>Italic</i>",buttonStyle))
{
aText.text += "<i>Italic</i>";
Repaint();
EditorUtility.SetDirty (target);
}
GUILayout.EndHorizontal();
//Color
GUILayout.BeginHorizontal();
color = EditorGUILayout.ColorField(color);
if(GUILayout.Button("<color=#" + ColorToHex(color) + ">Color</color>",buttonStyle))
{
aText.text += "<color=#" + ColorToHex(color) + ">Color</color>";
Repaint();
}
GUILayout.EndHorizontal();
//TAGS
//Style
GUILayout.BeginHorizontal();
//TODO: Better design for this.
if(GUILayout.Button("<b>"))
{
aText.text += "<b>";
Repaint();
EditorUtility.SetDirty (target);
}
if(GUILayout.Button("</b>"))
{
aText.text += "</b>";
Repaint();
EditorUtility.SetDirty (target);
}
if(GUILayout.Button("<i>"))
{
aText.text += "<i>";
Repaint();
EditorUtility.SetDirty (target);
}
if(GUILayout.Button("</i>"))
{
aText.text += "</i>";
Repaint();
EditorUtility.SetDirty (target);
}
GUILayout.EndHorizontal();
//Size
GUILayout.BeginHorizontal();
if(GUILayout.Button("<size>"))
{
aText.text += "<size=" + fontSize + ">";
Repaint();
EditorUtility.SetDirty (target);
}
if(GUILayout.Button("</size>"))
{
aText.text += "</size>";
Repaint();
EditorUtility.SetDirty (target);
}
GUILayout.EndHorizontal();
//Color
GUILayout.BeginHorizontal();
if(GUILayout.Button("<color>"))
{
aText.text += "<color=#" + ColorToHex(color) + ">";
Repaint();
EditorUtility.SetDirty (target);
}
if(GUILayout.Button("</color>"))
{
aText.text += "</color>";
Repaint();
EditorUtility.SetDirty (target);
}
GUILayout.EndHorizontal();
}
string ColorToHex(Color32 color)
{
string hex = color.r.ToString("X2") + color.g.ToString("X2") + color.b.ToString("X2") + color.a.ToString("X2");
return hex;
}
Color HexToColor(string hex)
{
byte r = byte.Parse(hex.Substring(0,2), System.Globalization.NumberStyles.HexNumber);
byte g = byte.Parse(hex.Substring(2,2), System.Globalization.NumberStyles.HexNumber);
byte b = byte.Parse(hex.Substring(4,2), System.Globalization.NumberStyles.HexNumber);
byte a = byte.Parse(hex.Substring(6,2), System.Globalization.NumberStyles.HexNumber);
return new Color32(r,g,b,a);
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Collections.Generic;
namespace Noesis
{
public partial class DependencyProperty
{
public static DependencyProperty Register(string name, System.Type propertyType,
System.Type ownerType)
{
return RegisterCommon(name, propertyType, ownerType, null);
}
public static DependencyProperty Register(string name, System.Type propertyType,
System.Type ownerType, PropertyMetadata propertyMetadata)
{
return RegisterCommon(name, propertyType, ownerType, propertyMetadata);
}
public static DependencyProperty RegisterAttached(string name, System.Type propertyType,
System.Type ownerType)
{
return RegisterCommon(name, propertyType, ownerType, null);
}
public static DependencyProperty RegisterAttached(string name, System.Type propertyType,
System.Type ownerType, PropertyMetadata propertyMetadata)
{
return RegisterCommon(name, propertyType, ownerType, propertyMetadata);
}
public void OverrideMetadata(System.Type forType, PropertyMetadata propertyMetadata)
{
IntPtr forTypePtr = Noesis.Extend.EnsureNativeType(forType, false);
Noesis_OverrideMetadata_(forTypePtr, swigCPtr.Handle,
PropertyMetadata.getCPtr(propertyMetadata).Handle);
}
internal static bool RegisterCalled { get; set; }
#region Register implementation
private static DependencyProperty RegisterCommon(string name, System.Type propertyType,
System.Type ownerType, PropertyMetadata propertyMetadata)
{
ValidateParams(name, propertyType, ownerType);
// Force native type registration, but skip DP registration because we are inside
// static constructor and DP are already being registered
IntPtr ownerTypePtr = Noesis.Extend.EnsureNativeType(ownerType, false);
// Check property type is supported and get the registered native type
Type originalPropertyType = propertyType;
IntPtr nativeType = ValidatePropertyType(ref propertyType);
// Create and register dependency property
IntPtr dependencyPtr = Noesis_RegisterDependencyProperty_(ownerTypePtr,
name, nativeType, PropertyMetadata.getCPtr(propertyMetadata).Handle);
DependencyProperty dependencyProperty = new DependencyProperty(dependencyPtr, false);
dependencyProperty.OriginalPropertyType = originalPropertyType;
RegisterCalled = true;
return dependencyProperty;
}
private static void ValidateParams(string name, System.Type propertyType,
System.Type ownerType)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (name.Length == 0)
{
throw new ArgumentException("Property name can't be empty");
}
if (ownerType == null)
{
throw new ArgumentNullException("ownerType");
}
if (propertyType == null)
{
throw new ArgumentNullException("propertyType");
}
}
private Type OriginalPropertyType { get; set; }
private static IntPtr ValidatePropertyType(ref Type propertyType)
{
Type validType;
if (_validTypes.TryGetValue(propertyType.TypeHandle, out validType))
{
propertyType = validType;
}
return Noesis.Extend.EnsureNativeType(propertyType);
}
private static Dictionary<RuntimeTypeHandle, Type> _validTypes = CreateValidTypes();
private static Dictionary<RuntimeTypeHandle, Type> CreateValidTypes()
{
Dictionary<RuntimeTypeHandle, Type> validTypes = new Dictionary<RuntimeTypeHandle, Type>(13);
validTypes[typeof(decimal).TypeHandle] = typeof(double);
validTypes[typeof(long).TypeHandle] = typeof(int);
validTypes[typeof(ulong).TypeHandle] = typeof(uint);
validTypes[typeof(char).TypeHandle] = typeof(uint);
validTypes[typeof(sbyte).TypeHandle] = typeof(short);
validTypes[typeof(byte).TypeHandle] = typeof(ushort);
validTypes[typeof(decimal?).TypeHandle] = typeof(double?);
validTypes[typeof(long?).TypeHandle] = typeof(int?);
validTypes[typeof(ulong?).TypeHandle] = typeof(uint?);
validTypes[typeof(char?).TypeHandle] = typeof(uint?);
validTypes[typeof(sbyte?).TypeHandle] = typeof(short?);
validTypes[typeof(byte?).TypeHandle] = typeof(ushort?);
validTypes[typeof(Type).TypeHandle] = typeof(ResourceKeyType);
return validTypes;
}
#endregion
#region Imports
private static IntPtr Noesis_RegisterDependencyProperty_(IntPtr classType,
string propertyName, IntPtr propertyType, IntPtr propertyMetadata)
{
IntPtr result = Noesis_RegisterDependencyProperty(classType, propertyName, propertyType, propertyMetadata);
#if UNITY_EDITOR || NOESIS_API
Error.Check();
#endif
return result;
}
private static void Noesis_OverrideMetadata_(IntPtr classType, IntPtr dependencyProperty,
IntPtr propertyMetadata)
{
Noesis_OverrideMetadata(classType, dependencyProperty, propertyMetadata);
#if UNITY_EDITOR || NOESIS_API
Error.Check();
#endif
}
#if UNITY_EDITOR
////////////////////////////////////////////////////////////////////////////////////////////////
public static void RegisterFunctions(Library lib)
{
// register DependencyProperty
_RegisterDependencyProperty = lib.Find<RegisterDependencyPropertyDelegate>(
"Noesis_RegisterDependencyProperty");
// override PropertyMetadata
_OverrideMetadata = lib.Find<OverrideMetadataDelegate>("Noesis_OverrideMetadata");
}
////////////////////////////////////////////////////////////////////////////////////////////////
public static void UnregisterFunctions()
{
// register DependencyProperty
_RegisterDependencyProperty = null;
_OverrideMetadata = null;
}
////////////////////////////////////////////////////////////////////////////////////////////////
delegate IntPtr RegisterDependencyPropertyDelegate(IntPtr classType,
[MarshalAs(UnmanagedType.LPStr)]string propertyName, IntPtr propertyType,
IntPtr propertyMetadata);
static RegisterDependencyPropertyDelegate _RegisterDependencyProperty;
private static IntPtr Noesis_RegisterDependencyProperty(IntPtr classType,
string propertyName, IntPtr propertyType, IntPtr propertyMetadata)
{
return _RegisterDependencyProperty(classType, propertyName, propertyType,
propertyMetadata);
}
////////////////////////////////////////////////////////////////////////////////////////////////
delegate void OverrideMetadataDelegate(IntPtr classType, IntPtr dependencyProperty,
IntPtr propertyMetadata);
static OverrideMetadataDelegate _OverrideMetadata;
private static void Noesis_OverrideMetadata(IntPtr classType, IntPtr dependencyProperty,
IntPtr propertyMetadata)
{
_OverrideMetadata(classType, dependencyProperty, propertyMetadata);
}
#else
////////////////////////////////////////////////////////////////////////////////////////////////
#if UNITY_IPHONE || UNITY_XBOX360
[DllImport("__Internal", EntryPoint="Noesis_RegisterDependencyProperty")]
#else
[DllImport("Noesis", EntryPoint = "Noesis_RegisterDependencyProperty")]
#endif
private static extern IntPtr Noesis_RegisterDependencyProperty(IntPtr classType,
[MarshalAs(UnmanagedType.LPStr)]string propertyName, IntPtr propertyType,
IntPtr propertyMetadata);
////////////////////////////////////////////////////////////////////////////////////////////////
#if UNITY_IPHONE || UNITY_XBOX360
[DllImport("__Internal", EntryPoint="Noesis_OverrideMetadata")]
#else
[DllImport("Noesis", EntryPoint = "Noesis_OverrideMetadata")]
#endif
private static extern void Noesis_OverrideMetadata(IntPtr classType,
IntPtr dependencyProperty, IntPtr propertyMetadata);
#endif
#endregion
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Web;
using System.Web.Caching;
using System.Web.SessionState;
using Common.Logging;
using Spring.Collections;
using Spring.Context.Attributes;
using Spring.Context.Support;
using Spring.Objects.Factory.Config;
using Spring.Util;
#endregion
namespace Spring.Objects.Factory.Support
{
/// <summary>
/// Concrete implementation of
/// <see cref="Spring.Objects.Factory.IListableObjectFactory"/> that knows
/// how to handle <see cref="IWebObjectDefinition"/>s.
/// </summary>
/// <remarks>
/// <p>
/// This class should only be used within the context of an ASP.NET web application.
/// </p>
/// </remarks>
/// <author>Aleksandar Seovic</author>
public class WebObjectFactory : DefaultListableObjectFactory
{
private readonly static ILog log = LogManager.GetLogger(typeof(WebObjectFactory));
private static bool s_eventHandlersRegistered = false;
private readonly static string OBJECTTABLEKEY = "spring.objects";
private delegate IDictionary ObjectDictionaryCreationHandler();
/// <summary>
/// Holds the virtual path this factory has been created from.
/// </summary>
private readonly string contextPath;
/// <summary>
/// Holds the handler reference for creating an object dictionary
/// matching this factory's case-sensitivity
/// </summary>
private readonly ObjectDictionaryCreationHandler createObjectDictionary;
#region Constructor (s) / Destructor
static WebObjectFactory()
{
//EnsureEventHandlersRegistered();
}
/// <summary>
/// Registers events handlers with <see cref="WebSupportModule"/> to ensure
/// proper disposal of 'request'- and 'session'-scoped objects
/// </summary>
private static void EnsureEventHandlersRegistered()
{
if (!s_eventHandlersRegistered)
{
lock(typeof(WebObjectFactory))
{
if (s_eventHandlersRegistered) return;
if (log.IsDebugEnabled) log.Debug("hooking up event handlers");
VirtualEnvironment.EndRequest += OnEndRequest;
VirtualEnvironment.EndSession += OnEndSession;
s_eventHandlersRegistered = true;
}
}
}
/// <summary>
/// Creates a new instance of the
/// <see cref="Spring.Objects.Factory.Support.WebObjectFactory"/> class.
/// </summary>
/// <param name="contextPath">The virtual path resources will be relative resolved to.</param>
/// <param name="caseSensitive">Flag specifying whether to make this object factory case sensitive or not.</param>
public WebObjectFactory(string contextPath, bool caseSensitive)
: this(contextPath, caseSensitive, null)
{
}
/// <summary>
/// Creates a new instance of the
/// <see cref="Spring.Objects.Factory.Support.WebObjectFactory"/> class.
/// </summary>
/// <param name="contextPath">The virtual path resources will be relative resolved to.</param>
/// <param name="caseSensitive">Flag specifying whether to make this object factory case sensitive or not.</param>
/// <param name="parentFactory">
/// The parent object factory.
/// </param>
public WebObjectFactory(string contextPath, bool caseSensitive, IObjectFactory parentFactory)
: base(caseSensitive, parentFactory)
{
this.contextPath = contextPath;
this.createObjectDictionary = (caseSensitive)
? new ObjectDictionaryCreationHandler(CreateCaseSensitiveDictionary)
: new ObjectDictionaryCreationHandler(CreateCaseInsensitiveDictionary);
InstantiationStrategy = new WebInstantiationStrategy();
}
#endregion
/// <summary>
/// Returns the virtual path this object factory is associated with.
/// </summary>
public string ContextPath
{
get { return contextPath; }
}
#region Convenience accessors for Http* objects
/// <summary>
/// Convinience accessor for HttpContext
/// </summary>
private HttpContext Context
{
get { return HttpContext.Current; }
}
/// <summary>
/// Get the table of 'request'-scoped objects.
/// </summary>
protected virtual IDictionary Request
{
get
{
IDictionary objecttable = null;
if (this.Context != null)
{
objecttable = this.Context.Items[OBJECTTABLEKEY] as IDictionary;
if (objecttable == null)
{
this.Context.Items[OBJECTTABLEKEY] = CreateObjectDictionary();
}
}
return objecttable;
}
}
/// <summary>
/// Get the table of 'session'-scoped objects. Returns null, if Session is disabled.
/// </summary>
protected virtual IDictionary Session
{
get
{
IDictionary objecttable = null;
if ((Context != null) && (Context.Session != null))
{
objecttable = Context.Session[OBJECTTABLEKEY] as IDictionary;
if (objecttable == null)
{
Context.Session[OBJECTTABLEKEY] = CreateObjectDictionary();
}
}
return objecttable;
}
}
#endregion
/// <summary>
/// Creates a dictionary matching this factory's case sensitivity behaviour.
/// </summary>
protected IDictionary CreateObjectDictionary()
{
return createObjectDictionary();
}
/// <summary>
/// Creates the root object definition.
/// </summary>
/// <param name="templateDefinition">The template definition.</param>
/// <returns>Root object definition.</returns>
protected override RootObjectDefinition CreateRootObjectDefinition(IObjectDefinition templateDefinition)
{
return new RootWebObjectDefinition(templateDefinition);
}
/// <summary>
/// Tries to find cached object for the specified name.
/// </summary>
/// <remarks>
/// This implementation tries to find object first in the Request scope,
/// then in the Session scope and finally in the Application scope.
/// </remarks>
/// <param name="objectName">Object name to look for.</param>
/// <returns>Cached object if found, null otherwise.</returns>
public override object GetSingleton(string objectName)
{
object instance = null;
instance = GetScopedSingleton(objectName, this.Request);
if (instance != null) return instance;
instance = GetScopedSingleton(objectName, this.Session);
if (instance != null) return instance;
instance = base.GetSingleton(objectName);
return instance;
}
/// <summary>
/// Looks up an <paramref name="objectName"/> in the specified cache dictionary.
/// </summary>
/// <param name="objectName">the name to lookup.</param>
/// <param name="scopedSingletonCache">the cache dictionary to search</param>
/// <returns>the found instance. null otherwise</returns>
protected object GetScopedSingleton(string objectName, IDictionary scopedSingletonCache)
{
if (scopedSingletonCache == null) return null;
lock (scopedSingletonCache.SyncRoot)
{
object instance = scopedSingletonCache[objectName];
if (instance == TemporarySingletonPlaceHolder)
{
throw new ObjectCurrentlyInCreationException(objectName);
}
return instance;
}
}
/// <summary>
/// Creates a singleton instance for the specified object name and definition.
/// </summary>
/// <param name="objectName">
/// The object name (will be used as the key in the singleton cache key).
/// </param>
/// <param name="objectDefinition">The object definition.</param>
/// <param name="arguments">
/// The arguments to use if creating a prototype using explicit arguments to
/// a static factory method. It is invalid to use a non-null arguments value
/// in any other case.
/// </param>
/// <returns>The created object instance.</returns>
protected override object CreateAndCacheSingletonInstance(
string objectName, RootObjectDefinition objectDefinition, object[] arguments)
{
if (IsWebScopedSingleton(objectDefinition))
{
ObjectScope scope = GetObjectScope(objectDefinition);
if (scope == ObjectScope.Request)
{
IDictionary requestCache = this.Request;
if (requestCache == null)
{
throw new ObjectCreationException(string.Format("'request' scoped web singleton object '{0}' requires a valid Request.", objectName));
}
object instance = CreateAndCacheScopedSingletonInstance(objectName, objectDefinition, arguments, requestCache);
return instance;
}
else if (scope == ObjectScope.Session)
{
IDictionary sessionCache = this.Session;
if (sessionCache == null)
{
throw new ObjectCreationException(string.Format("'session' scoped web singleton object '{0}' requires a valid Session.", objectName));
}
object instance = CreateAndCacheScopedSingletonInstance(objectName, objectDefinition, arguments, sessionCache);
return instance;
}
throw new ObjectDefinitionException("Web singleton objects must be either request, session or application scoped.");
}
return base.CreateAndCacheSingletonInstance(objectName, objectDefinition, arguments);
}
/// <summary>
/// Creates a singleton instance for the specified object name and definition
/// and caches the instance in the specified dictionary
/// </summary>
/// <param name="objectName">
/// The object name (will be used as the key in the singleton cache key).
/// </param>
/// <param name="objectDefinition">The object definition.</param>
/// <param name="arguments">
/// The arguments to use if creating a prototype using explicit arguments to
/// a static factory method. It is invalid to use a non-null arguments value
/// in any other case.
/// </param>
/// <param name="scopedSingletonCache">the dictionary to be used for caching singleton instances</param>
/// <returns>The created object instance.</returns>
/// <remarks>
/// If the object is successfully created, <paramref name="scopedSingletonCache"/>
/// contains the cached instance with the key <paramref name="objectName"/>.
/// </remarks>
protected virtual object CreateAndCacheScopedSingletonInstance(string objectName, RootObjectDefinition objectDefinition, object[] arguments, IDictionary scopedSingletonCache)
{
object instance;
lock (scopedSingletonCache.SyncRoot)
{
EnsureEventHandlersRegistered();
instance = scopedSingletonCache[objectName];
if (instance == TemporarySingletonPlaceHolder)
{
throw new ObjectCurrentlyInCreationException(objectName);
}
else if (instance == null)
{
scopedSingletonCache.Add(objectName, TemporarySingletonPlaceHolder);
try
{
instance = InstantiateObject(objectName, objectDefinition, arguments, true, false);
AssertUtils.ArgumentNotNull(instance, "instance");
scopedSingletonCache[objectName] = instance;
}
catch
{
scopedSingletonCache.Remove(objectName);
throw;
}
}
}
return instance;
}
/// <summary>
/// We need this override so that Web Scoped Singletons are not registered in general
/// DisposalObjectRegister
/// </summary>
/// <param name="name"></param>
/// <param name="instance"></param>
/// <param name="objectDefinition"></param>
protected override void RegisterDisposableObjectIfNecessary(string name, object instance,
RootObjectDefinition objectDefinition)
{
if (!IsWebScopedSingleton(objectDefinition))
{
base.RegisterDisposableObjectIfNecessary(name, instance, objectDefinition);
}
}
/// <summary>
/// Add the created, but yet unpopulated singleton to the singleton cache
/// to be able to resolve circular references
/// </summary>
/// <param name="objectName">the name of the object to add to the cache.</param>
/// <param name="objectDefinition">the definition used to create and populated the object.</param>
/// <param name="rawSingletonInstance">the raw object instance.</param>
/// <remarks>
/// Derived classes may override this method to select the right cache based on the object definition.
/// </remarks>
protected override void AddEagerlyCachedSingleton(string objectName, IObjectDefinition objectDefinition, object rawSingletonInstance)
{
if (IsWebScopedSingleton(objectDefinition))
{
ObjectScope scope = GetObjectScope(objectDefinition);
if (scope == ObjectScope.Request)
{
this.Request[objectName] = rawSingletonInstance;
}
else if (scope == ObjectScope.Session)
{
this.Session[objectName] = rawSingletonInstance;
}
else
{
throw new ObjectDefinitionException("Web singleton objects must be either request, session or application scoped.");
}
}
else
{
base.AddEagerlyCachedSingleton(objectName, objectDefinition, rawSingletonInstance);
}
}
/// <summary>
/// Remove the specified singleton from the singleton cache that has
/// been added before by a call to <see cref="AddEagerlyCachedSingleton"/>
/// </summary>
/// <param name="objectName">the name of the object to remove from the cache.</param>
/// <param name="objectDefinition">the definition used to create and populated the object.</param>
/// <remarks>
/// Derived classes may override this method to select the right cache based on the object definition.
/// </remarks>
protected override void RemoveEagerlyCachedSingleton(string objectName, IObjectDefinition objectDefinition)
{
if (IsWebScopedSingleton(objectDefinition))
{
ObjectScope scope = GetObjectScope(objectDefinition);
if (scope == ObjectScope.Request)
{
this.Request.Remove(objectName);
}
else if (scope == ObjectScope.Session)
{
this.Session.Remove(objectName);
}
else
{
throw new ObjectDefinitionException("Web singleton objects must be either 'request' or 'session' scoped.");
}
}
else
{
base.RemoveEagerlyCachedSingleton(objectName, objectDefinition);
}
}
private bool IsWebScopedSingleton(IObjectDefinition objectDefinition)
{
if (objectDefinition.IsSingleton &&
(objectDefinition is IWebObjectDefinition || objectDefinition is ScannedGenericObjectDefinition))
{
ObjectScope scope = GetObjectScope(objectDefinition);
return (scope == ObjectScope.Request) || (scope == ObjectScope.Session);
}
return false;
}
private ObjectScope GetObjectScope(IObjectDefinition objectDefinition)
{
if (objectDefinition is IWebObjectDefinition)
{
return ((IWebObjectDefinition) objectDefinition).Scope;
}
ObjectScope scope = (ObjectScope) Enum.Parse(typeof (ObjectScope), objectDefinition.Scope, true);
return scope;
}
/// <summary>
/// Configures object instance by injecting dependencies, satisfying Spring lifecycle
/// interfaces and applying object post-processors.
/// </summary>
/// <param name="name">
/// The name of the object definition expressing the dependencies that are to
/// be injected into the supplied <parameref name="target"/> instance.
/// </param>
/// <param name="definition">
/// An object definition that should be used to configure object.
/// </param>
/// <param name="wrapper">
/// A wrapped object instance that is to be so configured.
/// </param>
/// <seealso cref="Spring.Objects.Factory.IObjectFactory.ConfigureObject(object, string)"/>
protected override object ConfigureObject(string name, RootObjectDefinition definition, IObjectWrapper wrapper)
{
// always configure object relative to contextPath
using (new HttpContextSwitch(contextPath))
{
return base.ConfigureObject(name, definition, wrapper);
}
}
/// <summary>
/// Disposes all 'request'-scoped objects at the end of each Request
/// </summary>
private static void OnEndRequest(HttpContext context)
{
IDictionary items = context.Items[OBJECTTABLEKEY] as IDictionary;
if (items != null)
{
log.Debug("disposing 'request'-scoped item cache");
ArrayList keys = new ArrayList(items.Keys);
for (int i = 0; i < keys.Count; i++)
{
IDisposable d = items[keys[i]] as IDisposable;
if (d != null)
{
d.Dispose();
}
}
}
}
/// <summary>
/// Disposes all 'session'-scoped objects at the end of a session
/// </summary>
private static void OnEndSession(HttpSessionState session, CacheItemRemovedReason reason)
{
IDictionary items = null;
try
{
items = session[OBJECTTABLEKEY] as IDictionary;
}
catch
{
// ignore exceptions while accessing session
}
if (items != null)
{
log.Debug("disposing 'session'-scoped item cache");
object key = null;
try
{
ArrayList keys = new ArrayList(items.Keys);
for (int i = 0; i < keys.Count; i++)
{
key = keys[i];
IDisposable d = items[key] as IDisposable;
if (d != null)
{
d.Dispose();
}
}
}
catch (Exception ex)
{
log.Fatal(string.Format("error during disposing session item with key '{0}'", key), ex);
}
}
}
/// <summary>
/// Creates a case insensitive hashtable instance
/// </summary>
private static IDictionary CreateCaseInsensitiveDictionary()
{
return new CaseInsensitiveHashtable(); //CollectionsUtil.CreateCaseInsensitiveHashtable();
}
/// <summary>
/// Creates a case sensitive hashtable instance
/// </summary>
private static IDictionary CreateCaseSensitiveDictionary()
{
return new Hashtable();
}
}
}
| |
using System;
using System.Drawing;
using System.ComponentModel;
using GuruComponents.Netrix.ComInterop;
using GuruComponents.Netrix.VmlDesigner.DataTypes;
using Comzept.Genesis.NetRix.VgxDraw;
using System.Web.UI.WebControls;
using GuruComponents.Netrix;
namespace GuruComponents.Netrix.VmlDesigner.Elements
{
/// <summary>
/// Defines an extrusion for a shape.
/// </summary>
[ToolboxItem(false)]
public class ExtrusionElement : BaseShapeElement
{
/// <summary>
/// Determines whether the center of rotation will be the geometric center of the extrusion.
/// </summary>
public TriState AutoRotationCenter
{
get
{
return (TriState) base.GetEnumAttribute("AutoRotationCenter", TriState.False);
}
set
{
SetEnumAttribute("AutoRotationCenter", (VgTriState)(int)value, VgTriState.vgTriStateFalse);
}
}
///// <summary>
///// Defines the amount of backward extrusion.
///// </summary>
//public int BackDepth
//{
// get
// {
// }
// set
// {
// }
//}
/// <summary>
/// Specifies the amount of brightness of a scene.
/// </summary>
[DefaultValue(20000)]
public int Brightness
{
get
{
return base.GetIntegerAttribute("brightness", 20000);
}
set
{
base.SetIntegerAttribute("brightness", value, 20000);
}
}
/// <summary>
/// Defines the color of the extrusion faces.
/// </summary>
[TypeConverterAttribute(typeof(GuruComponents.Netrix.UserInterface.TypeConverters.UITypeConverterColor))]
[EditorAttribute(
typeof(GuruComponents.Netrix.UserInterface.TypeEditors.UITypeEditorColor),
typeof(System.Drawing.Design.UITypeEditor))]
public System.Drawing.Color Color
{
get
{
return base.GetColorAttribute("color");
}
set
{
base.SetColorAttribute("color", value);
}
}
/// <summary>
/// Determines the mode of extrusion color.
/// </summary>
public ThreeDColorMode ColorMode
{
get
{
return (ThreeDColorMode) base.GetEnumAttribute("colormode", Vg3DColorMode.vg3DColorModeAuto);
}
set
{
base.SetEnumAttribute("colormode", (Vg3DColorMode) (int) value, Vg3DColorMode.vg3DColorModeAuto);
}
}
/// <summary>
/// Defines the amount of diffusion of reflected light from an extruded shape.
/// </summary>
public bool Diffusity
{
get
{
return base.GetBooleanAttribute("diffusity");
}
set
{
base.SetBooleanAttribute("diffusity", value);
}
}
/// <summary>
/// Defines the apparent bevel of the extrusion edges.
/// </summary>
/// <remarks>
/// Sets the size of a simulated rounded beveled edge. Ranges from 0 to 32767 in floating point pts. Default is "1pt".
/// </remarks>
[DefaultValue(typeof(Unit), "1pt")]
public Unit Edge
{
get
{
return base.GetUnitAttribute("edge");
}
set
{
if (value.Value > 32767D || value.Value < 0D)
throw new ArgumentException("Edge requires a value between 0 and 32767 floating point pts.");
base.SetUnitAttribute("edge", value);
}
}
/// <summary>
/// Defines the default extrusion behavior for graphical editors.
/// </summary>
public bool Ext
{
get
{
return base.GetBooleanAttribute("ext");
}
set
{
base.SetBooleanAttribute("ext", value);
}
}
///// <summary>
///// Defines the number of facets used to describe curved surfaces of an extrusion.
///// </summary>
//public bool Facet
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Defines the amount of forward extrusion.
///// </summary>
//public bool ForeDepth
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Determines whether the front face of the extrusion will respond to changes in the lighting.
///// </summary>
//public bool LightFace
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Determines whether the primary light source will be harsh.
///// </summary>
//public bool LightHarsh
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Determines whether the secondary light source will be harsh.
///// </summary>
//public bool LightHarsh2
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Defines the intensity of the primary light source for the scene.
///// </summary>
//public bool LightLevel
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Defines the intensity of the secondary light source for the scene.
///// </summary>
//public bool LightLevel2
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Specifies the position of the primary light in a scene.
///// </summary>
//public bool LightPosition
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Specifies the position of the secondary light in a scene.
///// </summary>
//public bool LightPosition2
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Determines whether the rotation of the extruded object is specified by the RotationAngle attribute.
///// </summary>
//public bool LockRotationCenter
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Determines whether the surface of the extruded shape will resemble metal.
///// </summary>
//public bool Metal
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Determines whether an extrusion will be displayed.
///// </summary>
//public bool On
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Specifies the vector around which a shape will be rotated.
///// </summary>
//public bool Orientation
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Defines the angle that an extrusion rotates around the orientation.
///// </summary>
//public bool OrientationAngle
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Specifies the plane that is at right angles to the extrusion.
///// </summary>
//public bool Plane
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Defines the rendering mode of the extrusion.
///// </summary>
//public bool Render
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Specifies the rotation of the object about the x- and y-axes.
///// </summary>
//public bool RotationAngle
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Specifies the center of rotation for a shape.
///// </summary>
//public bool RotationCenter
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Defines the concentration of reflected light of an extrusion surface.
///// </summary>
//public bool Shininess
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Defines the amount of skew of an extrusion.
///// </summary>
//public bool SkewAmt
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Defines the angle of skew of an extrusion.
///// </summary>
//public bool SkewAngle
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Defines the specularity of an extruded shape.
///// </summary>
//public bool Specularity
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Defines the way that the shape is extruded.
///// </summary>
//public bool Type
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Defines the viewpoint of the observer.
///// </summary>
//public bool Viewpoint
//{
// get
// {
// }
// set
// {
// }
//}
///// <summary>
///// Defines the origin of the viewpoint within the bounding box of the shape.
///// </summary>
//public bool ViewpointOrigin
//{
// get
// {
// }
// set
// {
// }
//}
public ExtrusionElement(VmlBaseElement peer, VmlBaseElement parent, IHtmlEditor editor)
: this(peer.GetBaseElement(), parent.GetBaseElement(), editor)
{
}
internal ExtrusionElement(Interop.IHTMLElement peer, Interop.IHTMLElement parent, IHtmlEditor editor) : this(peer, editor)
{
Interop.IHTMLDOMNode parentNode = (Interop.IHTMLDOMNode) parent;
Interop.IHTMLElement extrusion = base.GetBaseElement();
if (extrusion != null)
{
parentNode.appendChild(extrusion as Interop.IHTMLDOMNode);
}
}
internal ExtrusionElement(Interop.IHTMLElement peer, IHtmlEditor editor) : base(peer, editor)
{
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using Xunit;
using Test.Cryptography;
using System.Security.Cryptography.Pkcs.Tests;
namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests
{
public static partial class StateTests
{
//
// Exercises various edge cases when EnvelopedCms methods and properties are called out of the "expected" order.
//
// The "expected" sequences are one of:
//
// ctor(ContentInfo)|ctor(ContentInfo,AlgorithmIdentifier) => Encrypt() => Encode()
//
// or
//
// ctor() => Decode() => RecipientInfos => Decrypt() => ContentInfo
//
// Most of these semantics are driven by backward compatibility. A tighter api design wouldn't
// have exposed all these state transitions in the first place.
//
// The four states an EnvelopedCms can be in are as follows:
//
// State 1: Post constructor
//
// There are three constructor overloads, but all but one just supply default arguments
// so we can consider there to be just one constructor.
//
// At this stage, there is no CMS underneath, just some properties (ContentInfo, AlgorithmIdentifier, etc.)
// that serve as implicit inputs to a future Encrypt() call.
//
// State 2: Post Encrypt()
//
// Encrypt() can be called at any time and it effectively resets the state of the EnvelopedCms
// (although the prior contents of ContentInfo, ContentEncryptionAlgorithm, UnprotectedAttributes and Certificates
// will naturally influence the contents of CMS is constructed.)
//
// Encrypt() actually both encrypts and encodes, but you have to call Encode() afterward to pick up the encoded bytes.
//
// State 3: Post Decode()
//
// Decode() can also be called at any time - it's effectively a constructor that resets the internal
// state and all the member properties.
//
// In this state, you can invoke the RecipientInfos properties to decide which recipient to pass to Decrypt().
//
// State 4: Post Decrypt()
//
// A Decrypt() can only happen after a Decode().
//
// Once in this state, you can fetch ContentInfo to get the decrypted content
// but otherwise, the CMS is in a pretty useless state.
//
//
// State 1
//
// Constructed using any of the constructor overloads.
//
[Fact]
public static void PostCtor_Version()
{
// Version returns 0 by fiat.
EnvelopedCms ecms = new EnvelopedCms();
Assert.Equal(0, ecms.Version);
}
[Fact]
public static void PostCtor_RecipientInfos()
{
// RecipientInfo returns empty collection by fiat.
EnvelopedCms ecms = new EnvelopedCms();
RecipientInfoCollection recipients = ecms.RecipientInfos;
Assert.Equal(0, recipients.Count);
}
[Fact]
public static void PostCtor_Encode()
{
EnvelopedCms ecms = new EnvelopedCms();
Assert.Throws<InvalidOperationException>(() => ecms.Encode());
}
[Fact]
public static void PostCtor_Decrypt()
{
EnvelopedCms ecms = new EnvelopedCms();
Assert.Throws<InvalidOperationException>(() => ecms.Decrypt());
}
[Fact]
public static void PostCtor_ContentInfo()
{
ContentInfo expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(expectedContentInfo);
ContentInfo actualContentInfo = ecms.ContentInfo;
Assert.Equal(expectedContentInfo.ContentType, actualContentInfo.ContentType);
Assert.Equal<byte>(expectedContentInfo.Content, actualContentInfo.Content);
}
//
// State 2
//
// Called constructor + Encrypt()
//
[Fact]
public static void PostEncrypt_Version()
{
ContentInfo expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(expectedContentInfo);
int versionBeforeEncrypt = ecms.Version;
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
ecms.Encrypt(new CmsRecipient(cert));
}
// Encrypt does not update Version member.
Assert.Equal(versionBeforeEncrypt, ecms.Version);
}
[Fact]
public static void PostEncrypt_RecipientInfos()
{
ContentInfo expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(expectedContentInfo);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
ecms.Encrypt(new CmsRecipient(cert));
}
object ignore;
Assert.ThrowsAny<CryptographicException>(() => ignore = ecms.RecipientInfos);
}
[Fact]
public static void PostEncrypt_Decrypt()
{
ContentInfo expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(expectedContentInfo);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
ecms.Encrypt(new CmsRecipient(cert));
}
Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt());
}
[Fact]
public static void PostEncrypt_ContentInfo()
{
ContentInfo expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(expectedContentInfo);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
ecms.Encrypt(new CmsRecipient(cert));
}
// Encrypting does not update ContentInfo.
ContentInfo actualContentInfo = ecms.ContentInfo;
Assert.Equal(expectedContentInfo.ContentType, actualContentInfo.ContentType);
Assert.Equal<byte>(expectedContentInfo.Content, actualContentInfo.Content);
}
//
// State 3: Called Decode()
//
public static void PostDecode_Encode(bool isRunningOnDesktop)
{
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e"
+ "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c"
+ "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4"
+ "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d"
+ "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
// This should really have thrown an InvalidOperationException. Instead, you get... something back.
string expectedString = isRunningOnDesktop ? "35edc437e31d0b70000000000000" : "35edc437e31d0b70";
byte[] expectedGarbage = expectedString.HexToByteArray();
byte[] garbage = ecms.Encode();
Assert.Equal(expectedGarbage, garbage);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp | TargetFrameworkMonikers.Uap)]
public static void PostDecode_Encode_net46()
{
PostDecode_Encode(isRunningOnDesktop: true);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void PostDecode_Encode_netcore()
{
PostDecode_Encode(isRunningOnDesktop: false);
}
public static void PostDecode_ContentInfo(bool isRunningOnDesktop)
{
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e"
+ "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c"
+ "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4"
+ "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d"
+ "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
// This gets you the encrypted inner content.
ContentInfo contentInfo = ecms.ContentInfo;
Assert.Equal(Oids.Pkcs7Data, contentInfo.ContentType.Value);
string expectedString = isRunningOnDesktop ? "35edc437e31d0b70000000000000" : "35edc437e31d0b70";
byte[] expectedGarbage = expectedString.HexToByteArray();
Assert.Equal(expectedGarbage, contentInfo.Content);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp | TargetFrameworkMonikers.Uap)]
public static void PostDecode_ContentInfo_net46()
{
PostDecode_ContentInfo(isRunningOnDesktop: true);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void PostDecode_ContentInfo_netcore()
{
PostDecode_ContentInfo(isRunningOnDesktop: false);
}
//
// State 4: Called Decode() + Decrypt()
//
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void PostDecrypt_Encode()
{
byte[] expectedContent = { 6, 3, 128, 33, 44 };
EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(expectedContent));
ecms.Encrypt(new CmsRecipient(Certificates.RSAKeyTransfer1.GetCertificate()));
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818067"
+ "6bada56dcaf2e65226941242db73b5a5420a6212cd6af662db52fdc0ca63875cb69066f7074da0fc009ce724e2d73fb19380"
+ "2deea8d92b069486a41c7c4fc3cd0174a918a559f79319039b40ae797bcacc909c361275ee2a5b1f0ff09fb5c19508e3f5ac"
+ "051ac0f03603c27fb8993d49ac428f8bcfc23a90ef9b0fac0f423a302b06092a864886f70d010701301406082a864886f70d"
+ "0307040828dc4d72ca3132e48008546cc90f2c5d4b79").HexToByteArray();
ecms.Decode(encodedMessage);
using (X509Certificate2 cer = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey())
{
if (cer == null)
return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can.
X509Certificate2Collection extraStore = new X509Certificate2Collection(cer);
RecipientInfoCollection r = ecms.RecipientInfos;
ecms.Decrypt(r[0], extraStore);
// Desktop compat: Calling Encode() at this point should have thrown an InvalidOperationException. Instead, it returns
// the decrypted inner content (same as ecms.ContentInfo.Content). This is easy for someone to take a reliance on
// so for compat sake, we'd better keep it.
byte[] encoded = ecms.Encode();
Assert.Equal<byte>(expectedContent, encoded);
}
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void PostDecrypt_RecipientInfos()
{
byte[] expectedContent = { 6, 3, 128, 33, 44 };
EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(expectedContent));
ecms.Encrypt(new CmsRecipient(Certificates.RSAKeyTransfer1.GetCertificate()));
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818067"
+ "6bada56dcaf2e65226941242db73b5a5420a6212cd6af662db52fdc0ca63875cb69066f7074da0fc009ce724e2d73fb19380"
+ "2deea8d92b069486a41c7c4fc3cd0174a918a559f79319039b40ae797bcacc909c361275ee2a5b1f0ff09fb5c19508e3f5ac"
+ "051ac0f03603c27fb8993d49ac428f8bcfc23a90ef9b0fac0f423a302b06092a864886f70d010701301406082a864886f70d"
+ "0307040828dc4d72ca3132e48008546cc90f2c5d4b79").HexToByteArray();
ecms.Decode(encodedMessage);
using (X509Certificate2 cer = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey())
{
if (cer == null)
return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can.
X509Certificate2Collection extraStore = new X509Certificate2Collection(cer);
RecipientInfoCollection col1 = ecms.RecipientInfos;
ecms.Decrypt(col1[0], extraStore);
// Make sure we can still RecipientInfos after a Decrypt()
RecipientInfoCollection col2 = ecms.RecipientInfos;
Assert.Equal(col1.Count, col2.Count);
RecipientInfo r1 = col1[0];
RecipientInfo r2 = col2[0];
X509IssuerSerial is1 = (X509IssuerSerial)(r1.RecipientIdentifier.Value);
X509IssuerSerial is2 = (X509IssuerSerial)(r2.RecipientIdentifier.Value);
Assert.Equal(is1.IssuerName, is2.IssuerName);
Assert.Equal(is1.SerialNumber, is2.SerialNumber);
}
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void PostDecrypt_Decrypt()
{
byte[] expectedContent = { 6, 3, 128, 33, 44 };
byte[] encodedMessage =
("308202b006092a864886f70d010703a08202a13082029d020100318202583081c5020100302e301a31183016060355040313"
+ "0f5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004"
+ "81801026d9fb60d1a55686b73cf859c8bd66b58defda5e23e3da5f535f1427e3c5f7a4a2a94373e8e3ba5488a7c6a1059bfb"
+ "57301156698e7fca62671426d388fb3fb4373c9cb53132fda067598256bbfe8491b14dadaaf04d5fdfb2463f358ad0d6a594"
+ "bf6a4fbab6b3d725f08032e601492265e6336d5a638096f9975025ccd6393081c5020100302e301a31183016060355040313"
+ "0f5253414b65795472616e736665723202102bce9f9ece39f98044f0cd2faa9a14e7300d06092a864886f70d010101050004"
+ "8180b6497a2b789728f200ca1f974a676c531a4769f03f3929bd7526e7333ea483b4abb530a49c8532db5d4a4df66f173e3e"
+ "a4ba9e4814b584dc987ac87c46bb131daab535140968aafad8808100a2515e9c6d0c1f382b024992ce36b70b841628e0eb43"
+ "4db89545d702a8fbd3403188e7de7cb4bc1dcc3bc325467570654aaf2ee83081c5020100302e301a31183016060355040313"
+ "0f5253414b65795472616e736665723302104497d870785a23aa4432ed0106ef72a6300d06092a864886f70d010101050004"
+ "81807517e594c353d41abff334c6162988b78e05df7d79457c146fbc886d2d8057f594fa3a96cd8df5842c9758baac1fcdd5"
+ "d9672a9f8ef9426326cccaaf5954f2ae657f8c7b13aef2f811adb4954323aa8319a1e8f2ad4e5c96c1d3fbe413ae479e471b"
+ "b701cbdfa145c9b64f5e1f69f472804995d56c31351553f779cf8efec237303c06092a864886f70d010701301d0609608648"
+ "01650304012a041023a114c149d7d4017ce2f5ec7c5d53f980104e50ab3c15533743dd054ef3ff8b9d83").HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
using (X509Certificate2 cert1 = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey())
using (X509Certificate2 cert2 = Certificates.RSAKeyTransfer2.TryGetCertificateWithPrivateKey())
using (X509Certificate2 cert3 = Certificates.RSAKeyTransfer3.TryGetCertificateWithPrivateKey())
{
if (cert1 == null || cert2 == null || cert3 == null)
return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can.
X509Certificate2Collection extraStore = new X509Certificate2Collection();
extraStore.Add(cert1);
extraStore.Add(cert2);
extraStore.Add(cert3);
RecipientInfoCollection r = ecms.RecipientInfos;
ecms.Decrypt(r[0], extraStore);
ContentInfo contentInfo = ecms.ContentInfo;
Assert.Equal<byte>(expectedContent, contentInfo.Content);
// Though this doesn't seem like a terribly unreasonable thing to attempt, attempting to call Decrypt() again
// after a successful Decrypt() throws a CryptographicException saying "Already decrypted."
Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(r[1], extraStore));
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlWriterTraceListener.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Globalization;
using System.Collections;
using System.Security.Permissions;
using System.Runtime.Versioning;
namespace System.Diagnostics {
[HostProtection(Synchronization=true)]
public class XmlWriterTraceListener : TextWriterTraceListener {
private const string fixedHeader = "<E2ETraceEvent xmlns=\"http://schemas.microsoft.com/2004/06/E2ETraceEvent\">" +
"<System xmlns=\"http://schemas.microsoft.com/2004/06/windows/eventlog/system\">";
private readonly string machineName = Environment.MachineName;
private StringBuilder strBldr = null;
private XmlTextWriter xmlBlobWriter = null;
// Previously we had a bug where TraceTransfer did not respect the filter set on this listener. We're fixing this
// bug, but only for cases where the filter was set via config. In the next side by side release, we'll remove
// this and always respect the filter for TraceTransfer events.
internal bool shouldRespectFilterOnTraceTransfer;
public XmlWriterTraceListener(Stream stream) : base(stream){ }
public XmlWriterTraceListener(Stream stream, string name) : base(stream, name){ }
public XmlWriterTraceListener(TextWriter writer) : base(writer){ }
public XmlWriterTraceListener(TextWriter writer, string name) : base(writer, name){ }
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public XmlWriterTraceListener(string filename) : base(filename){ }
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public XmlWriterTraceListener(string filename, string name) : base(filename, name){ }
public override void Write(string message) {
this.WriteLine(message);
}
public override void WriteLine(string message) {
this.TraceEvent(null, SR.GetString(SR.TraceAsTraceSource), TraceEventType.Information, 0, message);
}
public override void Fail(string message, string detailMessage) {
StringBuilder failMessage = new StringBuilder(message);
if (detailMessage != null) {
failMessage.Append(" ");
failMessage.Append(detailMessage);
}
this.TraceEvent(null, SR.GetString(SR.TraceAsTraceSource), TraceEventType.Error, 0, failMessage.ToString());
}
public override void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id, string format, params object[] args) {
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args))
return;
WriteHeader(source, eventType, id, eventCache);
string message;
if (args != null)
message = String.Format(CultureInfo.InvariantCulture, format, args);
else
message = format;
WriteEscaped(message);
WriteFooter(eventCache);
}
public override void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id, string message) {
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message))
return;
WriteHeader(source, eventType, id, eventCache);
WriteEscaped(message);
WriteFooter(eventCache);
}
public override void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, object data) {
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data))
return;
WriteHeader(source, eventType, id, eventCache);
InternalWrite("<TraceData>");
if (data != null) {
InternalWrite("<DataItem>");
WriteData(data);
InternalWrite("</DataItem>");
}
InternalWrite("</TraceData>");
WriteFooter(eventCache);
}
public override void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, params object[] data) {
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data))
return;
WriteHeader(source, eventType, id, eventCache);
InternalWrite("<TraceData>");
if (data != null) {
for (int i=0; i<data.Length; i++) {
InternalWrite("<DataItem>");
if (data[i] != null)
WriteData(data[i]);
InternalWrite("</DataItem>");
}
}
InternalWrite("</TraceData>");
WriteFooter(eventCache);
}
// Special case XPathNavigator dataitems to write out XML blob unescaped
private void WriteData(object data) {
XPathNavigator xmlBlob = data as XPathNavigator;
if(xmlBlob == null)
WriteEscaped(data.ToString());
else {
if (strBldr == null) {
strBldr = new StringBuilder();
xmlBlobWriter = new XmlTextWriter(new StringWriter(strBldr, CultureInfo.CurrentCulture));
}
else
strBldr.Length = 0;
try {
// Rewind the blob to point to the root, this is needed to support multiple XMLTL in one TraceData call
xmlBlob.MoveToRoot();
xmlBlobWriter.WriteNode(xmlBlob, false);
InternalWrite(strBldr.ToString());
}
catch (Exception) { // We probably only care about XmlException for ill-formed XML though
InternalWrite(data.ToString());
}
}
}
public override void Close() {
base.Close();
if (xmlBlobWriter != null)
xmlBlobWriter.Close();
xmlBlobWriter = null;
strBldr = null;
}
public override void TraceTransfer(TraceEventCache eventCache, String source, int id, string message, Guid relatedActivityId) {
if (shouldRespectFilterOnTraceTransfer && (Filter != null && !Filter.ShouldTrace(eventCache, source, TraceEventType.Transfer, id, message)))
return;
WriteHeader(source, TraceEventType.Transfer, id, eventCache, relatedActivityId);
WriteEscaped(message);
WriteFooter(eventCache);
}
private void WriteHeader(String source, TraceEventType eventType, int id, TraceEventCache eventCache, Guid relatedActivityId) {
WriteStartHeader(source, eventType, id, eventCache);
InternalWrite("\" RelatedActivityID=\"");
InternalWrite(relatedActivityId.ToString("B"));
WriteEndHeader(eventCache);
}
private void WriteHeader(String source, TraceEventType eventType, int id, TraceEventCache eventCache) {
WriteStartHeader(source, eventType, id, eventCache);
WriteEndHeader(eventCache);
}
private void WriteStartHeader(String source, TraceEventType eventType, int id, TraceEventCache eventCache) {
InternalWrite(fixedHeader);
InternalWrite("<EventID>");
InternalWrite(((uint)id).ToString(CultureInfo.InvariantCulture));
InternalWrite("</EventID>");
InternalWrite("<Type>3</Type>");
InternalWrite("<SubType Name=\"");
InternalWrite(eventType.ToString());
InternalWrite("\">0</SubType>");
InternalWrite("<Level>");
int sev = (int)eventType;
if (sev > 255)
sev = 255;
if (sev < 0)
sev = 0;
InternalWrite(sev.ToString(CultureInfo.InvariantCulture));
InternalWrite("</Level>");
InternalWrite("<TimeCreated SystemTime=\"");
if (eventCache != null)
InternalWrite(eventCache.DateTime.ToString("o", CultureInfo.InvariantCulture));
else
InternalWrite(DateTime.Now.ToString("o", CultureInfo.InvariantCulture));
InternalWrite("\" />");
InternalWrite("<Source Name=\"");
WriteEscaped(source);
InternalWrite("\" />");
InternalWrite("<Correlation ActivityID=\"");
if (eventCache != null)
InternalWrite(eventCache.ActivityId.ToString("B"));
else
InternalWrite(Guid.Empty.ToString("B"));
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
private void WriteEndHeader(TraceEventCache eventCache) {
InternalWrite("\" />");
InternalWrite("<Execution ProcessName=\"");
InternalWrite(TraceEventCache.GetProcessName());
InternalWrite("\" ProcessID=\"");
InternalWrite(((uint)TraceEventCache.GetProcessId()).ToString(CultureInfo.InvariantCulture));
InternalWrite("\" ThreadID=\"");
if (eventCache != null)
WriteEscaped(eventCache.ThreadId.ToString(CultureInfo.InvariantCulture));
else
WriteEscaped(TraceEventCache.GetThreadId().ToString(CultureInfo.InvariantCulture));
InternalWrite("\" />");
InternalWrite("<Channel/>");
InternalWrite("<Computer>");
InternalWrite(machineName);
InternalWrite("</Computer>");
InternalWrite("</System>");
InternalWrite("<ApplicationData>");
}
private void WriteFooter(TraceEventCache eventCache) {
bool writeLogicalOps = IsEnabled(TraceOptions.LogicalOperationStack);
bool writeCallstack = IsEnabled(TraceOptions.Callstack);
if (eventCache != null && (writeLogicalOps || writeCallstack)) {
InternalWrite("<System.Diagnostics xmlns=\"http://schemas.microsoft.com/2004/08/System.Diagnostics\">");
if (writeLogicalOps) {
InternalWrite("<LogicalOperationStack>");
Stack s = eventCache.LogicalOperationStack as Stack;
if (s != null) {
foreach (object correlationId in s) {
InternalWrite("<LogicalOperation>");
WriteEscaped(correlationId.ToString());
InternalWrite("</LogicalOperation>");
}
}
InternalWrite("</LogicalOperationStack>");
}
InternalWrite("<Timestamp>");
InternalWrite(eventCache.Timestamp.ToString(CultureInfo.InvariantCulture));
InternalWrite("</Timestamp>");
if (writeCallstack) {
InternalWrite("<Callstack>");
WriteEscaped(eventCache.Callstack);
InternalWrite("</Callstack>");
}
InternalWrite("</System.Diagnostics>");
}
InternalWrite("</ApplicationData></E2ETraceEvent>");
}
private void WriteEscaped(string str) {
if (str == null)
return;
int lastIndex = 0;
for (int i=0; i<str.Length; i++) {
switch(str[i]) {
case '&':
InternalWrite(str.Substring(lastIndex, i-lastIndex));
InternalWrite("&");
lastIndex = i +1;
break;
case '<':
InternalWrite(str.Substring(lastIndex, i-lastIndex));
InternalWrite("<");
lastIndex = i +1;
break;
case '>':
InternalWrite(str.Substring(lastIndex, i-lastIndex));
InternalWrite(">");
lastIndex = i +1;
break;
case '"':
InternalWrite(str.Substring(lastIndex, i-lastIndex));
InternalWrite(""");
lastIndex = i +1;
break;
case '\'':
InternalWrite(str.Substring(lastIndex, i-lastIndex));
InternalWrite("'");
lastIndex = i +1;
break;
case (char)0xD:
InternalWrite(str.Substring(lastIndex, i-lastIndex));
InternalWrite("
");
lastIndex = i +1;
break;
case (char)0xA:
InternalWrite(str.Substring(lastIndex, i-lastIndex));
InternalWrite("
");
lastIndex = i +1;
break;
}
}
InternalWrite(str.Substring(lastIndex, str.Length-lastIndex));
}
private void InternalWrite(string message) {
if (!EnsureWriter()) return;
// NeedIndent is nop
writer.Write(message);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Wizcorp.MageSDK.Log.Writers
{
public class ConsoleWriter : LogWriter
{
private List<string> config;
public ConsoleWriter(List<string> logLevels)
{
config = logLevels;
if (config.Contains("verbose"))
{
Logger.LogEmitter.On("log:verbose", Verbose);
}
if (config.Contains("debug"))
{
Logger.LogEmitter.On("log:debug", Debug);
}
if (config.Contains("info"))
{
Logger.LogEmitter.On("log:info", Info);
}
if (config.Contains("notice"))
{
Logger.LogEmitter.On("log:notice", Notice);
}
if (config.Contains("warning"))
{
Logger.LogEmitter.On("log:warning", Warning);
}
if (config.Contains("error"))
{
Logger.LogEmitter.On("log:error", Error);
}
if (config.Contains("critical"))
{
Logger.LogEmitter.On("log:critical", Critical);
}
if (config.Contains("alert"))
{
Logger.LogEmitter.On("log:alert", Alert);
}
if (config.Contains("emergency"))
{
Logger.LogEmitter.On("log:emergency", Emergency);
}
}
public override void Dispose()
{
if (config.Contains("verbose"))
{
Logger.LogEmitter.Off("log:verbose", Verbose);
}
if (config.Contains("debug"))
{
Logger.LogEmitter.Off("log:debug", Debug);
}
if (config.Contains("info"))
{
Logger.LogEmitter.Off("log:info", Info);
}
if (config.Contains("notice"))
{
Logger.LogEmitter.Off("log:notice", Notice);
}
if (config.Contains("warning"))
{
Logger.LogEmitter.Off("log:warning", Warning);
}
if (config.Contains("error"))
{
Logger.LogEmitter.Off("log:error", Error);
}
if (config.Contains("critical"))
{
Logger.LogEmitter.Off("log:critical", Critical);
}
if (config.Contains("alert"))
{
Logger.LogEmitter.Off("log:alert", Alert);
}
if (config.Contains("emergency"))
{
Logger.LogEmitter.Off("log:emergency", Emergency);
}
}
private string makeLogString(string channel, string context, string message)
{
return String.Format("[{0}] [{1}] {2}", channel, context, message);
}
private object makeDataString(object logData)
{
// Check if data is an excetion with a stack trace
var exception = logData as Exception;
if (exception != null && exception.StackTrace != null)
{
return exception + ":\n" + exception.StackTrace;
}
// Otherwise log data as is using its ToString function
Type objectType = logData.GetType();
MethodInfo toStringMethod = objectType.GetMethod("ToString", Type.EmptyTypes);
return toStringMethod.Invoke(logData, null);
}
private void Verbose(object sender, LogEntry logEntry)
{
UnityEngine.Debug.Log(makeLogString("verbose", logEntry.Context, logEntry.Message));
if (logEntry.Data != null)
{
UnityEngine.Debug.Log(makeDataString(logEntry.Data));
}
}
private void Debug(object sender, LogEntry logEntry)
{
UnityEngine.Debug.Log(makeLogString("debug", logEntry.Context, logEntry.Message));
if (logEntry.Data != null)
{
UnityEngine.Debug.Log(makeDataString(logEntry.Data));
}
}
private void Info(object sender, LogEntry logEntry)
{
UnityEngine.Debug.Log(makeLogString("info", logEntry.Context, logEntry.Message));
if (logEntry.Data != null)
{
UnityEngine.Debug.Log(makeDataString(logEntry.Data));
}
}
private void Notice(object sender, LogEntry logEntry)
{
UnityEngine.Debug.Log(makeLogString("notice", logEntry.Context, logEntry.Message));
if (logEntry.Data != null)
{
UnityEngine.Debug.Log(makeDataString(logEntry.Data));
}
}
private void Warning(object sender, LogEntry logEntry)
{
UnityEngine.Debug.LogWarning(makeLogString("warning", logEntry.Context, logEntry.Message));
if (logEntry.Data != null)
{
UnityEngine.Debug.LogWarning(makeDataString(logEntry.Data));
}
}
private void Error(object sender, LogEntry logEntry)
{
UnityEngine.Debug.LogError(makeLogString("error", logEntry.Context, logEntry.Message));
if (logEntry.Data != null)
{
UnityEngine.Debug.LogError(makeDataString(logEntry.Data));
}
}
private void Critical(object sender, LogEntry logEntry)
{
UnityEngine.Debug.LogError(makeLogString("critical", logEntry.Context, logEntry.Message));
if (logEntry.Data != null)
{
UnityEngine.Debug.LogError(makeDataString(logEntry.Data));
}
}
private void Alert(object sender, LogEntry logEntry)
{
UnityEngine.Debug.LogError(makeLogString("alert", logEntry.Context, logEntry.Message));
if (logEntry.Data != null)
{
UnityEngine.Debug.LogError(makeDataString(logEntry.Data));
}
}
private void Emergency(object sender, LogEntry logEntry)
{
UnityEngine.Debug.LogError(makeLogString("emergency", logEntry.Context, logEntry.Message));
if (logEntry.Data != null)
{
UnityEngine.Debug.LogError(makeDataString(logEntry.Data));
}
}
}
}
| |
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Content.Server.GameObjects.Components.Projectiles;
using Content.Server.Utility;
using Content.Shared.GameObjects.EntitySystems;
using Content.Shared.Physics;
using JetBrains.Annotations;
using Robust.Shared.GameObjects;
using Robust.Shared.GameObjects.Components;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Physics;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Log;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Singularity
{
[RegisterComponent]
public class ContainmentFieldGeneratorComponent : Component, ICollideBehavior
{
[Dependency] private IPhysicsManager _physicsManager = null!;
public override string Name => "ContainmentFieldGenerator";
private int _powerBuffer;
[ViewVariables]
public int PowerBuffer
{
get => _powerBuffer;
set => _powerBuffer = Math.Clamp(value, 0, 6);
}
public void ReceivePower(int power)
{
var totalPower = power + PowerBuffer;
var powerPerConnection = totalPower / 2;
var newBuffer = totalPower % 2;
TryPowerConnection(ref _connection1, ref newBuffer, powerPerConnection);
TryPowerConnection(ref _connection2, ref newBuffer, powerPerConnection);
PowerBuffer = newBuffer;
}
private void TryPowerConnection(ref Tuple<Direction, ContainmentFieldConnection>? connectionProperty, ref int powerBuffer, int powerPerConnection)
{
if (connectionProperty != null)
{
connectionProperty.Item2.SharedEnergyPool += powerPerConnection;
}
else
{
if (TryGenerateFieldConnection(ref connectionProperty))
{
connectionProperty.Item2.SharedEnergyPool += powerPerConnection;
}
else
{
powerBuffer += powerPerConnection;
}
}
}
private PhysicsComponent? _collidableComponent;
private Tuple<Direction, ContainmentFieldConnection>? _connection1;
private Tuple<Direction, ContainmentFieldConnection>? _connection2;
public bool CanRepell(IEntity toRepell) => _connection1?.Item2?.CanRepell(toRepell) == true ||
_connection2?.Item2?.CanRepell(toRepell) == true;
public override void Initialize()
{
base.Initialize();
if (!Owner.TryGetComponent(out _collidableComponent))
{
Logger.Error("ContainmentFieldGeneratorComponent created with no CollidableComponent");
return;
}
_collidableComponent.AnchoredChanged += OnAnchoredChanged;
}
private void OnAnchoredChanged()
{
if(_collidableComponent?.Anchored == true)
{
Owner.SnapToGrid();
}
else
{
_connection1?.Item2.Dispose();
_connection2?.Item2.Dispose();
}
}
private bool IsConnectedWith(ContainmentFieldGeneratorComponent comp)
{
return comp == this || _connection1?.Item2.Generator1 == comp || _connection1?.Item2.Generator2 == comp ||
_connection2?.Item2.Generator1 == comp || _connection2?.Item2.Generator2 == comp;
}
public bool HasFreeConnections()
{
return _connection1 == null || _connection2 == null;
}
private bool TryGenerateFieldConnection([NotNullWhen(true)] ref Tuple<Direction, ContainmentFieldConnection>? propertyFieldTuple)
{
if (propertyFieldTuple != null) return false;
if(_collidableComponent?.Anchored == false) return false;
foreach (var direction in new[] {Direction.North, Direction.East, Direction.South, Direction.West})
{
if (_connection1?.Item1 == direction || _connection2?.Item1 == direction) continue;
var dirVec = direction.ToVec();
var ray = new CollisionRay(Owner.Transform.WorldPosition, dirVec, (int) CollisionGroup.MobMask);
var rawRayCastResults = _physicsManager.IntersectRay(Owner.Transform.MapID, ray, 4.5f, Owner, false);
var rayCastResults = rawRayCastResults as RayCastResults[] ?? rawRayCastResults.ToArray();
if(!rayCastResults.Any()) continue;
RayCastResults? closestResult = null;
var smallestDist = 4.5f;
foreach (var res in rayCastResults)
{
if (res.Distance > smallestDist) continue;
smallestDist = res.Distance;
closestResult = res;
}
if(closestResult == null) continue;
var ent = closestResult.Value.HitEntity;
if (!ent.TryGetComponent<ContainmentFieldGeneratorComponent>(out var fieldGeneratorComponent) ||
fieldGeneratorComponent.Owner == Owner ||
!fieldGeneratorComponent.HasFreeConnections() ||
IsConnectedWith(fieldGeneratorComponent) ||
!ent.TryGetComponent<PhysicsComponent>(out var collidableComponent) ||
!collidableComponent.Anchored)
{
continue;
}
var connection = new ContainmentFieldConnection(this, fieldGeneratorComponent);
propertyFieldTuple = new Tuple<Direction, ContainmentFieldConnection>(direction, connection);
if (fieldGeneratorComponent._connection1 == null)
{
fieldGeneratorComponent._connection1 = new Tuple<Direction, ContainmentFieldConnection>(direction.GetOpposite(), connection);
}
else if (fieldGeneratorComponent._connection2 == null)
{
fieldGeneratorComponent._connection2 = new Tuple<Direction, ContainmentFieldConnection>(direction.GetOpposite(), connection);
}
else
{
Logger.Error("When trying to connect two Containmentfieldgenerators, the second one already had two connection but the check didn't catch it");
}
return true;
}
return false;
}
public void RemoveConnection(ContainmentFieldConnection? connection)
{
if (_connection1?.Item2 == connection)
{
_connection1 = null;
}else if (_connection2?.Item2 == connection)
{
_connection2 = null;
}
else if(connection != null)
{
Logger.Error("RemoveConnection called on Containmentfieldgenerator with a connection that can't be found in its connections.");
}
}
public void CollideWith(IEntity collidedWith)
{
if(collidedWith.HasComponent<EmitterBoltComponent>())
{
ReceivePower(4);
}
}
public override void OnRemove()
{
_connection1?.Item2.Dispose();
_connection2?.Item2.Dispose();
base.OnRemove();
}
}
}
| |
namespace NEventStore.Persistence.Sql.SqlDialects
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Transactions;
using NEventStore.Logging;
using NEventStore.Persistence.Sql;
using System.Threading.Tasks;
using ALinq;
public class CommonDbStatement : IDbStatement
{
private const int InfinitePageSize = 0;
private static readonly ILog Logger = LogFactory.BuildLogger(typeof (CommonDbStatement));
private readonly IDbAsyncConnection _connection;
private readonly ISqlDialect _dialect;
private readonly TransactionScope _scope;
private readonly IDbTransaction _transaction;
public CommonDbStatement(
ISqlDialect dialect,
TransactionScope scope,
IDbAsyncConnection connection,
IDbTransaction transaction)
{
Parameters = new Dictionary<string, Tuple<object, DbType?>>();
_dialect = dialect;
_scope = scope;
_connection = connection;
_transaction = transaction;
}
protected IDictionary<string, Tuple<object, DbType?>> Parameters { get; private set; }
protected ISqlDialect Dialect
{
get { return _dialect; }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual int PageSize { get; set; }
public virtual void AddParameter(string name, object value, DbType? parameterType = null)
{
Logger.Debug(Messages.AddingParameter, name);
Parameters[name] = Tuple.Create(_dialect.CoalesceParameterValue(value), parameterType);
}
public virtual async Task<int> ExecuteWithoutExceptions(string commandText)
{
try
{
return await ExecuteNonQuery(commandText);
}
catch (Exception)
{
Logger.Debug(Messages.ExceptionSuppressed);
return 0;
}
}
public virtual async Task<int> ExecuteNonQuery(string commandText)
{
try
{
using (var command = BuildCommand(commandText))
{
return await command.ExecuteNonQueryAsync();
}
}
catch (Exception e)
{
if (_dialect.IsDuplicate(e))
{
throw new UniqueKeyViolationException(e.Message, e);
}
throw;
}
}
public virtual async Task<object> ExecuteScalar(string commandText)
{
try
{
using (var command = BuildCommand(commandText))
{
return await command.ExecuteScalarAsync().ConfigureAwait(false);
}
}
catch (Exception e)
{
if (_dialect.IsDuplicate(e))
{
throw new UniqueKeyViolationException(e.Message, e);
}
throw;
}
}
public virtual IAsyncEnumerable<IDataRecord> ExecuteWithQuery(string queryText)
{
return ExecuteQuery(queryText, (query, latest) => { }, InfinitePageSize);
}
public virtual IAsyncEnumerable<IDataRecord> ExecutePagedQuery(string queryText, NextPageDelegate nextpage)
{
int pageSize = _dialect.CanPage ? PageSize : InfinitePageSize;
if (pageSize > 0)
{
Logger.Verbose(Messages.MaxPageSize, pageSize);
Parameters.Add(_dialect.Limit, Tuple.Create((object) pageSize, (DbType?) null));
}
return ExecuteQuery(queryText, nextpage, pageSize);
}
protected virtual void Dispose(bool disposing)
{
Logger.Verbose(Messages.DisposingStatement);
if (_transaction != null)
{
_transaction.Dispose();
}
if (_connection != null)
{
_connection.Dispose();
}
if (_scope != null)
{
_scope.Dispose();
}
}
protected virtual IAsyncEnumerable<IDataRecord> ExecuteQuery2(string queryText, NextPageDelegate nextpage, int pageSize)
{
Parameters.Add(_dialect.Skip, Tuple.Create((object) 0, (DbType?) null));
var command = BuildCommand(queryText);
try
{
return new AsyncPagedEnumerationCollection(_scope, _dialect, command, nextpage, pageSize, this);
}
catch (Exception)
{
command.Dispose();
throw;
}
}
protected virtual IAsyncEnumerable<IDataRecord> ExecuteQuery(string queryText, NextPageDelegate nextpage, int pageSize)
{
Parameters.Add(_dialect.Skip, Tuple.Create((object)0, (DbType?)null));
return AsyncEnumerable.Create<IDataRecord>(async producer =>
{
using (var command = BuildCommand(queryText))
{
var position = 0;
var read = 0;
try
{
do
{
using (var reader = await command.ExecuteReaderAsync())
{
read = 0;
while (await reader.ReadAsync())
{
await producer.Yield(reader);
position++;
read++;
if (IsPageCompletelyEnumerated(pageSize, position))
{
command.SetParameter(_dialect.Skip, position);
nextpage(command, reader);
}
}
Logger.Verbose(Messages.EnumeratedRowCount, position);
}
}
while (read > 0 && IsPageCompletelyEnumerated(pageSize,position));
}
catch (Exception e)
{
Logger.Debug(Messages.EnumerationThrewException, e.GetType());
throw new StorageUnavailableException(e.Message, e);
}
}
});
}
private bool IsPageCompletelyEnumerated(int pageSize, int position)
{
return pageSize > 0 && // Check if paging is disabled (pageSize == 0)
(position > 0 && 0 == (position % pageSize)); // Check if we have enumerated all the rows in this page
}
protected virtual IAsyncDbCommand BuildCommand(string statement)
{
Logger.Verbose(Messages.CreatingCommand);
var command = _connection.CreateAsyncCommand();
int timeout = 0;
if( int.TryParse( System.Configuration.ConfigurationManager.AppSettings["NEventStore.SqlCommand.Timeout"], out timeout ) )
{
command.CommandTimeout = timeout;
}
command.Transaction = _transaction;
command.CommandText = statement;
Logger.Verbose(Messages.ClientControlledTransaction, _transaction != null);
Logger.Verbose(Messages.CommandTextToExecute, statement);
BuildParameters(command);
return command;
}
protected virtual void BuildParameters(IDbCommand command)
{
foreach (var item in Parameters)
{
BuildParameter(command, item.Key, item.Value.Item1, item.Value.Item2);
}
}
protected virtual void BuildParameter(IDbCommand command, string name, object value, DbType? dbType)
{
IDbDataParameter parameter = command.CreateParameter();
parameter.ParameterName = name;
SetParameterValue(parameter, value, dbType);
Logger.Verbose(Messages.BindingParameter, name, parameter.Value);
command.Parameters.Add(parameter);
}
protected virtual void SetParameterValue(IDataParameter param, object value, DbType? type)
{
param.Value = value ?? DBNull.Value;
param.DbType = type ?? (value == null ? DbType.Binary : param.DbType);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using log4net;
using OpenSim.Framework;
using OpenSim.Data;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Services.AssetService
{
public class AssetService : AssetServiceBase, IAssetService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
protected static AssetService m_RootInstance;
public AssetService(IConfigSource config)
: this(config, "AssetService")
{
}
public AssetService(IConfigSource config, string configName) : base(config, configName)
{
if (m_RootInstance == null)
{
m_RootInstance = this;
if (m_AssetLoader != null)
{
IConfig assetConfig = config.Configs[m_ConfigName];
if (assetConfig == null)
throw new Exception("No " + m_ConfigName + " configuration");
string loaderArgs = assetConfig.GetString("AssetLoaderArgs",
String.Empty);
bool assetLoaderEnabled = assetConfig.GetBoolean("AssetLoaderEnabled", true);
if (assetLoaderEnabled)
{
m_log.DebugFormat("[ASSET SERVICE]: Loading default asset set from {0}", loaderArgs);
m_AssetLoader.ForEachDefaultXmlAsset(
loaderArgs,
delegate(AssetBase a)
{
AssetBase existingAsset = Get(a.ID);
// AssetMetadata existingMetadata = GetMetadata(a.ID);
if (existingAsset == null || Util.SHA1Hash(existingAsset.Data) != Util.SHA1Hash(a.Data))
{
// m_log.DebugFormat("[ASSET]: Storing {0} {1}", a.Name, a.ID);
m_Database.StoreAsset(a);
}
});
}
m_log.Debug("[ASSET SERVICE]: Local asset service enabled");
}
}
}
public virtual AssetBase Get(string id)
{
// m_log.DebugFormat("[ASSET SERVICE]: Get asset for {0}", id);
UUID assetID;
if (!UUID.TryParse(id, out assetID))
{
m_log.WarnFormat("[ASSET SERVICE]: Could not parse requested asset id {0}", id);
return null;
}
try
{
return m_Database.GetAsset(assetID);
}
catch (Exception e)
{
m_log.ErrorFormat("[ASSET SERVICE]: Exception getting asset {0} {1}", assetID, e);
return null;
}
}
public virtual AssetBase GetCached(string id)
{
return Get(id);
}
public virtual AssetMetadata GetMetadata(string id)
{
// m_log.DebugFormat("[ASSET SERVICE]: Get asset metadata for {0}", id);
AssetBase asset = Get(id);
if (asset != null)
return asset.Metadata;
else
return null;
}
public virtual byte[] GetData(string id)
{
// m_log.DebugFormat("[ASSET SERVICE]: Get asset data for {0}", id);
AssetBase asset = Get(id);
if (asset != null)
return asset.Data;
else
return null;
}
public virtual bool Get(string id, Object sender, AssetRetrieved handler)
{
//m_log.DebugFormat("[AssetService]: Get asset async {0}", id);
handler(id, sender, Get(id));
return true;
}
public virtual bool[] AssetsExist(string[] ids)
{
try
{
UUID[] uuid = Array.ConvertAll(ids, id => UUID.Parse(id));
return m_Database.AssetsExist(uuid);
}
catch (Exception e)
{
m_log.Error("[ASSET SERVICE]: Exception getting assets ", e);
return new bool[ids.Length];
}
}
public virtual string Store(AssetBase asset)
{
bool exists = m_Database.AssetsExist(new[] { asset.FullID })[0];
if (!exists)
{
// m_log.DebugFormat(
// "[ASSET SERVICE]: Storing asset {0} {1}, bytes {2}", asset.Name, asset.FullID, asset.Data.Length);
if (!m_Database.StoreAsset(asset))
{
return UUID.Zero.ToString();
}
}
// else
// {
// m_log.DebugFormat(
// "[ASSET SERVICE]: Not storing asset {0} {1}, bytes {2} as it already exists", asset.Name, asset.FullID, asset.Data.Length);
// }
return asset.ID;
}
public bool UpdateContent(string id, byte[] data)
{
return false;
}
public virtual bool Delete(string id)
{
// m_log.DebugFormat("[ASSET SERVICE]: Deleting asset {0}", id);
UUID assetID;
if (!UUID.TryParse(id, out assetID))
return false;
return m_Database.Delete(id);
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Core.CrossDomainImagesWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
/*
* Copyright 2010-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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DynamoDB.Model
{
/// <summary>
/// Container for the parameters to the Scan operation.
/// <para>Retrieves one or more items and its attributes by performing a full scan of a table.</para> <para>Provide a <c>ScanFilter</c> to get
/// more specific results.</para>
/// </summary>
/// <seealso cref="Amazon.DynamoDB.AmazonDynamoDB.Scan"/>
public class ScanRequest : AmazonWebServiceRequest
{
private string tableName;
private List<string> attributesToGet = new List<string>();
private int? limit;
private bool? count;
private Dictionary<string,Condition> scanFilter = new Dictionary<string,Condition>();
private Key exclusiveStartKey;
/// <summary>
/// The name of the table in which you want to scan. Allowed characters are <c>a-z</c>, <c>A-Z</c>, <c>0-9</c>, <c>_</c> (underscore), <c>-</c>
/// (hyphen) and <c>.</c> (period).
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>3 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[a-zA-Z0-9_.-]+</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string TableName
{
get { return this.tableName; }
set { this.tableName = value; }
}
/// <summary>
/// Sets the TableName property
/// </summary>
/// <param name="tableName">The value to set for the TableName property </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 ScanRequest WithTableName(string tableName)
{
this.tableName = tableName;
return this;
}
// Check to see if TableName property is set
internal bool IsSetTableName()
{
return this.tableName != null;
}
/// <summary>
/// List of <c>Attribute</c> names. If attribute names are not specified then all attributes will be returned. If some attributes are not found,
/// they will not appear in the result.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - </description>
/// </item>
/// </list>
/// </para>
/// </summary>
public List<string> AttributesToGet
{
get { return this.attributesToGet; }
set { this.attributesToGet = value; }
}
/// <summary>
/// Adds elements to the AttributesToGet collection
/// </summary>
/// <param name="attributesToGet">The values to add to the AttributesToGet collection </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 ScanRequest WithAttributesToGet(params string[] attributesToGet)
{
foreach (string element in attributesToGet)
{
this.attributesToGet.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the AttributesToGet collection
/// </summary>
/// <param name="attributesToGet">The values to add to the AttributesToGet collection </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 ScanRequest WithAttributesToGet(IEnumerable<string> attributesToGet)
{
foreach (string element in attributesToGet)
{
this.attributesToGet.Add(element);
}
return this;
}
// Check to see if AttributesToGet property is set
internal bool IsSetAttributesToGet()
{
return this.attributesToGet.Count > 0;
}
/// <summary>
/// The maximum number of items to return. If Amazon DynamoDB hits this limit while scanning the table, it stops the scan and returns the
/// matching values up to the limit, and a <c>LastEvaluatedKey</c> to apply in a subsequent operation to continue the scan. Also, if the scanned
/// data set size exceeds 1 MB before Amazon DynamoDB hits this limit, it stops the scan and returns the matching values up to the limit, and a
/// <c>LastEvaluatedKey</c> to apply in a subsequent operation to continue the scan.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Range</term>
/// <description>1 - </description>
/// </item>
/// </list>
/// </para>
/// </summary>
public int Limit
{
get { return this.limit ?? default(int); }
set { this.limit = value; }
}
/// <summary>
/// Sets the Limit property
/// </summary>
/// <param name="limit">The value to set for the Limit property </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 ScanRequest WithLimit(int limit)
{
this.limit = limit;
return this;
}
// Check to see if Limit property is set
internal bool IsSetLimit()
{
return this.limit.HasValue;
}
/// <summary>
/// If set to <c>true</c>, Amazon DynamoDB returns a total number of items for the <c>Scan</c> operation, even if the operation has no matching
/// items for the assigned filter. Do not set <c>Count</c> to <c>true</c> while providing a list of <c>AttributesToGet</c>, otherwise Amazon
/// DynamoDB returns a validation error.
///
/// </summary>
public bool Count
{
get { return this.count ?? default(bool); }
set { this.count = value; }
}
/// <summary>
/// Sets the Count property
/// </summary>
/// <param name="count">The value to set for the Count property </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 ScanRequest WithCount(bool count)
{
this.count = count;
return this;
}
// Check to see if Count property is set
internal bool IsSetCount()
{
return this.count.HasValue;
}
/// <summary>
/// Evaluates the scan results and returns only the desired values.
///
/// </summary>
public Dictionary<string,Condition> ScanFilter
{
get { return this.scanFilter; }
set { this.scanFilter = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the ScanFilter dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the ScanFilter dictionary.</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 ScanRequest WithScanFilter(params KeyValuePair<string, Condition>[] pairs)
{
foreach (KeyValuePair<string, Condition> pair in pairs)
{
this.ScanFilter[pair.Key] = pair.Value;
}
return this;
}
// Check to see if ScanFilter property is set
internal bool IsSetScanFilter()
{
return this.scanFilter != null;
}
/// <summary>
/// Primary key of the item from which to continue an earlier scan. An earlier scan might provide this value if that scan operation was
/// interrupted before scanning the entire table; either because of the result set size or the <c>Limit</c> parameter. The
/// <c>LastEvaluatedKey</c> can be passed back in a new scan request to continue the operation from that point.
///
/// </summary>
public Key ExclusiveStartKey
{
get { return this.exclusiveStartKey; }
set { this.exclusiveStartKey = value; }
}
/// <summary>
/// Sets the ExclusiveStartKey property
/// </summary>
/// <param name="exclusiveStartKey">The value to set for the ExclusiveStartKey property </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 ScanRequest WithExclusiveStartKey(Key exclusiveStartKey)
{
this.exclusiveStartKey = exclusiveStartKey;
return this;
}
// Check to see if ExclusiveStartKey property is set
internal bool IsSetExclusiveStartKey()
{
return this.exclusiveStartKey != null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System.Diagnostics;
using System.Text;
namespace System.Net.Http.HPack
{
internal class DynamicHPackEncoder
{
public const int DefaultHeaderTableSize = 4096;
// Internal for testing
internal readonly EncoderHeaderEntry Head;
private readonly bool _allowDynamicCompression;
private readonly EncoderHeaderEntry[] _headerBuckets;
private readonly byte _hashMask;
private uint _headerTableSize;
private uint _maxHeaderTableSize;
private bool _pendingTableSizeUpdate;
private EncoderHeaderEntry? _removed;
internal uint TableSize => _headerTableSize;
public DynamicHPackEncoder(bool allowDynamicCompression = true, uint maxHeaderTableSize = DefaultHeaderTableSize)
{
_allowDynamicCompression = allowDynamicCompression;
_maxHeaderTableSize = maxHeaderTableSize;
Head = new EncoderHeaderEntry();
Head.Initialize(-1, string.Empty, string.Empty, 0, int.MaxValue, null);
// Bucket count balances memory usage and the expected low number of headers (constrained by the header table size).
// Performance with different bucket counts hasn't been measured in detail.
_headerBuckets = new EncoderHeaderEntry[16];
_hashMask = (byte)(_headerBuckets.Length - 1);
Head.Before = Head.After = Head;
}
public void UpdateMaxHeaderTableSize(uint maxHeaderTableSize)
{
if (_maxHeaderTableSize != maxHeaderTableSize)
{
_maxHeaderTableSize = maxHeaderTableSize;
// Dynamic table size update will be written next HEADERS frame
_pendingTableSizeUpdate = true;
// Check capacity and remove entries that exceed the new capacity
EnsureCapacity(0);
}
}
public bool EnsureDynamicTableSizeUpdate(Span<byte> buffer, out int length)
{
// Check if there is a table size update that should be encoded
if (_pendingTableSizeUpdate)
{
bool success = HPackEncoder.EncodeDynamicTableSizeUpdate((int)_maxHeaderTableSize, buffer, out length);
_pendingTableSizeUpdate = false;
return success;
}
length = 0;
return true;
}
public bool EncodeHeader(Span<byte> buffer, int staticTableIndex, HeaderEncodingHint encodingHint, string name, string value,
Encoding? valueEncoding, out int bytesWritten)
{
Debug.Assert(!_pendingTableSizeUpdate, "Dynamic table size update should be encoded before headers.");
// Never index sensitive value.
if (encodingHint == HeaderEncodingHint.NeverIndex)
{
int index = ResolveDynamicTableIndex(staticTableIndex, name);
return index == -1
? HPackEncoder.EncodeLiteralHeaderFieldNeverIndexingNewName(name, value, valueEncoding, buffer, out bytesWritten)
: HPackEncoder.EncodeLiteralHeaderFieldNeverIndexing(index, value, valueEncoding, buffer, out bytesWritten);
}
// No dynamic table. Only use the static table.
if (!_allowDynamicCompression || _maxHeaderTableSize == 0 || encodingHint == HeaderEncodingHint.IgnoreIndex)
{
return staticTableIndex == -1
? HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexingNewName(name, value, valueEncoding, buffer, out bytesWritten)
: HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexing(staticTableIndex, value, valueEncoding, buffer, out bytesWritten);
}
// Header is greater than the maximum table size.
// Don't attempt to add dynamic header as all existing dynamic headers will be removed.
var headerLength = HeaderField.GetLength(name.Length, valueEncoding?.GetByteCount(value) ?? value.Length);
if (headerLength > _maxHeaderTableSize)
{
int index = ResolveDynamicTableIndex(staticTableIndex, name);
return index == -1
? HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexingNewName(name, value, valueEncoding, buffer, out bytesWritten)
: HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexing(index, value, valueEncoding, buffer, out bytesWritten);
}
return EncodeDynamicHeader(buffer, staticTableIndex, name, value, headerLength, valueEncoding, out bytesWritten);
}
private int ResolveDynamicTableIndex(int staticTableIndex, string name)
{
if (staticTableIndex != -1)
{
// Prefer static table index.
return staticTableIndex;
}
return CalculateDynamicTableIndex(name);
}
private bool EncodeDynamicHeader(Span<byte> buffer, int staticTableIndex, string name, string value,
int headerLength, Encoding? valueEncoding, out int bytesWritten)
{
EncoderHeaderEntry? headerField = GetEntry(name, value);
if (headerField != null)
{
// Already exists in dynamic table. Write index.
int index = CalculateDynamicTableIndex(headerField.Index);
return HPackEncoder.EncodeIndexedHeaderField(index, buffer, out bytesWritten);
}
else
{
// Doesn't exist in dynamic table. Add new entry to dynamic table.
int index = ResolveDynamicTableIndex(staticTableIndex, name);
bool success = index == -1
? HPackEncoder.EncodeLiteralHeaderFieldIndexingNewName(name, value, valueEncoding, buffer, out bytesWritten)
: HPackEncoder.EncodeLiteralHeaderFieldIndexing(index, value, valueEncoding, buffer, out bytesWritten);
if (success)
{
uint headerSize = (uint)headerLength;
EnsureCapacity(headerSize);
AddHeaderEntry(name, value, headerSize);
}
return success;
}
}
/// <summary>
/// Ensure there is capacity for the new header. If there is not enough capacity then remove
/// existing headers until space is available.
/// </summary>
private void EnsureCapacity(uint headerSize)
{
Debug.Assert(headerSize <= _maxHeaderTableSize, "Header is bigger than dynamic table size.");
while (_maxHeaderTableSize - _headerTableSize < headerSize)
{
EncoderHeaderEntry? removed = RemoveHeaderEntry();
Debug.Assert(removed != null);
// Removed entries are tracked to be reused.
PushRemovedEntry(removed);
}
}
private EncoderHeaderEntry? GetEntry(string name, string value)
{
if (_headerTableSize == 0)
{
return null;
}
int hash = name.GetHashCode();
int bucketIndex = CalculateBucketIndex(hash);
for (EncoderHeaderEntry? e = _headerBuckets[bucketIndex]; e != null; e = e.Next)
{
// We've already looked up entries based on a hash of the name.
// Compare value before name as it is more likely to be different.
if (e.Hash == hash &&
string.Equals(value, e.Value, StringComparison.Ordinal) &&
string.Equals(name, e.Name, StringComparison.Ordinal))
{
return e;
}
}
return null;
}
private int CalculateDynamicTableIndex(string name)
{
if (_headerTableSize == 0)
{
return -1;
}
int hash = name.GetHashCode();
int bucketIndex = CalculateBucketIndex(hash);
for (EncoderHeaderEntry? e = _headerBuckets[bucketIndex]; e != null; e = e.Next)
{
if (e.Hash == hash && string.Equals(name, e.Name, StringComparison.Ordinal))
{
return CalculateDynamicTableIndex(e.Index);
}
}
return -1;
}
private int CalculateDynamicTableIndex(int index)
{
return index == -1 ? -1 : index - Head.Before!.Index + 1 + H2StaticTable.Count;
}
private void AddHeaderEntry(string name, string value, uint headerSize)
{
Debug.Assert(headerSize <= _maxHeaderTableSize, "Header is bigger than dynamic table size.");
Debug.Assert(headerSize <= _maxHeaderTableSize - _headerTableSize, "Not enough room in dynamic table.");
int hash = name.GetHashCode();
int bucketIndex = CalculateBucketIndex(hash);
EncoderHeaderEntry? oldEntry = _headerBuckets[bucketIndex];
// Attempt to reuse removed entry
EncoderHeaderEntry? newEntry = PopRemovedEntry() ?? new EncoderHeaderEntry();
newEntry.Initialize(hash, name, value, headerSize, Head.Before!.Index - 1, oldEntry);
_headerBuckets[bucketIndex] = newEntry;
newEntry.AddBefore(Head);
_headerTableSize += headerSize;
}
private void PushRemovedEntry(EncoderHeaderEntry removed)
{
if (_removed != null)
{
removed.Next = _removed;
}
_removed = removed;
}
private EncoderHeaderEntry? PopRemovedEntry()
{
if (_removed != null)
{
EncoderHeaderEntry? removed = _removed;
_removed = _removed.Next;
return removed;
}
return null;
}
/// <summary>
/// Remove the oldest entry.
/// </summary>
private EncoderHeaderEntry? RemoveHeaderEntry()
{
if (_headerTableSize == 0)
{
return null;
}
EncoderHeaderEntry? eldest = Head.After;
int hash = eldest!.Hash;
int bucketIndex = CalculateBucketIndex(hash);
EncoderHeaderEntry? prev = _headerBuckets[bucketIndex];
EncoderHeaderEntry? e = prev;
while (e != null)
{
EncoderHeaderEntry? next = e.Next;
if (e == eldest)
{
if (prev == eldest)
{
_headerBuckets[bucketIndex] = next!;
}
else
{
prev.Next = next;
}
_headerTableSize -= eldest.Size;
eldest.Remove();
return eldest;
}
prev = e;
e = next;
}
return null;
}
private int CalculateBucketIndex(int hash)
{
return hash & _hashMask;
}
}
/// <summary>
/// Hint for how the header should be encoded as HPack. This value can be overriden.
/// For example, a header that is larger than the dynamic table won't be indexed.
/// </summary>
internal enum HeaderEncodingHint
{
Index,
IgnoreIndex,
NeverIndex
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class TypeBuilderCreateType3
{
private const int MinAsmName = 1;
private const int MaxAsmName = 260;
private const int MinModName = 1;
private const int MaxModName = 260;
private const int MinTypName = 1;
private const int MaxTypName = 1024;
private const int NumLoops = 5;
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
private TypeAttributes[] _typesPos = new TypeAttributes[17] {
TypeAttributes.Abstract | TypeAttributes.NestedPublic,
TypeAttributes.AnsiClass | TypeAttributes.NestedPublic,
TypeAttributes.AutoClass | TypeAttributes.NestedPublic,
TypeAttributes.AutoLayout | TypeAttributes.NestedPublic,
TypeAttributes.BeforeFieldInit | TypeAttributes.NestedPublic,
TypeAttributes.Class | TypeAttributes.NestedPublic,
TypeAttributes.ClassSemanticsMask | TypeAttributes.Abstract | TypeAttributes.NestedPublic,
TypeAttributes.ExplicitLayout | TypeAttributes.NestedPublic,
TypeAttributes.Import | TypeAttributes.NestedPublic,
TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.NestedPublic,
TypeAttributes.Sealed | TypeAttributes.NestedPublic,
TypeAttributes.SequentialLayout | TypeAttributes.NestedPublic,
TypeAttributes.Serializable | TypeAttributes.NestedPublic,
TypeAttributes.SpecialName | TypeAttributes.NestedPublic,
TypeAttributes.StringFormatMask | TypeAttributes.NestedPublic,
TypeAttributes.UnicodeClass | TypeAttributes.NestedPublic,
TypeAttributes.VisibilityMask,
};
[Fact]
public void TestDefineNestedType()
{
ModuleBuilder modBuilder;
TypeBuilder typeBuilder;
TypeBuilder nestedType = null;
Type newType;
string typeName = "";
string nestedTypeName = "";
modBuilder = CreateModule(
_generator.GetString(true, MinAsmName, MaxAsmName),
_generator.GetString(false, MinModName, MaxModName));
typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
typeBuilder = modBuilder.DefineType(typeName);
for (int i = 0; i < NumLoops; i++)
{
nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
// create nested type
if (null != nestedType && 0 == (_generator.GetInt32() % 2))
{
nestedType.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic, typeBuilder.GetType());
}
else
{
nestedType = typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic, typeBuilder.GetType());
}
}
newType = typeBuilder.CreateTypeInfo().AsType();
Assert.True(newType.Name.Equals(typeName));
}
[Fact]
public void TestWithEmbeddedNullsInName()
{
ModuleBuilder modBuilder;
TypeBuilder typeBuilder;
Type newType;
string typeName = "";
string nestedTypeName = "";
for (int i = 0; i < NumLoops; i++)
{
modBuilder = CreateModule(
_generator.GetString(true, MinAsmName, MaxAsmName),
_generator.GetString(false, MinModName, MaxModName));
typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName / 4)
+ '\0'
+ _generator.GetString(true, MinTypName, MaxTypName / 4)
+ '\0'
+ _generator.GetString(true, MinTypName, MaxTypName / 4);
typeBuilder = modBuilder.DefineType(typeName);
// create nested type
typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic, typeBuilder.GetType());
newType = typeBuilder.CreateTypeInfo().AsType();
Assert.True(newType.Name.Equals(typeName));
}
}
[Fact]
public void TestWithTypeAttributesSet()
{
ModuleBuilder modBuilder;
TypeBuilder typeBuilder;
TypeBuilder nestedType = null;
Type newType;
string typeName = "";
string nestedTypeName = "";
TypeAttributes typeAttrib = (TypeAttributes)0;
int i = 0;
modBuilder = CreateModule(
_generator.GetString(true, MinAsmName, MaxAsmName),
_generator.GetString(false, MinModName, MaxModName));
typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
typeBuilder = modBuilder.DefineType(typeName, typeAttrib);
for (i = 0; i < _typesPos.Length; i++)
{
typeAttrib = _typesPos[i];
nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
// create nested type
if (null != nestedType && 0 == (_generator.GetInt32() % 2))
{
nestedType.DefineNestedType(nestedTypeName, _typesPos[i], typeBuilder.GetType());
}
else
{
nestedType = typeBuilder.DefineNestedType(nestedTypeName, _typesPos[i], typeBuilder.GetType());
}
}
newType = typeBuilder.CreateTypeInfo().AsType();
Assert.True(newType.Name.Equals(typeName));
}
[Fact]
public void TestWithNullParentType()
{
ModuleBuilder modBuilder;
TypeBuilder typeBuilder;
TypeBuilder nestedType = null;
Type newType;
string typeName = "";
string nestedTypeName = "";
modBuilder = CreateModule(
_generator.GetString(true, MinAsmName, MaxAsmName),
_generator.GetString(false, MinModName, MaxModName));
typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
typeBuilder = modBuilder.DefineType(typeName);
nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
// create nested type
nestedType = typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic, null);
newType = typeBuilder.CreateTypeInfo().AsType();
Assert.True(newType.Name.Equals(typeName));
}
[Fact]
public void TestThrowsExceptionForNullname()
{
ModuleBuilder modBuilder;
TypeBuilder typeBuilder;
Type newType;
string typeName = "";
string nestedTypeName = "";
modBuilder = CreateModule(
_generator.GetString(true, MinAsmName, MaxAsmName),
_generator.GetString(false, MinModName, MaxModName));
typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
nestedTypeName = null;
typeBuilder = modBuilder.DefineType(typeName);
Assert.Throws<ArgumentNullException>(() =>
{
// create nested type
typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.NestedPublic | TypeAttributes.Class, typeBuilder.GetType());
newType = typeBuilder.CreateTypeInfo().AsType();
});
}
[Fact]
public void TestThrowsExcetpionForEmptyName()
{
ModuleBuilder modBuilder;
TypeBuilder typeBuilder;
Type newType;
string typeName = "";
string nestedTypeName = "";
modBuilder = CreateModule(
_generator.GetString(true, MinAsmName, MaxAsmName),
_generator.GetString(false, MinModName, MaxModName));
typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
nestedTypeName = string.Empty;
typeBuilder = modBuilder.DefineType(typeName);
Assert.Throws<ArgumentException>(() =>
{
// create nested type
typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.NestedPublic | TypeAttributes.Class, typeBuilder.GetType());
newType = typeBuilder.CreateTypeInfo().AsType();
});
}
public ModuleBuilder CreateModule(string assemblyName, string modName)
{
AssemblyName asmName;
AssemblyBuilder asmBuilder;
ModuleBuilder modBuilder;
// create the dynamic module
asmName = new AssemblyName(assemblyName);
asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
modBuilder = TestLibrary.Utilities.GetModuleBuilder(asmBuilder, "Module1");
return modBuilder;
}
}
}
| |
/* Copyright (c) 2006-2008 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.
*/
/* Change history
* Oct 13 2008 Joe Feser [email protected]
* Converted ArrayLists and other .NET 1.1 collections to use Generics
* Combined IExtensionElement and IExtensionElementFactory interfaces
*
*/
#region Using directives
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Net;
using System.Xml;
using Google.GData.Client;
using System.Collections.Generic;
#endregion
namespace Google.GData.GoogleBase
{
///////////////////////////////////////////////////////////////////////
/// <summary>Object model for gm:attribute XML tags
///
/// The histogram feeds returns entries with exactly one gm:attribute
/// tag.
///
/// AttributeHistogram usually come from GoogleBaseEntry found in
/// an histogram feed using: GoogleBaseEntry.AttributeHistogram
/// </summary>
///////////////////////////////////////////////////////////////////////
public class AttributeHistogram : IExtensionElementFactory
{
private readonly string name;
private readonly GBaseAttributeType type;
private readonly int count;
private readonly List<HistogramValue> values;
///////////////////////////////////////////////////////////////////////
/// <summary>Creates an AttributeHistogram with no example values.
/// </summary>
/// <param name="name">attribute name</param>
/// <param name="type">attribute type</param>
/// <param name="count">number of times this attribute appeared
/// in the histogram query results</param>
///////////////////////////////////////////////////////////////////////
public AttributeHistogram(string name,
GBaseAttributeType type,
int count)
:this(name, type, count, null)
{
}
///////////////////////////////////////////////////////////////////////
/// <summary>Creates an AttributeHistogram.</summary>
/// <param name="name">attribute name</param>
/// <param name="type">attribute type</param>
/// <param name="count">number of times this attribute appeared
/// in the histogram query results</param>
/// <param name="values">example values, may be empty or null
/// in the histogram query results</param>
///////////////////////////////////////////////////////////////////////
public AttributeHistogram(string name,
GBaseAttributeType type,
int count,
List<HistogramValue> values)
{
this.name = name;
this.type = type;
this.count = count;
this.values = values == null ? new List<HistogramValue>() : values;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Partial string representation, for debugging.</summary>
///////////////////////////////////////////////////////////////////////
public override string ToString()
{
return "AttributeHistogram:" + name + "(" + type + ")";
}
///////////////////////////////////////////////////////////////////////
/// <summary>Attribute name</summary>
///////////////////////////////////////////////////////////////////////
public string Name
{
get
{
return name;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Attribute type</summary>
///////////////////////////////////////////////////////////////////////
public GBaseAttributeType Type
{
get
{
return type;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Number of times this attribute appeared in the histogram
/// query results.</summary>
///////////////////////////////////////////////////////////////////////
public int Count
{
get
{
return count;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>The most common values found for this attribute in
/// the histogram query results. It might be empty.</summary>
///////////////////////////////////////////////////////////////////////
public List<HistogramValue> Values
{
get
{
return values;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Parses a gm:attribute tag and create the corresponding
/// AttributeHistogram object.</summary>
///////////////////////////////////////////////////////////////////////
public static AttributeHistogram Parse(XmlNode node)
{
if (node.Attributes != null)
{
string name = null;
int count = 0;
GBaseAttributeType type = null;
name = Utilities.GetAttributeValue("name", node);
String value = Utilities.GetAttributeValue("type", node);
if (value != null)
{
type = GBaseAttributeType.ForName(value);
}
value = Utilities.GetAttributeValue("count", node);
if (value != null)
{
count = NumberFormat.ToInt(value);
}
if (name != null && type != null)
{
//TODO determine if this is correct.
List<HistogramValue> values = new List<HistogramValue>();
for (XmlNode child = node.FirstChild;
child != null;
child = child.NextSibling)
{
if (child.LocalName == "value")
{
value = Utilities.GetAttributeValue("count", child);
if (value != null)
{
int valueCount = NumberFormat.ToInt(value);
values.Add(new HistogramValue(child.InnerText, valueCount));
}
}
}
return new AttributeHistogram(name, type, count, values);
}
}
return null;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Generates XML code for the current tag.</summary>
///////////////////////////////////////////////////////////////////////
public void Save(XmlWriter writer)
{
writer.WriteStartElement(XmlPrefix,
"attribute",
XmlNameSpace);
writer.WriteAttributeString("name", name);
writer.WriteAttributeString("type", type.Name);
writer.WriteAttributeString("count", NumberFormat.ToString(count));
foreach (HistogramValue value in values)
{
writer.WriteStartElement(GBaseNameTable.GBaseMetaPrefix,
"value",
GBaseNameTable.NSGBaseMeta);
writer.WriteAttributeString("count", NumberFormat.ToString(value.Count));
writer.WriteString(value.Content);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
#region IExtensionElementFactory Members
public string XmlName
{
get
{
//TODO determine if this is correct
return name;
}
}
public string XmlNameSpace
{
get
{
return GBaseNameTable.NSGBaseMeta;
}
}
public string XmlPrefix
{
get
{
return GBaseNameTable.GBaseMetaPrefix;
}
}
public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser)
{
return Parse(node);
}
#endregion
}
///////////////////////////////////////////////////////////////////////
/// <summary>An example value of an AttributeHistogram.</summary>
///////////////////////////////////////////////////////////////////////
public struct HistogramValue
{
private readonly string content;
private readonly int count;
///////////////////////////////////////////////////////////////////////
/// <summary>Creates an example value.</summary>
/// <param name="content">the example itself, as a string</param>
/// <param name="count">number of times this particular value
/// appeared in the histogram query results</param>
///////////////////////////////////////////////////////////////////////
public HistogramValue(string content, int count)
{
this.content = content;
this.count = count;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Returns the example itself, as a string.</summary>
///////////////////////////////////////////////////////////////////////
public override string ToString()
{
return content;
}
///////////////////////////////////////////////////////////////////////
/// <summary>The example itself, as a string</summary>
///////////////////////////////////////////////////////////////////////
public string Content
{
get
{
return content;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Number of times this particular value appeared
/// in the histogram query</summary>
///////////////////////////////////////////////////////////////////////
public int Count
{
get
{
return count;
}
}
}
}
| |
#region License
/* The MIT License
*
* Copyright (c) 2011 Red Badger Consulting
*
* 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
//-------------------------------------------------------------------------------------------------
// <auto-generated>
// Marked as auto-generated so StyleCop will ignore BDD style tests
// </auto-generated>
//-------------------------------------------------------------------------------------------------
#pragma warning disable 169
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedMember.Local
namespace RedBadger.Xpf.Specs.Controls.GridSpecs
{
using Machine.Specifications;
using Moq;
using RedBadger.Xpf.Controls;
using It = Machine.Specifications.It;
[Subject(typeof(Grid), "Arrange - Pixel/Auto/Star")]
public class when_arranging_a_grid_that_has_columns_of_mixed_pixel_auto_and_star : a_Grid
{
private const double Column1PixelWidth = 30d;
private const double Column2ChildWidth = 20d;
private static readonly Mock<UIElement>[] children = new Mock<UIElement>[4];
private static readonly double expectedProportionalWidth = (AvailableSize.Width - Column1PixelWidth -
Column2ChildWidth) / 2;
private Establish context = () =>
{
Subject.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(Column1PixelWidth) });
Subject.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
Subject.ColumnDefinitions.Add(new ColumnDefinition());
Subject.ColumnDefinitions.Add(new ColumnDefinition());
children[0] = new Mock<UIElement> { CallBase = true };
children[1] = new Mock<UIElement> { CallBase = true };
children[2] = new Mock<UIElement> { CallBase = true };
children[3] = new Mock<UIElement> { CallBase = true };
Grid.SetColumn(children[0].Object, 0);
Grid.SetColumn(children[1].Object, 1);
Grid.SetColumn(children[2].Object, 2);
Grid.SetColumn(children[3].Object, 3);
children[1].Object.Width = Column2ChildWidth;
Subject.Children.Add(children[0].Object);
Subject.Children.Add(children[1].Object);
Subject.Children.Add(children[2].Object);
Subject.Children.Add(children[3].Object);
Subject.Measure(AvailableSize);
};
private Because of = () => Subject.Arrange(new Rect(AvailableSize));
private It should_layout_child_1_correctly =
() => children[0].Object.VisualOffset.ShouldEqual(new Vector(0d, 0d));
private It should_layout_child_2_correctly =
() => children[1].Object.VisualOffset.ShouldEqual(new Vector(Column1PixelWidth, 0d));
private It should_layout_child_3_correctly =
() => children[2].Object.VisualOffset.ShouldEqual(new Vector(Column1PixelWidth + Column2ChildWidth, 0d));
private It should_layout_child_4_correctly =
() =>
children[3].Object.VisualOffset.ShouldEqual(
new Vector(Column1PixelWidth + Column2ChildWidth + expectedProportionalWidth, 0d));
}
[Subject(typeof(Grid), "Arrange - Pixel/Auto/Star")]
public class when_arranging_a_grid_that_has_rows_of_mixed_pixel_auto_and_star : a_Grid
{
private const double Row1PixelHeight = 30;
private const double Row2ChildHeight = 20;
private static readonly Mock<UIElement>[] children = new Mock<UIElement>[4];
private static readonly double expectedProportionalHeight = (AvailableSize.Height - Row1PixelHeight -
Row2ChildHeight) / 2;
private Establish context = () =>
{
Subject.RowDefinitions.Add(new RowDefinition { Height = new GridLength(Row1PixelHeight) });
Subject.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
Subject.RowDefinitions.Add(new RowDefinition());
Subject.RowDefinitions.Add(new RowDefinition());
children[0] = new Mock<UIElement> { CallBase = true };
children[1] = new Mock<UIElement> { CallBase = true };
children[2] = new Mock<UIElement> { CallBase = true };
children[3] = new Mock<UIElement> { CallBase = true };
Grid.SetRow(children[0].Object, 0);
Grid.SetRow(children[1].Object, 1);
Grid.SetRow(children[2].Object, 2);
Grid.SetRow(children[3].Object, 3);
children[1].Object.Height = Row2ChildHeight;
Subject.Children.Add(children[0].Object);
Subject.Children.Add(children[1].Object);
Subject.Children.Add(children[2].Object);
Subject.Children.Add(children[3].Object);
Subject.Measure(AvailableSize);
};
private Because of = () => Subject.Arrange(new Rect(AvailableSize));
private It should_layout_child_1_correctly =
() => children[0].Object.VisualOffset.ShouldEqual(new Vector(0d, 0d));
private It should_layout_child_2_correctly =
() => children[1].Object.VisualOffset.ShouldEqual(new Vector(0d, Row1PixelHeight));
private It should_layout_child_3_correctly =
() => children[2].Object.VisualOffset.ShouldEqual(new Vector(0d, Row1PixelHeight + Row2ChildHeight));
private It should_layout_child_4_correctly =
() =>
children[3].Object.VisualOffset.ShouldEqual(
new Vector(0d, Row1PixelHeight + Row2ChildHeight + expectedProportionalHeight));
}
[Subject(typeof(Grid), "Arrange - Pixel/Auto/Star")]
public class when_arranging_a_grid_that_has_rows_and_columns_of_mixed_pixel_auto_and_star : a_Grid
{
private const double AutoColumnWidth = 50;
private const double AutoRowHeight = 50;
private const double PixelColumnWidth = 50;
private const double PixelRowHeight = 50;
private const double StarColumnWidth = 100;
private const double StarRowHeight = 100;
private static readonly Mock<UIElement>[] children = new Mock<UIElement>[9];
private Establish context = () =>
{
Subject.RowDefinitions.Add(new RowDefinition());
Subject.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
Subject.RowDefinitions.Add(new RowDefinition { Height = new GridLength(PixelRowHeight) });
Subject.ColumnDefinitions.Add(new ColumnDefinition());
Subject.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
Subject.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(PixelColumnWidth) });
children[0] = CreateChild(0, 0);
children[1] = CreateChild(0, 1);
children[2] = CreateChild(0, 2);
children[3] = CreateChild(1, 0);
children[4] = CreateChild(1, 1);
children[5] = CreateChild(1, 2);
children[6] = CreateChild(2, 0);
children[7] = CreateChild(2, 1);
children[8] = CreateChild(2, 2);
children[1].Object.Width = AutoColumnWidth;
children[3].Object.Height = AutoRowHeight;
Subject.Measure(AvailableSize);
};
private Because of = () => Subject.Arrange(new Rect(AvailableSize));
private It should_layout_child_1_correctly =
() => children[0].Object.VisualOffset.ShouldEqual(new Vector(0d, 0d));
private It should_layout_child_2_correctly =
() => children[1].Object.VisualOffset.ShouldEqual(new Vector(StarColumnWidth, 0d));
private It should_layout_child_3_correctly =
() => children[2].Object.VisualOffset.ShouldEqual(new Vector(StarColumnWidth + AutoColumnWidth, 0d));
private It should_layout_child_4_correctly =
() => children[3].Object.VisualOffset.ShouldEqual(new Vector(0d, StarRowHeight));
private It should_layout_child_5_correctly =
() => children[4].Object.VisualOffset.ShouldEqual(new Vector(StarColumnWidth, StarRowHeight));
private It should_layout_child_6_correctly =
() =>
children[5].Object.VisualOffset.ShouldEqual(new Vector(StarColumnWidth + AutoColumnWidth, StarRowHeight));
private It should_layout_child_7_correctly =
() => children[6].Object.VisualOffset.ShouldEqual(new Vector(0d, StarRowHeight + AutoRowHeight));
private It should_layout_child_8_correctly =
() =>
children[7].Object.VisualOffset.ShouldEqual(new Vector(StarColumnWidth, StarRowHeight + AutoRowHeight));
private It should_layout_child_9_correctly =
() =>
children[8].Object.VisualOffset.ShouldEqual(
new Vector(StarColumnWidth + AutoColumnWidth, StarRowHeight + AutoRowHeight));
}
}
| |
//
// TableViewBackend.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using System.Collections.Generic;
using System.Linq;
#if MONOMAC
using nint = System.Int32;
using nfloat = System.Single;
using MonoMac.Foundation;
using MonoMac.AppKit;
#else
using Foundation;
using AppKit;
#endif
namespace Xwt.Mac
{
public abstract class TableViewBackend<T,S>: ViewBackend<NSScrollView,S>, ITableViewBackend, ICellSource
where T:NSTableView where S:ITableViewEventSink
{
List<NSTableColumn> cols = new List<NSTableColumn> ();
protected NSTableView Table;
ScrollView scroll;
NSObject selChangeObserver;
NormalClipView clipView;
public TableViewBackend ()
{
}
public override void Initialize ()
{
Table = CreateView ();
scroll = new ScrollView ();
clipView = new NormalClipView ();
clipView.Scrolled += OnScrolled;
scroll.ContentView = clipView;
scroll.DocumentView = Table;
scroll.BorderType = NSBorderType.BezelBorder;
ViewObject = scroll;
Widget.AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable;
Widget.AutoresizesSubviews = true;
}
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
Util.DrainObjectCopyPool ();
}
public ScrollPolicy VerticalScrollPolicy {
get {
if (scroll.AutohidesScrollers && scroll.HasVerticalScroller)
return ScrollPolicy.Automatic;
else if (scroll.HasVerticalScroller)
return ScrollPolicy.Always;
else
return ScrollPolicy.Never;
}
set {
switch (value) {
case ScrollPolicy.Automatic:
scroll.AutohidesScrollers = true;
scroll.HasVerticalScroller = true;
break;
case ScrollPolicy.Always:
scroll.AutohidesScrollers = false;
scroll.HasVerticalScroller = true;
break;
case ScrollPolicy.Never:
scroll.HasVerticalScroller = false;
break;
}
}
}
public ScrollPolicy HorizontalScrollPolicy {
get {
if (scroll.AutohidesScrollers && scroll.HasHorizontalScroller)
return ScrollPolicy.Automatic;
else if (scroll.HasHorizontalScroller)
return ScrollPolicy.Always;
else
return ScrollPolicy.Never;
}
set {
switch (value) {
case ScrollPolicy.Automatic:
scroll.AutohidesScrollers = true;
scroll.HasHorizontalScroller = true;
break;
case ScrollPolicy.Always:
scroll.AutohidesScrollers = false;
scroll.HasHorizontalScroller = true;
break;
case ScrollPolicy.Never:
scroll.HasHorizontalScroller = false;
break;
}
}
}
ScrollControlBackend vertScroll;
public IScrollControlBackend CreateVerticalScrollControl ()
{
if (vertScroll == null)
vertScroll = new ScrollControlBackend (ApplicationContext, scroll, true);
return vertScroll;
}
ScrollControlBackend horScroll;
public IScrollControlBackend CreateHorizontalScrollControl ()
{
if (horScroll == null)
horScroll = new ScrollControlBackend (ApplicationContext, scroll, false);
return horScroll;
}
void OnScrolled (object o, EventArgs e)
{
if (vertScroll != null)
vertScroll.NotifyValueChanged ();
if (horScroll != null)
horScroll.NotifyValueChanged ();
}
protected override Size GetNaturalSize ()
{
return EventSink.GetDefaultNaturalSize ();
}
protected abstract NSTableView CreateView ();
protected abstract string SelectionChangeEventName { get; }
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is TableViewEvent) {
switch ((TableViewEvent)eventId) {
case TableViewEvent.SelectionChanged:
selChangeObserver = NSNotificationCenter.DefaultCenter.AddObserver (new NSString (SelectionChangeEventName), HandleTreeSelectionDidChange, Table);
break;
}
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is TableViewEvent) {
switch ((TableViewEvent)eventId) {
case TableViewEvent.SelectionChanged:
if (selChangeObserver != null)
NSNotificationCenter.DefaultCenter.RemoveObserver (selChangeObserver);
break;
}
}
}
void HandleTreeSelectionDidChange (NSNotification notif)
{
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnSelectionChanged ();
});
}
public void SetSelectionMode (SelectionMode mode)
{
Table.AllowsMultipleSelection = mode == SelectionMode.Multiple;
}
public virtual NSTableColumn AddColumn (ListViewColumn col)
{
var tcol = new NSTableColumn ();
tcol.Editable = true;
cols.Add (tcol);
var c = CellUtil.CreateCell (ApplicationContext, Table, this, col.Views, cols.Count - 1);
tcol.DataCell = c;
Table.AddColumn (tcol);
var hc = new NSTableHeaderCell ();
hc.Title = col.Title ?? "";
tcol.HeaderCell = hc;
Widget.InvalidateIntrinsicContentSize ();
return tcol;
}
object IColumnContainerBackend.AddColumn (ListViewColumn col)
{
return AddColumn (col);
}
public void RemoveColumn (ListViewColumn col, object handle)
{
Table.RemoveColumn ((NSTableColumn)handle);
}
public void UpdateColumn (ListViewColumn col, object handle, ListViewColumnChange change)
{
NSTableColumn tcol = (NSTableColumn) handle;
var c = CellUtil.CreateCell (ApplicationContext, Table, this, col.Views, cols.IndexOf (tcol));
tcol.DataCell = c;
}
public Rectangle GetCellBounds (int row, CellView cell, bool includeMargin)
{
var cellBackend = cell.GetBackend () as CellViewBackend;
var r = Table.GetCellFrame (cellBackend.Column, row);
var container = Table.GetCell (cellBackend.Column, row) as CompositeCell;
r = container.GetCellRect (r, (NSCell)cellBackend.CurrentCell);
r.Y -= scroll.DocumentVisibleRect.Y;
r.X -= scroll.DocumentVisibleRect.X;
if (HeadersVisible)
r.Y += Table.HeaderView.Frame.Height;
return new Rectangle (r.X, r.Y, r.Width, r.Height);
}
public Rectangle GetRowBounds (int row, bool includeMargin)
{
var rect = Rectangle.Zero;
var columns = Table.TableColumns ();
for (int i = 0; i < columns.Length; i++)
{
var r = Table.GetCellFrame (i, row);
if (rect == Rectangle.Zero)
rect = new Rectangle (r.X, r.Y, r.Width, r.Height);
else
rect = rect.Union (new Rectangle (r.X, r.Y, r.Width, r.Height));
}
rect.Y -= scroll.DocumentVisibleRect.Y;
rect.X -= scroll.DocumentVisibleRect.X;
if (HeadersVisible)
rect.Y += Table.HeaderView.Frame.Height;
return rect;
}
public void SelectAll ()
{
Table.SelectAll (null);
}
public void UnselectAll ()
{
Table.DeselectAll (null);
}
public void ScrollToRow (int row)
{
Table.ScrollRowToVisible (row);
}
public void StartEditingCell (int row, CellView cell)
{
// TODO
}
public abstract object GetValue (object pos, int nField);
public abstract void SetValue (object pos, int nField, object value);
public abstract void SetCurrentEventRow (object pos);
nfloat ICellSource.RowHeight {
get { return Table.RowHeight; }
set { Table.RowHeight = value; }
}
public bool BorderVisible {
get { return scroll.BorderType == NSBorderType.BezelBorder;}
set {
scroll.BorderType = value ? NSBorderType.BezelBorder : NSBorderType.NoBorder;
}
}
public bool HeadersVisible {
get {
return Table.HeaderView != null;
}
set {
if (value) {
if (Table.HeaderView == null)
Table.HeaderView = new NSTableHeaderView ();
} else {
Table.HeaderView = null;
}
}
}
public GridLines GridLinesVisible
{
get { return Table.GridStyleMask.ToXwtValue (); }
set { Table.GridStyleMask = value.ToMacValue (); }
}
}
class ScrollView: NSScrollView, IViewObject
{
public ViewBackend Backend { get; set; }
public NSView View {
get { return this; }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.Linq.Mapping;
using System.Linq.Expressions;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Transactions;
using System.Data.Linq.Provider;
using System.Diagnostics.CodeAnalysis;
namespace System.Data.Linq {
public sealed class CompiledQuery {
LambdaExpression query;
ICompiledQuery compiled;
MappingSource mappingSource;
private CompiledQuery(LambdaExpression query) {
this.query = query;
}
public LambdaExpression Expression {
get { return this.query; }
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TResult> Compile<TArg0, TResult>(Expression<Func<TArg0, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TResult> Compile<TArg0, TArg1, TResult>(Expression<Func<TArg0, TArg1, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TArg2, TResult> Compile<TArg0, TArg1, TArg2, TResult>(Expression<Func<TArg0, TArg1, TArg2, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TArg2, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TArg2, TArg3, TResult> Compile<TArg0, TArg1, TArg2, TArg3, TResult>(Expression<Func<TArg0, TArg1, TArg2, TArg3, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TArg2, TArg3, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TArg2, TArg3, TArg4, TResult> Compile<TArg0, TArg1, TArg2, TArg3, TArg4, TResult>(Expression<Func<TArg0, TArg1, TArg2, TArg3, TArg4, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TResult> Compile<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TResult>(Expression<Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TResult> Compile<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TResult>(Expression<Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TResult> Compile<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TResult>(Expression<Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TResult> Compile<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TResult>(Expression<Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TResult> Compile<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TResult>(Expression<Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TResult> Compile<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TResult>(Expression<Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TResult> Compile<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TResult>(Expression<Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TResult> Compile<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TResult>(Expression<Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TResult> Compile<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TResult>(Expression<Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TResult> Compile<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TResult>(Expression<Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TResult>;
}
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
public static Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TArg15, TResult> Compile<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TArg15, TResult>(Expression<Func<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TArg15, TResult>> query) where TArg0 : DataContext {
if (query == null) {
Error.ArgumentNull("query");
}
if (UseExpressionCompile(query)) {
return query.Compile();
}
else {
return new CompiledQuery(query).Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TArg15, TResult>;
}
}
private static bool UseExpressionCompile(LambdaExpression query) {
return typeof(ITable).IsAssignableFrom(query.Body.Type);
}
private TResult Invoke<TArg0, TResult>(TArg0 arg0) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0});
}
private TResult Invoke<TArg0, TArg1, TResult>(TArg0 arg0, TArg1 arg1) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1});
}
private TResult Invoke<TArg0, TArg1, TArg2, TResult>(TArg0 arg0, TArg1 arg1, TArg2 arg2) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1, arg2});
}
private TResult Invoke<TArg0, TArg1, TArg2, TArg3, TResult>(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1, arg2, arg3});
}
private TResult Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TResult>(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1, arg2, arg3, arg4});
}
private TResult Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TResult>(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1, arg2, arg3, arg4, arg5});
}
private TResult Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TResult>(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1, arg2, arg3, arg4, arg5, arg6});
}
private TResult Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TResult>(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7});
}
private TResult Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TResult>(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7, TArg8 arg8) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8});
}
private TResult Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TResult>(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7, TArg8 arg8, TArg9 arg9) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9});
}
private TResult Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TResult>(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7, TArg8 arg8, TArg9 arg9, TArg10 arg10) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10});
}
private TResult Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TResult>(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7, TArg8 arg8, TArg9 arg9, TArg10 arg10, TArg11 arg11) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11});
}
private TResult Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TResult>(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7, TArg8 arg8, TArg9 arg9, TArg10 arg10, TArg11 arg11, TArg12 arg12) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12});
}
private TResult Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TResult>(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7, TArg8 arg8, TArg9 arg9, TArg10 arg10, TArg11 arg11, TArg12 arg12, TArg13 arg13) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13});
}
private TResult Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TResult>(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7, TArg8 arg8, TArg9 arg9, TArg10 arg10, TArg11 arg11, TArg12 arg12, TArg13 arg13, TArg14 arg14) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14});
}
private TResult Invoke<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TArg15, TResult>(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7, TArg8 arg8, TArg9 arg9, TArg10 arg10, TArg11 arg11, TArg12 arg12, TArg13 arg13, TArg14 arg14, TArg15 arg15) where TArg0 : DataContext {
return (TResult) this.ExecuteQuery(arg0, new object[] {arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15});
}
private object ExecuteQuery(DataContext context, object[] args) {
if (context == null) {
throw Error.ArgumentNull("context");
}
if (this.compiled == null) {
lock (this) {
if (this.compiled == null) {
this.compiled = context.Provider.Compile(this.query);
this.mappingSource = context.Mapping.MappingSource;
}
}
}
else {
if (context.Mapping.MappingSource != this.mappingSource)
throw Error.QueryWasCompiledForDifferentMappingSource();
}
return this.compiled.Execute(context.Provider, args).ReturnValue;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
using Microsoft.DotNet.XUnitExtensions;
namespace System.IO.Ports.Tests
{
public class Write_byte_int_int_generic : PortsTest
{
//Set bounds fore random timeout values.
//If the min is to low write will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
//If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
//If the percentage difference between the expected timeout and the actual timeout
//found through Stopwatch is greater then 10% then the timeout value was not correctly
//to the write method and the testcase fails.
private const double maxPercentageDifference = .15;
//The byte size used when veryifying exceptions that write will throw
private const int BYTE_SIZE_EXCEPTION = 4;
//The byte size used when veryifying timeout
private const int BYTE_SIZE_TIMEOUT = 4;
//The byte size used when veryifying BytesToWrite
private const int BYTE_SIZE_BYTES_TO_WRITE = 4;
//The bytes size used when veryifying Handshake
private const int BYTE_SIZE_HANDSHAKE = 8;
private const int NUM_TRYS = 5;
#region Test Cases
[Fact]
public void WriteWithoutOpen()
{
using (SerialPort com = new SerialPort())
{
Debug.WriteLine("Verifying write method throws exception without a call to Open()");
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterFailedOpen()
{
using (SerialPort com = new SerialPort("BAD_PORT_NAME"))
{
Debug.WriteLine("Verifying write method throws exception with a failed call to Open()");
//Since the PortName is set to a bad port name Open will thrown an exception
//however we don't care what it is since we are verfifying a write method
Assert.ThrowsAny<Exception>(() => com.Open());
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying write method throws exception after a call to Cloes()");
com.Open();
com.Close();
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Timeout()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] XOffBuffer = new byte[1];
XOffBuffer[0] = 19;
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.XOnXOff;
Debug.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout);
com1.Open();
com2.Open();
com2.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
com2.Close();
VerifyTimeout(com1);
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com.Handshake = Handshake.RequestToSendXOnXOff;
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout);
com.Open();
try
{
com.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT);
}
catch (TimeoutException)
{
}
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeoutWithWriteSucceeding()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
AsyncEnableRts asyncEnableRts = new AsyncEnableRts();
var t = new Task(asyncEnableRts.EnableRTS);
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.RequestToSend;
com1.Encoding = new UTF8Encoding();
Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout", com1.WriteTimeout);
com1.Open();
//Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed
//before the timeout is reached
t.Start();
TCSupport.WaitForTaskToStart(t);
try
{
com1.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT);
}
catch (TimeoutException)
{
}
asyncEnableRts.Stop();
TCSupport.WaitForTaskCompletion(t);
VerifyTimeout(com1);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void BytesToWrite()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_BYTES_TO_WRITE);
var t = new Task(asyncWriteRndByteArray.WriteRndByteArray);
Debug.WriteLine("Verifying BytesToWrite with one call to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 500;
//Write a random byte[] asynchronously so we can verify some things while the write call is blocking
t.Start();
TCSupport.WaitForTaskToStart(t);
TCSupport.WaitForExactWriteBufferLoad(com, BYTE_SIZE_BYTES_TO_WRITE);
//Wait for write method to timeout
TCSupport.WaitForTaskCompletion(t);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void BytesToWriteSuccessive()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_BYTES_TO_WRITE);
var t1 = new Task(asyncWriteRndByteArray.WriteRndByteArray);
var t2 = new Task(asyncWriteRndByteArray.WriteRndByteArray);
Debug.WriteLine("Verifying BytesToWrite with successive calls to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 1000;
//Write a random byte[] asynchronously so we can verify some things while the write call is blocking
t1.Start();
TCSupport.WaitForTaskToStart(t1);
TCSupport.WaitForExactWriteBufferLoad(com, BYTE_SIZE_BYTES_TO_WRITE);
//Write a random byte[] asynchronously so we can verify some things while the write call is blocking
t2.Start();
TCSupport.WaitForTaskToStart(t2);
TCSupport.WaitForExactWriteBufferLoad(com, BYTE_SIZE_BYTES_TO_WRITE * 2);
//Wait for both write methods to timeout
TCSupport.WaitForTaskCompletion(t1);
var aggregatedException = Assert.Throws<AggregateException>(() => TCSupport.WaitForTaskCompletion(t2));
Assert.IsType<IOException>(aggregatedException.InnerException);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_None()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_HANDSHAKE);
var t = new Task(asyncWriteRndByteArray.WriteRndByteArray);
//Write a random byte[] asynchronously so we can verify some things while the write call is blocking
Debug.WriteLine("Verifying Handshake=None");
com.Open();
t.Start();
TCSupport.WaitForTaskCompletion(t);
if (0 != com.BytesToWrite)
{
Fail("ERROR!!! Expcted BytesToWrite=0 actual {0}", com.BytesToWrite);
}
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSend()
{
Verify_Handshake(Handshake.RequestToSend);
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_XOnXOff()
{
Verify_Handshake(Handshake.XOnXOff);
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSendXOnXOff()
{
Verify_Handshake(Handshake.RequestToSendXOnXOff);
}
private class AsyncEnableRts
{
private bool _stop;
public void EnableRTS()
{
lock (this)
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
//Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.RtsEnable = true;
while (!_stop)
Monitor.Wait(this);
com2.RtsEnable = false;
}
}
}
public void Stop()
{
lock (this)
{
_stop = true;
Monitor.Pulse(this);
}
}
}
private class AsyncWriteRndByteArray
{
private readonly SerialPort _com;
private readonly int _byteLength;
public AsyncWriteRndByteArray(SerialPort com, int byteLength)
{
_com = com;
_byteLength = byteLength;
}
public void WriteRndByteArray()
{
byte[] buffer = new byte[_byteLength];
Random rndGen = new Random(-55);
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)rndGen.Next(0, 256);
}
try
{
_com.Write(buffer, 0, buffer.Length);
}
catch (TimeoutException)
{
}
}
}
#endregion
#region Verification for Test Cases
private static void VerifyWriteException(SerialPort com, Type expectedException)
{
Assert.Throws(expectedException, () => com.Write(new byte[BYTE_SIZE_EXCEPTION], 0, BYTE_SIZE_EXCEPTION));
}
private void VerifyTimeout(SerialPort com)
{
Stopwatch timer = new Stopwatch();
int expectedTime = com.WriteTimeout;
int actualTime = 0;
double percentageDifference;
try
{
com.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT); //Warm up write method
}
catch (TimeoutException) { }
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
timer.Start();
try
{
com.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT);
}
catch (TimeoutException) { }
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
//Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void Verify_Handshake(Handshake handshake)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com1, BYTE_SIZE_HANDSHAKE);
var t = new Task(asyncWriteRndByteArray.WriteRndByteArray);
byte[] XOffBuffer = new byte[1];
byte[] XOnBuffer = new byte[1];
XOffBuffer[0] = 19;
XOnBuffer[0] = 17;
Debug.WriteLine("Verifying Handshake={0}", handshake);
com1.Handshake = handshake;
com1.Open();
com2.Open();
//Setup to ensure write will bock with type of handshake method being used
if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.RtsEnable = false;
}
if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
}
//Write a random byte asynchronously so we can verify some things while the write call is blocking
t.Start();
TCSupport.WaitForTaskToStart(t);
TCSupport.WaitForExactWriteBufferLoad(com1, BYTE_SIZE_HANDSHAKE);
//Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used
if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding)
{
Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding);
}
//Setup to ensure write will succeed
if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.RtsEnable = true;
}
if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.Write(XOnBuffer, 0, 1);
}
TCSupport.WaitForTaskCompletion(t);
Assert.Equal(0, com1.BytesToWrite);
//Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used
if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) &&
!com1.CtsHolding)
{
Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", true, com1.CtsHolding);
}
}
}
#endregion
}
}
| |
//
// System.Web.UI.WebControls.DetailsView.cs
//
// Authors:
// Lluis Sanchez Gual ([email protected])
//
// (C) 2005 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.
//
#if NET_2_0
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Web.UI;
using System.Security.Permissions;
using System.Text;
using System.IO;
using System.Reflection;
namespace System.Web.UI.WebControls
{
[ToolboxDataAttribute ("<{0}:DetailsView runat=\"server\" Width=\"125px\" Height=\"50px\"></{0}:DetailsView>")]
[DesignerAttribute ("System.Web.UI.Design.WebControls.DetailsViewDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ComponentModel.Design.IDesigner")]
[ControlValuePropertyAttribute ("SelectedValue")]
[DefaultEventAttribute ("PageIndexChanging")]
[AspNetHostingPermissionAttribute (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermissionAttribute (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class DetailsView: CompositeDataBoundControl, ICallbackEventHandler, ICallbackContainer, IDataItemContainer
{
object dataItem;
Table table;
DetailsViewRowCollection rows;
DetailsViewRow headerRow;
DetailsViewRow footerRow;
DetailsViewRow bottomPagerRow;
DetailsViewRow topPagerRow;
IOrderedDictionary currentEditRowKeys;
IOrderedDictionary currentEditNewValues;
IOrderedDictionary currentEditOldValues;
ITemplate pagerTemplate;
ITemplate emptyDataTemplate;
ITemplate headerTemplate;
ITemplate footerTemplate;
PropertyDescriptor[] cachedKeyProperties;
readonly string[] emptyKeys = new string[0];
CommandField commandField;
DetailsViewRow commandRow;
// View state
DataControlFieldCollection columns;
PagerSettings pagerSettings;
TableItemStyle alternatingRowStyle;
TableItemStyle editRowStyle;
TableItemStyle insertRowStyle;
TableItemStyle emptyDataRowStyle;
TableItemStyle footerStyle;
TableItemStyle headerStyle;
TableItemStyle pagerStyle;
TableItemStyle rowStyle;
TableItemStyle commandRowStyle;
TableItemStyle fieldHeaderStyle;
DataKey key;
DataKey oldEditValues;
AutoGeneratedFieldProperties[] autoFieldProperties;
private static readonly object PageIndexChangedEvent = new object();
private static readonly object PageIndexChangingEvent = new object();
private static readonly object ItemCommandEvent = new object();
private static readonly object ItemCreatedEvent = new object();
private static readonly object ItemDeletedEvent = new object();
private static readonly object ItemDeletingEvent = new object();
private static readonly object ItemInsertedEvent = new object();
private static readonly object ItemInsertingEvent = new object();
private static readonly object ModeChangingEvent = new object();
private static readonly object ModeChangedEvent = new object();
private static readonly object ItemUpdatedEvent = new object();
private static readonly object ItemUpdatingEvent = new object();
// Control state
int pageIndex;
DetailsViewMode currentMode = DetailsViewMode.ReadOnly;
int pageCount = -1;
public DetailsView ()
{
}
public event EventHandler PageIndexChanged {
add { Events.AddHandler (PageIndexChangedEvent, value); }
remove { Events.RemoveHandler (PageIndexChangedEvent, value); }
}
public event DetailsViewPageEventHandler PageIndexChanging {
add { Events.AddHandler (PageIndexChangingEvent, value); }
remove { Events.RemoveHandler (PageIndexChangingEvent, value); }
}
public event DetailsViewCommandEventHandler ItemCommand {
add { Events.AddHandler (ItemCommandEvent, value); }
remove { Events.RemoveHandler (ItemCommandEvent, value); }
}
public event EventHandler ItemCreated {
add { Events.AddHandler (ItemCreatedEvent, value); }
remove { Events.RemoveHandler (ItemCreatedEvent, value); }
}
public event DetailsViewDeletedEventHandler ItemDeleted {
add { Events.AddHandler (ItemDeletedEvent, value); }
remove { Events.RemoveHandler (ItemDeletedEvent, value); }
}
public event DetailsViewDeleteEventHandler ItemDeleting {
add { Events.AddHandler (ItemDeletingEvent, value); }
remove { Events.RemoveHandler (ItemDeletingEvent, value); }
}
public event DetailsViewInsertedEventHandler ItemInserted {
add { Events.AddHandler (ItemInsertedEvent, value); }
remove { Events.RemoveHandler (ItemInsertedEvent, value); }
}
public event DetailsViewInsertEventHandler ItemInserting {
add { Events.AddHandler (ItemInsertingEvent, value); }
remove { Events.RemoveHandler (ItemInsertingEvent, value); }
}
public event DetailsViewModeEventHandler ModeChanging {
add { Events.AddHandler (ModeChangingEvent, value); }
remove { Events.RemoveHandler (ModeChangingEvent, value); }
}
public event EventHandler ModeChanged {
add { Events.AddHandler (ModeChangedEvent, value); }
remove { Events.RemoveHandler (ModeChangedEvent, value); }
}
public event DetailsViewUpdatedEventHandler ItemUpdated {
add { Events.AddHandler (ItemUpdatedEvent, value); }
remove { Events.RemoveHandler (ItemUpdatedEvent, value); }
}
public event DetailsViewUpdateEventHandler ItemUpdating {
add { Events.AddHandler (ItemUpdatingEvent, value); }
remove { Events.RemoveHandler (ItemUpdatingEvent, value); }
}
protected virtual void OnPageIndexChanged (EventArgs e)
{
if (Events != null) {
EventHandler eh = (EventHandler) Events [PageIndexChangedEvent];
if (eh != null) eh (this, e);
}
}
protected virtual void OnPageIndexChanging (DetailsViewPageEventArgs e)
{
if (Events != null) {
DetailsViewPageEventHandler eh = (DetailsViewPageEventHandler) Events [PageIndexChangingEvent];
if (eh != null) eh (this, e);
}
}
protected virtual void OnItemCommand (DetailsViewCommandEventArgs e)
{
if (Events != null) {
DetailsViewCommandEventHandler eh = (DetailsViewCommandEventHandler) Events [ItemCommandEvent];
if (eh != null) eh (this, e);
}
}
protected virtual void OnItemCreated (EventArgs e)
{
if (Events != null) {
EventHandler eh = (EventHandler) Events [ItemCreatedEvent];
if (eh != null) eh (this, e);
}
}
protected virtual void OnItemDeleted (DetailsViewDeletedEventArgs e)
{
if (Events != null) {
DetailsViewDeletedEventHandler eh = (DetailsViewDeletedEventHandler) Events [ItemDeletedEvent];
if (eh != null) eh (this, e);
}
}
protected virtual void OnItemInserted (DetailsViewInsertedEventArgs e)
{
if (Events != null) {
DetailsViewInsertedEventHandler eh = (DetailsViewInsertedEventHandler) Events [ItemInsertedEvent];
if (eh != null) eh (this, e);
}
}
protected virtual void OnItemInserting (DetailsViewInsertEventArgs e)
{
if (Events != null) {
DetailsViewInsertEventHandler eh = (DetailsViewInsertEventHandler) Events [ItemInsertingEvent];
if (eh != null) eh (this, e);
}
}
protected virtual void OnItemDeleting (DetailsViewDeleteEventArgs e)
{
if (Events != null) {
DetailsViewDeleteEventHandler eh = (DetailsViewDeleteEventHandler) Events [ItemDeletingEvent];
if (eh != null) eh (this, e);
}
}
protected virtual void OnModeChanged (EventArgs e)
{
if (Events != null) {
EventHandler eh = (EventHandler) Events [ModeChangedEvent];
if (eh != null) eh (this, e);
}
}
protected virtual void OnModeChanging (DetailsViewModeEventArgs e)
{
if (Events != null) {
DetailsViewModeEventHandler eh = (DetailsViewModeEventHandler) Events [ModeChangingEvent];
if (eh != null) eh (this, e);
}
}
protected virtual void OnItemUpdated (DetailsViewUpdatedEventArgs e)
{
if (Events != null) {
DetailsViewUpdatedEventHandler eh = (DetailsViewUpdatedEventHandler) Events [ItemUpdatedEvent];
if (eh != null) eh (this, e);
}
}
protected virtual void OnItemUpdating (DetailsViewUpdateEventArgs e)
{
if (Events != null) {
DetailsViewUpdateEventHandler eh = (DetailsViewUpdateEventHandler) Events [ItemUpdatingEvent];
if (eh != null) eh (this, e);
}
}
[WebCategoryAttribute ("Paging")]
[DefaultValueAttribute (false)]
public bool AllowPaging {
get {
object ob = ViewState ["AllowPaging"];
if (ob != null) return (bool) ob;
return false;
}
set {
ViewState ["AllowPaging"] = value;
RequireBinding ();
}
}
[DefaultValueAttribute (null)]
[WebCategoryAttribute ("Styles")]
[PersistenceMode (PersistenceMode.InnerProperty)]
[NotifyParentProperty (true)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
public virtual TableItemStyle AlternatingRowStyle {
get {
if (alternatingRowStyle == null) {
alternatingRowStyle = new TableItemStyle ();
if (IsTrackingViewState)
alternatingRowStyle.TrackViewState();
}
return alternatingRowStyle;
}
}
[WebCategoryAttribute ("Behavior")]
[DefaultValueAttribute (false)]
public virtual bool AutoGenerateEditButton {
get {
object ob = ViewState ["AutoGenerateEditButton"];
if (ob != null) return (bool) ob;
return false;
}
set {
ViewState ["AutoGenerateEditButton"] = value;
RequireBinding ();
}
}
[WebCategoryAttribute ("Behavior")]
[DefaultValueAttribute (false)]
public virtual bool AutoGenerateDeleteButton {
get {
object ob = ViewState ["AutoGenerateDeleteButton"];
if (ob != null) return (bool) ob;
return false;
}
set {
ViewState ["AutoGenerateDeleteButton"] = value;
RequireBinding ();
}
}
[WebCategoryAttribute ("Behavior")]
[DefaultValueAttribute (false)]
public virtual bool AutoGenerateInsertButton {
get {
object ob = ViewState ["AutoGenerateInsertButton"];
if (ob != null) return (bool) ob;
return false;
}
set {
ViewState ["AutoGenerateInsertButton"] = value;
RequireBinding ();
}
}
[WebCategoryAttribute ("Behavior")]
[DefaultValueAttribute (true)]
public virtual bool AutoGenerateRows {
get {
object ob = ViewState ["AutoGenerateRows"];
if (ob != null) return (bool) ob;
return true;
}
set {
ViewState ["AutoGenerateRows"] = value;
RequireBinding ();
}
}
[UrlPropertyAttribute]
[WebCategoryAttribute ("Appearance")]
[DefaultValueAttribute ("")]
[EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public virtual string BackImageUrl {
get {
object ob = ViewState ["BackImageUrl"];
if (ob != null) return (string) ob;
return string.Empty;
}
set {
ViewState ["BackImageUrl"] = value;
RequireBinding ();
}
}
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute (false)]
public virtual DetailsViewRow BottomPagerRow {
get {
EnsureDataBound ();
return bottomPagerRow;
}
}
[WebCategoryAttribute ("Accessibility")]
[DefaultValueAttribute ("")]
[LocalizableAttribute (true)]
public string Caption {
get {
object ob = ViewState ["Caption"];
if (ob != null) return (string) ob;
return string.Empty;
}
set {
ViewState ["Caption"] = value;
RequireBinding ();
}
}
[WebCategoryAttribute ("Accessibility")]
[DefaultValueAttribute (TableCaptionAlign.NotSet)]
public virtual TableCaptionAlign CaptionAlign
{
get {
object o = ViewState ["CaptionAlign"];
if(o != null) return (TableCaptionAlign) o;
return TableCaptionAlign.NotSet;
}
set {
ViewState ["CaptionAlign"] = value;
RequireBinding ();
}
}
[WebCategoryAttribute ("Layout")]
[DefaultValueAttribute (-1)]
public virtual int CellPadding
{
get {
object o = ViewState ["CellPadding"];
if (o != null) return (int) o;
return -1;
}
set {
ViewState ["CellPadding"] = value;
RequireBinding ();
}
}
[WebCategoryAttribute ("Layout")]
[DefaultValueAttribute (0)]
public virtual int CellSpacing
{
get {
object o = ViewState ["CellSpacing"];
if (o != null) return (int) o;
return 0;
}
set {
ViewState ["CellSpacing"] = value;
RequireBinding ();
}
}
[DefaultValueAttribute (null)]
[WebCategoryAttribute ("Styles")]
[PersistenceMode (PersistenceMode.InnerProperty)]
[NotifyParentProperty (true)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
public virtual TableItemStyle CommandRowStyle {
get {
if (commandRowStyle == null) {
commandRowStyle = new TableItemStyle ();
if (IsTrackingViewState)
commandRowStyle.TrackViewState();
}
return commandRowStyle;
}
}
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute (false)]
public DetailsViewMode CurrentMode {
get {
return currentMode;
}
}
[DefaultValueAttribute (DetailsViewMode.ReadOnly)]
[WebCategoryAttribute ("Behavior")]
public virtual DetailsViewMode DefaultMode {
get {
object o = ViewState ["DefaultMode"];
if (o != null) return (DetailsViewMode) o;
return DetailsViewMode.ReadOnly;
}
set {
ViewState ["DefaultMode"] = value;
RequireBinding ();
}
}
[EditorAttribute ("System.Web.UI.Design.WebControls.DataControlFieldTypeEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[MergablePropertyAttribute (false)]
[PersistenceModeAttribute (PersistenceMode.InnerProperty)]
[DefaultValueAttribute (null)]
[WebCategoryAttribute ("Misc")]
public virtual DataControlFieldCollection Fields {
get {
if (columns == null) {
columns = new DataControlFieldCollection ();
columns.FieldsChanged += new EventHandler (OnFieldsChanged);
if (IsTrackingViewState)
((IStateManager)columns).TrackViewState ();
}
return columns;
}
}
[DefaultValueAttribute (null)]
[WebCategoryAttribute ("Data")]
[TypeConverter (typeof(StringArrayConverter))]
[EditorAttribute ("System.Web.UI.Design.WebControls.DataFieldEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public virtual string[] DataKeyNames
{
get {
object o = ViewState ["DataKeyNames"];
if (o != null) return (string[]) o;
return emptyKeys;
}
set {
ViewState ["DataKeyNames"] = value;
RequireBinding ();
}
}
[BrowsableAttribute (false)]
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
public virtual DataKey DataKey {
get {
EnsureDataBound ();
return key;
}
}
[WebCategoryAttribute ("Styles")]
[PersistenceMode (PersistenceMode.InnerProperty)]
[NotifyParentProperty (true)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
[DefaultValueAttribute (null)]
public virtual TableItemStyle EditRowStyle {
get {
if (editRowStyle == null) {
editRowStyle = new TableItemStyle ();
if (IsTrackingViewState)
editRowStyle.TrackViewState();
}
return editRowStyle;
}
}
[WebCategoryAttribute ("Styles")]
[PersistenceMode (PersistenceMode.InnerProperty)]
[NotifyParentProperty (true)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
[DefaultValueAttribute (null)]
public virtual TableItemStyle EmptyDataRowStyle {
get {
if (emptyDataRowStyle == null) {
emptyDataRowStyle = new TableItemStyle ();
if (IsTrackingViewState)
emptyDataRowStyle.TrackViewState();
}
return emptyDataRowStyle;
}
}
[DefaultValue (null)]
[TemplateContainer (typeof(DetailsView), BindingDirection.OneWay)]
[PersistenceMode (PersistenceMode.InnerProperty)]
[Browsable (false)]
public ITemplate EmptyDataTemplate {
get { return emptyDataTemplate; }
set { emptyDataTemplate = value; RequireBinding (); }
}
[LocalizableAttribute (true)]
[WebCategoryAttribute ("Appearance")]
[DefaultValueAttribute ("")]
public virtual string EmptyDataText {
get {
object ob = ViewState ["EmptyDataText"];
if (ob != null) return (string) ob;
return string.Empty;
}
set {
ViewState ["EmptyDataText"] = value;
RequireBinding ();
}
}
[WebCategoryAttribute ("Behavior")]
[DefaultValueAttribute (false)]
public virtual bool EnablePagingCallbacks {
get {
object ob = ViewState ["EnablePagingCallbacks"];
if (ob != null) return (bool) ob;
return false;
}
set {
ViewState ["EnablePagingCallbacks"] = value;
RequireBinding ();
}
}
[WebCategoryAttribute ("Styles")]
[PersistenceMode (PersistenceMode.InnerProperty)]
[NotifyParentProperty (true)]
[DefaultValue (null)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
public virtual TableItemStyle FieldHeaderStyle {
get {
if (fieldHeaderStyle == null) {
fieldHeaderStyle = new TableItemStyle ();
if (IsTrackingViewState)
fieldHeaderStyle.TrackViewState();
}
return fieldHeaderStyle;
}
}
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute (false)]
public virtual DetailsViewRow FooterRow {
get {
EnsureChildControls ();
return footerRow;
}
}
[DefaultValue (null)]
[TemplateContainer (typeof(DetailsView), BindingDirection.OneWay)]
[PersistenceMode (PersistenceMode.InnerProperty)]
[Browsable (false)]
public ITemplate FooterTemplate {
get { return footerTemplate; }
set { footerTemplate = value; RequireBinding (); }
}
[LocalizableAttribute (true)]
[WebCategoryAttribute ("Appearance")]
[DefaultValueAttribute ("")]
public string FooterText {
get {
object ob = ViewState ["FooterText"];
if (ob != null) return (string) ob;
return string.Empty;
}
set {
ViewState ["FooterText"] = value;
RequireBinding ();
}
}
[WebCategoryAttribute ("Styles")]
[PersistenceMode (PersistenceMode.InnerProperty)]
[NotifyParentProperty (true)]
[DefaultValue (null)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
public virtual TableItemStyle FooterStyle {
get {
if (footerStyle == null) {
footerStyle = new TableItemStyle ();
if (IsTrackingViewState)
footerStyle.TrackViewState();
}
return footerStyle;
}
}
[WebCategoryAttribute ("Appearance")]
[DefaultValueAttribute (GridLines.Both)]
public virtual GridLines GridLines {
get {
object ob = ViewState ["GridLines"];
if (ob != null) return (GridLines) ob;
return GridLines.Both;
}
set {
ViewState ["GridLines"] = value;
}
}
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute (false)]
public virtual DetailsViewRow HeaderRow {
get {
EnsureChildControls ();
return headerRow;
}
}
[WebCategoryAttribute ("Styles")]
[PersistenceMode (PersistenceMode.InnerProperty)]
[NotifyParentProperty (true)]
[DefaultValue (null)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
public virtual TableItemStyle HeaderStyle {
get {
if (headerStyle == null) {
headerStyle = new TableItemStyle ();
if (IsTrackingViewState)
headerStyle.TrackViewState();
}
return headerStyle;
}
}
[DefaultValue (null)]
[TemplateContainer (typeof(DetailsView), BindingDirection.OneWay)]
[PersistenceMode (PersistenceMode.InnerProperty)]
[Browsable (false)]
public ITemplate HeaderTemplate {
get { return headerTemplate; }
set { headerTemplate = value; RequireBinding (); }
}
[LocalizableAttribute (true)]
[WebCategoryAttribute ("Appearance")]
[DefaultValueAttribute ("")]
public string HeaderText {
get {
object ob = ViewState ["HeaderText"];
if (ob != null) return (string) ob;
return string.Empty;
}
set {
ViewState ["HeaderText"] = value;
RequireBinding ();
}
}
[DefaultValueAttribute (HorizontalAlign.NotSet)]
public virtual HorizontalAlign HorizontalAlign {
get {
object ob = ViewState ["HorizontalAlign"];
if (ob != null) return (HorizontalAlign) ob;
return HorizontalAlign.NotSet;
}
set {
ViewState ["HorizontalAlign"] = value;
RequireBinding ();
}
}
[WebCategoryAttribute ("Styles")]
[PersistenceMode (PersistenceMode.InnerProperty)]
[NotifyParentProperty (true)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
[DefaultValueAttribute (null)]
public virtual TableItemStyle InsertRowStyle {
get {
if (insertRowStyle == null) {
insertRowStyle = new TableItemStyle ();
if (IsTrackingViewState)
insertRowStyle.TrackViewState();
}
return insertRowStyle;
}
}
[BrowsableAttribute (false)]
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
public int PageCount {
get {
if (pageCount != -1) return pageCount;
EnsureDataBound ();
return pageCount;
}
}
[WebCategoryAttribute ("Paging")]
[BindableAttribute (true, BindingDirection.OneWay)]
[DefaultValueAttribute (0)]
public int PageIndex {
get {
return pageIndex;
}
set {
pageIndex = value;
RequireBinding ();
}
}
[WebCategoryAttribute ("Paging")]
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
[NotifyParentPropertyAttribute (true)]
[PersistenceModeAttribute (PersistenceMode.InnerProperty)]
public PagerSettings PagerSettings {
get {
if (pagerSettings == null) {
pagerSettings = new PagerSettings (this);
if (IsTrackingViewState)
((IStateManager)pagerSettings).TrackViewState ();
}
return pagerSettings;
}
}
[WebCategoryAttribute ("Styles")]
[PersistenceMode (PersistenceMode.InnerProperty)]
[NotifyParentProperty (true)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
public virtual TableItemStyle PagerStyle {
get {
if (pagerStyle == null) {
pagerStyle = new TableItemStyle ();
if (IsTrackingViewState)
pagerStyle.TrackViewState();
}
return pagerStyle;
}
}
[DefaultValue (null)]
[TemplateContainer (typeof(DetailsView), BindingDirection.OneWay)]
[PersistenceMode (PersistenceMode.InnerProperty)]
[Browsable (false)]
public ITemplate PagerTemplate {
get { return pagerTemplate; }
set { pagerTemplate = value; RequireBinding (); }
}
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute (false)]
public virtual DetailsViewRowCollection Rows {
get {
EnsureDataBound ();
return rows;
}
}
[WebCategoryAttribute ("Styles")]
[PersistenceMode (PersistenceMode.InnerProperty)]
[NotifyParentProperty (true)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
[DefaultValue (null)]
public virtual TableItemStyle RowStyle {
get {
if (rowStyle == null) {
rowStyle = new TableItemStyle ();
if (IsTrackingViewState)
rowStyle.TrackViewState();
}
return rowStyle;
}
}
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute (false)]
public virtual object SelectedValue {
get { return DataKey.Value; }
}
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute (false)]
public virtual DetailsViewRow TopPagerRow {
get {
EnsureDataBound ();
return topPagerRow;
}
}
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute (false)]
public object DataItem {
get {
EnsureDataBound ();
return dataItem;
}
}
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute (false)]
public int DataItemCount {
get { return PageCount; }
}
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute (false)]
public int DataItemIndex {
get { return PageIndex; }
}
int IDataItemContainer.DisplayIndex {
get { return PageIndex; }
}
public virtual bool IsBindableType (Type type)
{
return type.IsPrimitive || type == typeof(string) || type == typeof(DateTime) || type == typeof(Guid);
}
protected override DataSourceSelectArguments CreateDataSourceSelectArguments ()
{
return base.CreateDataSourceSelectArguments ();
}
protected virtual ICollection CreateFieldSet (object dataItem, bool useDataSource)
{
ArrayList fields = new ArrayList ();
if (AutoGenerateRows) {
if (useDataSource) {
if (dataItem != null)
fields.AddRange (CreateAutoGeneratedRows (dataItem));
} else {
if (autoFieldProperties != null) {
foreach (AutoGeneratedFieldProperties props in autoFieldProperties)
fields.Add (CreateAutoGeneratedRow (props));
}
}
}
fields.AddRange (Fields);
if (AutoGenerateEditButton || AutoGenerateDeleteButton || AutoGenerateInsertButton) {
CommandField field = new CommandField ();
field.ShowEditButton = AutoGenerateEditButton;
field.ShowDeleteButton = AutoGenerateDeleteButton;
field.ShowInsertButton = AutoGenerateInsertButton;
fields.Add (field);
commandField = field;
}
return fields;
}
protected virtual ICollection CreateAutoGeneratedRows (object dataItem)
{
ArrayList list = new ArrayList ();
autoFieldProperties = CreateAutoFieldProperties (dataItem);
foreach (AutoGeneratedFieldProperties props in autoFieldProperties)
list.Add (CreateAutoGeneratedRow (props));
return list;
}
protected virtual AutoGeneratedField CreateAutoGeneratedRow (AutoGeneratedFieldProperties fieldProperties)
{
return new AutoGeneratedField (fieldProperties);
}
AutoGeneratedFieldProperties[] CreateAutoFieldProperties (object dataItem)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties (dataItem);
ArrayList retVal = new ArrayList();
if (props != null && props.Count > 0)
{
foreach (PropertyDescriptor current in props) {
if (IsBindableType (current.PropertyType)) {
AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
((IStateManager)field).TrackViewState();
field.Name = current.Name;
field.DataField = current.Name;
field.IsReadOnly = current.IsReadOnly;
field.Type = current.PropertyType;
retVal.Add (field);
}
}
}
if (retVal.Count > 0)
return (AutoGeneratedFieldProperties[]) retVal.ToArray (typeof(AutoGeneratedFieldProperties));
else
return new AutoGeneratedFieldProperties [0];
}
protected virtual DetailsViewRow CreateRow (int rowIndex, DataControlRowType rowType, DataControlRowState rowState)
{
DetailsViewRow row = new DetailsViewRow (rowIndex, rowType, rowState);
OnItemCreated (EventArgs.Empty);
return row;
}
void RequireBinding ()
{
if (Initialized) {
RequiresDataBinding = true;
pageCount = -1;
}
}
protected virtual Table CreateTable ()
{
Table table = new Table ();
table.Caption = Caption;
table.CaptionAlign = CaptionAlign;
table.CellPadding = CellPadding;
table.CellSpacing = CellSpacing;
table.HorizontalAlign = HorizontalAlign;
table.BackImageUrl = BackImageUrl;
return table;
}
protected override int CreateChildControls (IEnumerable data, bool dataBinding)
{
PagedDataSource dataSource;
if (dataBinding) {
DataSourceView view = GetData ();
dataSource = new PagedDataSource ();
dataSource.DataSource = data;
if (AllowPaging) {
dataSource.AllowPaging = true;
dataSource.PageSize = 1;
dataSource.CurrentPageIndex = PageIndex;
if (view.CanPage) {
dataSource.AllowServerPaging = true;
if (view.CanRetrieveTotalRowCount)
dataSource.VirtualCount = SelectArguments.TotalRowCount;
else {
dataSource.DataSourceView = view;
dataSource.DataSourceSelectArguments = SelectArguments;
dataSource.SetItemCountFromPageIndex (PageIndex + PagerSettings.PageButtonCount);
}
}
}
pageCount = dataSource.PageCount;
}
else
{
dataSource = new PagedDataSource ();
dataSource.DataSource = data;
if (AllowPaging) {
dataSource.AllowPaging = true;
dataSource.PageSize = 1;
dataSource.CurrentPageIndex = PageIndex;
}
}
bool showPager = AllowPaging && (PageCount > 1);
Controls.Clear ();
table = CreateTable ();
Controls.Add (table);
ArrayList list = new ArrayList ();
if (!Page.IsPostBack)
currentMode = DefaultMode;
// Gets the current data item
IEnumerator e = dataSource.GetEnumerator ();
if (e.MoveNext ())
dataItem = e.Current;
else
dataItem = null;
// Creates the set of fields to show
ICollection fieldCollection = CreateFieldSet (dataItem, dataBinding);
DataControlField[] fields = new DataControlField [fieldCollection.Count];
fieldCollection.CopyTo (fields, 0);
foreach (DataControlField field in fields) {
field.Initialize (false, this);
if (EnablePagingCallbacks)
field.ValidateSupportsCallback ();
}
// Main table creation
if (HeaderText.Length != 0 || headerTemplate != null) {
headerRow = CreateRow (-1, DataControlRowType.Header, DataControlRowState.Normal);
DataControlFieldCell cell = new DataControlFieldCell (null);
cell.ColumnSpan = 2;
if (headerTemplate != null)
headerTemplate.InstantiateIn (cell);
else
cell.Text = HeaderText;
headerRow.Cells.Add (cell);
table.Rows.Add (headerRow);
}
if (showPager && PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom) {
topPagerRow = CreateRow (-1, DataControlRowType.Pager, DataControlRowState.Normal);
InitializePager (topPagerRow, dataSource);
table.Rows.Add (topPagerRow);
}
if (dataSource.Count > 0) {
foreach (DataControlField field in fields) {
DataControlRowState rstate = GetRowState (list.Count);
DetailsViewRow row = CreateRow (list.Count, DataControlRowType.DataRow, rstate);
InitializeRow (row, field);
table.Rows.Add (row);
list.Add (row);
if (commandField == field)
commandRow = row;
}
if (!dataBinding) {
if (CurrentMode == DetailsViewMode.Edit)
oldEditValues = new DataKey (new OrderedDictionary ());
key = new DataKey (new OrderedDictionary (), DataKeyNames);
}
} else {
table.Rows.Add (CreateEmptyrRow ());
}
rows = new DetailsViewRowCollection (list);
if (showPager && PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom) {
bottomPagerRow = CreateRow (-1, DataControlRowType.Pager, DataControlRowState.Normal);
InitializePager (bottomPagerRow, dataSource);
table.Rows.Add (bottomPagerRow);
}
if (FooterText.Length != 0 || footerTemplate != null) {
footerRow = CreateRow (-1, DataControlRowType.Footer, DataControlRowState.Normal);
DataControlFieldCell cell = new DataControlFieldCell (null);
cell.ColumnSpan = 2;
if (footerTemplate != null)
footerTemplate.InstantiateIn (cell);
else
cell.Text = FooterText;
footerRow.Cells.Add (cell);
table.Rows.Add (footerRow);
}
if (dataBinding)
DataBind (false);
return dataSource.DataSourceCount;
}
DataControlRowState GetRowState (int index)
{
DataControlRowState rstate = (index % 2) == 0 ? DataControlRowState.Normal : DataControlRowState.Alternate;
if (CurrentMode == DetailsViewMode.Edit) rstate |= DataControlRowState.Edit;
else if (CurrentMode == DetailsViewMode.Insert) rstate |= DataControlRowState.Insert;
return rstate;
}
protected virtual void InitializePager (DetailsViewRow row, PagedDataSource dataSource)
{
TableCell cell = new TableCell ();
cell.ColumnSpan = 2;
if (pagerTemplate != null)
pagerTemplate.InstantiateIn (cell);
else
cell.Controls.Add (PagerSettings.CreatePagerControl (dataSource.CurrentPageIndex, dataSource.PageCount));
row.Cells.Add (cell);
}
DetailsViewRow CreateEmptyrRow ()
{
DetailsViewRow row = CreateRow (-1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
TableCell cell = new TableCell ();
cell.ColumnSpan = 2;
if (emptyDataTemplate != null)
emptyDataTemplate.InstantiateIn (cell);
else
cell.Text = EmptyDataText;
row.Cells.Add (cell);
return row;
}
protected virtual void InitializeRow (DetailsViewRow row, DataControlField field)
{
DataControlFieldCell cell;
if (field.ShowHeader) {
cell = new DataControlFieldCell (field);
row.Cells.Add (cell);
field.InitializeCell (cell, DataControlCellType.Header, row.RowState, row.RowIndex);
}
cell = new DataControlFieldCell (field);
if (!field.ShowHeader)
cell.ColumnSpan = 2;
row.Cells.Add (cell);
field.InitializeCell (cell, DataControlCellType.DataCell, row.RowState, row.RowIndex);
}
IOrderedDictionary CreateRowDataKey (object dataItem)
{
if (cachedKeyProperties == null) {
PropertyDescriptorCollection props = TypeDescriptor.GetProperties (dataItem);
cachedKeyProperties = new PropertyDescriptor [DataKeyNames.Length];
for (int n=0; n<DataKeyNames.Length; n++) {
PropertyDescriptor p = props [DataKeyNames[n]];
if (p == null)
new InvalidOperationException ("Property '" + DataKeyNames[n] + "' not found in object of type " + dataItem.GetType());
cachedKeyProperties [n] = p;
}
}
OrderedDictionary dic = new OrderedDictionary ();
foreach (PropertyDescriptor p in cachedKeyProperties)
dic [p.Name] = p.GetValue (dataItem);
return dic;
}
IOrderedDictionary GetRowValues (bool includeReadOnlyFields, bool includePrimaryKey)
{
OrderedDictionary dic = new OrderedDictionary ();
ExtractRowValues (dic, includeReadOnlyFields, includePrimaryKey);
return dic;
}
protected virtual void ExtractRowValues (IOrderedDictionary fieldValues, bool includeReadOnlyFields, bool includePrimaryKey)
{
foreach (DetailsViewRow row in Rows) {
if (row.Cells.Count < 1) continue;
DataControlFieldCell c = row.Cells[row.Cells.Count-1] as DataControlFieldCell;
if (c != null)
c.ContainingField.ExtractValuesFromCell (fieldValues, c, row.RowState, includeReadOnlyFields);
}
if (!includePrimaryKey && DataKeyNames != null)
foreach (string key in DataKeyNames)
fieldValues.Remove (key);
}
protected override HtmlTextWriterTag TagKey {
get {
if (EnablePagingCallbacks)
return HtmlTextWriterTag.Div;
else
return HtmlTextWriterTag.Table;
}
}
public sealed override void DataBind ()
{
DataSourceView view = GetData ();
if (AllowPaging && view.CanPage) {
SelectArguments.StartRowIndex = PageIndex;
SelectArguments.MaximumRows = 1;
if (view.CanRetrieveTotalRowCount)
SelectArguments.RetrieveTotalRowCount = true;
}
cachedKeyProperties = null;
base.DataBind ();
if (dataItem != null) {
if (CurrentMode == DetailsViewMode.Edit)
oldEditValues = new DataKey (GetRowValues (false, true));
key = new DataKey (CreateRowDataKey (dataItem), DataKeyNames);
}
}
protected override void PerformDataBinding (IEnumerable data)
{
base.PerformDataBinding (data);
}
protected override void OnInit (EventArgs e)
{
Page.RegisterRequiresControlState (this);
base.OnInit (e);
}
void OnFieldsChanged (object sender, EventArgs args)
{
RequireBinding ();
}
protected override void OnDataSourceViewChanged (object sender, EventArgs e)
{
base.OnDataSourceViewChanged (sender, e);
RequireBinding ();
}
protected override bool OnBubbleEvent (object source, EventArgs e)
{
DetailsViewCommandEventArgs args = e as DetailsViewCommandEventArgs;
if (args != null) {
OnItemCommand (args);
ProcessEvent (args.CommandName, args.CommandArgument as string);
}
return base.OnBubbleEvent (source, e);
}
// TODO: This is prolly obsolete
protected virtual void RaisePostBackEvent (string eventArgument)
{
int i = eventArgument.IndexOf ('$');
if (i != -1)
ProcessEvent (eventArgument.Substring (0, i), eventArgument.Substring (i + 1));
else
ProcessEvent (eventArgument, null);
}
void ProcessEvent (string eventName, string param)
{
switch (eventName)
{
case DataControlCommands.PageCommandName:
int newIndex = -1;
switch (param) {
case DataControlCommands.FirstPageCommandArgument:
newIndex = 0;
break;
case DataControlCommands.LastPageCommandArgument:
newIndex = PageCount - 1;
break;
case DataControlCommands.NextPageCommandArgument:
if (PageIndex < PageCount - 1) newIndex = PageIndex + 1;
break;
case DataControlCommands.PreviousPageCommandArgument:
if (PageIndex > 0) newIndex = PageIndex - 1;
break;
default:
newIndex = int.Parse (param) - 1;
break;
}
ShowPage (newIndex);
break;
case DataControlCommands.FirstPageCommandArgument:
ShowPage (0);
break;
case DataControlCommands.LastPageCommandArgument:
ShowPage (PageCount - 1);
break;
case DataControlCommands.NextPageCommandArgument:
if (PageIndex < PageCount - 1)
ShowPage (PageIndex + 1);
break;
case DataControlCommands.PreviousPageCommandArgument:
if (PageIndex > 0)
ShowPage (PageIndex - 1);
break;
case DataControlCommands.EditCommandName:
ChangeMode (DetailsViewMode.Edit);
break;
case DataControlCommands.NewCommandName:
ChangeMode (DetailsViewMode.Insert);
break;
case DataControlCommands.UpdateCommandName:
UpdateItem (param, true);
break;
case DataControlCommands.CancelCommandName:
CancelEdit ();
break;
case DataControlCommands.DeleteCommandName:
DeleteItem ();
break;
case DataControlCommands.InsertCommandName:
InsertItem (true);
break;
}
}
void ShowPage (int newIndex)
{
DetailsViewPageEventArgs args = new DetailsViewPageEventArgs (newIndex);
OnPageIndexChanging (args);
if (!args.Cancel) {
EndRowEdit ();
PageIndex = args.NewPageIndex;
OnPageIndexChanged (EventArgs.Empty);
}
}
public void ChangeMode (DetailsViewMode newMode)
{
DetailsViewModeEventArgs args = new DetailsViewModeEventArgs (newMode, false);
OnModeChanging (args);
if (!args.Cancel) {
currentMode = args.NewMode;
OnModeChanged (EventArgs.Empty);
RequireBinding ();
}
}
void CancelEdit ()
{
DetailsViewModeEventArgs args = new DetailsViewModeEventArgs (DetailsViewMode.ReadOnly, true);
OnModeChanging (args);
if (!args.Cancel) {
EndRowEdit ();
}
}
public virtual void UpdateItem (bool causesValidation)
{
UpdateItem (null, causesValidation);
}
void UpdateItem (string param, bool causesValidation)
{
if (causesValidation)
Page.Validate ();
if (currentMode != DetailsViewMode.Edit) throw new NotSupportedException ();
currentEditOldValues = oldEditValues.Values;
currentEditRowKeys = DataKey.Values;
currentEditNewValues = GetRowValues (false, false);
DetailsViewUpdateEventArgs args = new DetailsViewUpdateEventArgs (param, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
OnItemUpdating (args);
if (!args.Cancel) {
DataSourceView view = GetData ();
if (view == null) throw new HttpException ("The DataSourceView associated to data bound control was null");
view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
} else
EndRowEdit ();
}
bool UpdateCallback (int recordsAffected, Exception exception)
{
DetailsViewUpdatedEventArgs dargs = new DetailsViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
OnItemUpdated (dargs);
if (!dargs.KeepInEditMode)
EndRowEdit ();
return dargs.ExceptionHandled;
}
public virtual void InsertItem (bool causesValidation)
{
InsertItem (null, causesValidation);
}
void InsertItem (string param, bool causesValidation)
{
if (causesValidation)
Page.Validate ();
if (currentMode != DetailsViewMode.Insert) throw new NotSupportedException ();
currentEditNewValues = GetRowValues (false, true);
DetailsViewInsertEventArgs args = new DetailsViewInsertEventArgs (param, currentEditNewValues);
OnItemInserting (args);
if (!args.Cancel) {
DataSourceView view = GetData ();
if (view == null) throw new HttpException ("The DataSourceView associated to data bound control was null");
view.Insert (currentEditNewValues, new DataSourceViewOperationCallback (InsertCallback));
} else
EndRowEdit ();
}
bool InsertCallback (int recordsAffected, Exception exception)
{
DetailsViewInsertedEventArgs dargs = new DetailsViewInsertedEventArgs (recordsAffected, exception, currentEditNewValues);
OnItemInserted (dargs);
if (!dargs.KeepInInsertMode)
EndRowEdit ();
return dargs.ExceptionHandled;
}
public void DeleteItem ()
{
currentEditRowKeys = DataKey.Values;
currentEditNewValues = GetRowValues (true, true);
DetailsViewDeleteEventArgs args = new DetailsViewDeleteEventArgs (PageIndex, currentEditRowKeys, currentEditNewValues);
OnItemDeleting (args);
if (!args.Cancel) {
if (PageIndex == PageCount - 1)
PageIndex --;
RequireBinding ();
DataSourceView view = GetData ();
if (view != null)
view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
else {
DetailsViewDeletedEventArgs dargs = new DetailsViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
OnItemDeleted (dargs);
}
}
}
bool DeleteCallback (int recordsAffected, Exception exception)
{
DetailsViewDeletedEventArgs dargs = new DetailsViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
OnItemDeleted (dargs);
return dargs.ExceptionHandled;
}
void EndRowEdit ()
{
ChangeMode (DefaultMode);
oldEditValues = new DataKey (new OrderedDictionary ());
currentEditRowKeys = null;
currentEditOldValues = null;
currentEditNewValues = null;
RequireBinding ();
}
protected internal override void LoadControlState (object ob)
{
if (ob == null) return;
object[] state = (object[]) ob;
base.LoadControlState (state[0]);
pageIndex = (int) state[1];
pageCount = (int) state[2];
currentMode = (DetailsViewMode) state[3];
}
protected internal override object SaveControlState ()
{
object bstate = base.SaveControlState ();
return new object[] {
bstate, pageIndex, pageCount, currentMode
};
}
protected override void TrackViewState()
{
base.TrackViewState();
if (columns != null) ((IStateManager)columns).TrackViewState();
if (pagerSettings != null) ((IStateManager)pagerSettings).TrackViewState();
if (alternatingRowStyle != null) ((IStateManager)alternatingRowStyle).TrackViewState();
if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState();
if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState();
if (pagerStyle != null) ((IStateManager)pagerStyle).TrackViewState();
if (rowStyle != null) ((IStateManager)rowStyle).TrackViewState();
if (editRowStyle != null) ((IStateManager)editRowStyle).TrackViewState();
if (insertRowStyle != null) ((IStateManager)insertRowStyle).TrackViewState();
if (emptyDataRowStyle != null) ((IStateManager)emptyDataRowStyle).TrackViewState();
if (key != null) ((IStateManager)key).TrackViewState();
if (autoFieldProperties != null) {
foreach (IStateManager sm in autoFieldProperties)
sm.TrackViewState ();
}
}
protected override object SaveViewState()
{
object[] states = new object [14];
states[0] = base.SaveViewState();
states[1] = (columns == null ? null : ((IStateManager)columns).SaveViewState());
states[2] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
states[3] = (alternatingRowStyle == null ? null : ((IStateManager)alternatingRowStyle).SaveViewState());
states[4] = (footerStyle == null ? null : ((IStateManager)footerStyle).SaveViewState());
states[5] = (headerStyle == null ? null : ((IStateManager)headerStyle).SaveViewState());
states[6] = (pagerStyle == null ? null : ((IStateManager)pagerStyle).SaveViewState());
states[7] = (rowStyle == null ? null : ((IStateManager)rowStyle).SaveViewState());
states[8] = (insertRowStyle == null ? null : ((IStateManager)insertRowStyle).SaveViewState());
states[9] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
states[10] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
states[11] = (key == null ? null : ((IStateManager)key).SaveViewState());
states[12] = (oldEditValues == null ? null : ((IStateManager)oldEditValues).SaveViewState());
if (autoFieldProperties != null) {
object[] data = new object [autoFieldProperties.Length];
bool allNull = true;
for (int n=0; n<data.Length; n++) {
data [n] = ((IStateManager)autoFieldProperties [n]).SaveViewState ();
if (data [n] != null) allNull = false;
}
if (!allNull) states [13] = data;
}
for (int i = states.Length - 1; i >= 0; i--) {
if (states [i] != null)
return states;
}
return null;
}
protected override void LoadViewState (object savedState)
{
if (savedState == null) {
base.LoadViewState (null);
return;
}
object [] states = (object []) savedState;
if (states[13] != null) {
object[] data = (object[]) states [13];
autoFieldProperties = new AutoGeneratedFieldProperties [data.Length];
for (int n=0; n<data.Length; n++) {
IStateManager p = new AutoGeneratedFieldProperties ();
p.TrackViewState ();
p.LoadViewState (data [n]);
autoFieldProperties [n] = (AutoGeneratedFieldProperties) p;
}
}
base.LoadViewState (states[0]);
EnsureChildControls ();
if (states[1] != null) ((IStateManager)Fields).LoadViewState (states[1]);
if (states[2] != null) ((IStateManager)PagerSettings).LoadViewState (states[2]);
if (states[3] != null) ((IStateManager)AlternatingRowStyle).LoadViewState (states[3]);
if (states[4] != null) ((IStateManager)FooterStyle).LoadViewState (states[4]);
if (states[5] != null) ((IStateManager)HeaderStyle).LoadViewState (states[5]);
if (states[6] != null) ((IStateManager)PagerStyle).LoadViewState (states[6]);
if (states[7] != null) ((IStateManager)RowStyle).LoadViewState (states[7]);
if (states[8] != null) ((IStateManager)InsertRowStyle).LoadViewState (states[8]);
if (states[9] != null) ((IStateManager)EditRowStyle).LoadViewState (states[9]);
if (states[10] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[10]);
if (states[11] != null) ((IStateManager)DataKey).LoadViewState (states[11]);
if (states[12] != null && oldEditValues != null) ((IStateManager)oldEditValues).LoadViewState (states[12]);
}
string ICallbackEventHandler.RaiseCallbackEvent (string eventArgs)
{
return RaiseCallbackEvent (eventArgs);
}
protected virtual string RaiseCallbackEvent (string eventArgs)
{
string[] clientData = eventArgs.Split ('|');
pageIndex = int.Parse (clientData[0]);
RequireBinding ();
RaisePostBackEvent (clientData[2]);
EnsureDataBound ();
StringWriter sw = new StringWriter ();
sw.Write (PageIndex.ToString());
HtmlTextWriter writer = new HtmlTextWriter (sw);
RenderGrid (writer);
return sw.ToString ();
}
string ICallbackContainer.GetCallbackScript (IButtonControl control, string argument)
{
if (EnablePagingCallbacks)
return "javascript:GridView_ClientEvent (\"" + ClientID + "\",\"" + control.CommandName + "$" + control.CommandArgument + "\"); return false;";
else
return null;
}
protected override void OnPreRender (EventArgs e)
{
base.OnPreRender (e);
if (EnablePagingCallbacks)
{
if (!Page.ClientScript.IsClientScriptIncludeRegistered (typeof(GridView), "GridView.js")) {
string url = Page.ClientScript.GetWebResourceUrl (typeof(GridView), "GridView.js");
Page.ClientScript.RegisterClientScriptInclude (typeof(GridView), "GridView.js", url);
}
string cgrid = ClientID + "_data";
string script = string.Format ("var {0} = new Object ();\n", cgrid);
script += string.Format ("{0}.pageIndex = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (PageIndex));
script += string.Format ("{0}.uid = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (UniqueID));
Page.ClientScript.RegisterStartupScript (typeof(TreeView), this.UniqueID, script, true);
// Make sure the basic script infrastructure is rendered
Page.ClientScript.GetCallbackEventReference (this, "null", "", "null");
Page.ClientScript.GetPostBackClientHyperlink (this, "");
}
}
protected override void Render (HtmlTextWriter writer)
{
if (EnablePagingCallbacks)
base.RenderBeginTag (writer);
RenderGrid (writer);
if (EnablePagingCallbacks)
base.RenderEndTag (writer);
}
void RenderGrid (HtmlTextWriter writer)
{
switch (GridLines) {
case GridLines.Horizontal:
writer.AddAttribute (HtmlTextWriterAttribute.Rules, "rows");
writer.AddAttribute (HtmlTextWriterAttribute.Border, "1");
break;
case GridLines.Vertical:
writer.AddAttribute (HtmlTextWriterAttribute.Rules, "cols");
writer.AddAttribute (HtmlTextWriterAttribute.Border, "1");
break;
case GridLines.Both:
writer.AddAttribute (HtmlTextWriterAttribute.Rules, "all");
writer.AddAttribute (HtmlTextWriterAttribute.Border, "1");
break;
default:
writer.AddAttribute (HtmlTextWriterAttribute.Border, "0");
break;
}
writer.AddAttribute (HtmlTextWriterAttribute.Cellspacing, "0");
writer.AddStyleAttribute (HtmlTextWriterStyle.BorderCollapse, "collapse");
table.RenderBeginTag (writer);
foreach (DetailsViewRow row in table.Rows)
{
switch (row.RowType) {
case DataControlRowType.Header:
if (headerStyle != null)headerStyle.AddAttributesToRender (writer, row);
break;
case DataControlRowType.Footer:
if (footerStyle != null) footerStyle.AddAttributesToRender (writer, row);
break;
case DataControlRowType.Pager:
if (pagerStyle != null) pagerStyle.AddAttributesToRender (writer, row);
break;
case DataControlRowType.EmptyDataRow:
if (emptyDataRowStyle != null) emptyDataRowStyle.AddAttributesToRender (writer, row);
break;
default:
if (rowStyle != null) rowStyle.AddAttributesToRender (writer, row);
break;
}
if ((row.RowState & DataControlRowState.Alternate) != 0 && alternatingRowStyle != null)
alternatingRowStyle.AddAttributesToRender (writer, row);
if ((row.RowState & DataControlRowState.Edit) != 0 && editRowStyle != null)
editRowStyle.AddAttributesToRender (writer, row);
if ((row.RowState & DataControlRowState.Insert) != 0 && insertRowStyle != null)
insertRowStyle.AddAttributesToRender (writer, row);
if (row == commandRow && commandRowStyle != null)
commandRowStyle.AddAttributesToRender (writer, row);
row.RenderBeginTag (writer);
for (int n=0; n<row.Cells.Count; n++) {
DataControlFieldCell fcell = row.Cells[n] as DataControlFieldCell;
if (fcell != null && fcell.ContainingField != null) {
if (n == 0 && fcell.ContainingField.ShowHeader) {
if (fieldHeaderStyle != null)
fieldHeaderStyle.AddAttributesToRender (writer, fcell);
fcell.ContainingField.HeaderStyle.AddAttributesToRender (writer, fcell);
}
else
fcell.ContainingField.ItemStyle.AddAttributesToRender (writer, fcell);
}
row.Cells[n].Render (writer);
}
row.RenderEndTag (writer);
}
table.RenderEndTag (writer);
}
}
}
#endif
| |
using System;
using System.Linq;
using Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using Android.Content;
using System.Timers;
using System.Linq.Expressions;
using Android.Util;
using Android.Animation;
using Android.Graphics;
namespace XamarinStore
{
class ProductDetailsFragment : Fragment, ViewTreeObserver.IOnGlobalLayoutListener
{
ImageView productImage;
int currentIndex = 0;
Product currentProduct;
bool shouldAnimatePop;
BadgeDrawable basketBadge;
public Action<Product> AddToBasket = delegate {};
string[] images = new string[0];
bool cached;
int slidingDelta;
Spinner sizeSpinner;
Spinner colorSpinner;
KenBurnsDrawable productDrawable;
ValueAnimator kenBurnsMovement;
ValueAnimator kenBurnsAlpha;
public ProductDetailsFragment ()
{
}
public ProductDetailsFragment (Product product,int slidingDelta )
{
this.slidingDelta = slidingDelta;
currentProduct = product;
images = product.ImageUrls.ToArray().Shuffle() ?? new string[0];
}
public override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
RetainInstance = true;
SetHasOptionsMenu (true);
}
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.Inflate (Resource.Layout.ProductDetail, null, true);
}
public override void OnViewCreated (View view, Bundle savedInstanceState)
{
base.OnViewCreated (view, savedInstanceState);
productImage = View.FindViewById<ImageView> (Resource.Id.productImage);
sizeSpinner = View.FindViewById<Spinner> (Resource.Id.productSize);
colorSpinner = View.FindViewById<Spinner> (Resource.Id.productColor);
var addToBasket = View.FindViewById<Button> (Resource.Id.addToBasket);
addToBasket.Click += delegate {
currentProduct.Size = currentProduct.Sizes [sizeSpinner.SelectedItemPosition];
currentProduct.Color = currentProduct.Colors [colorSpinner.SelectedItemPosition];
shouldAnimatePop = true;
Activity.FragmentManager.PopBackStack();
AddToBasket (currentProduct);
};
View.FindViewById<TextView> (Resource.Id.productTitle).Text = currentProduct.Name ?? string.Empty;
View.FindViewById<TextView> (Resource.Id.productPrice).Text = currentProduct.PriceDescription ?? string.Empty;
View.FindViewById<TextView> (Resource.Id.productDescription).Text = currentProduct.Description ?? string.Empty;
((SlidingLayout)View).InitialMainViewDelta = slidingDelta;
LoadOptions ();
}
void LoadOptions()
{
var sizeAdapter = new ArrayAdapter<ProductSize> (Activity, Android.Resource.Layout.SimpleSpinnerDropDownItem, currentProduct.Sizes);
sizeAdapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
sizeSpinner.Adapter = sizeAdapter;
sizeSpinner.SetSelection (currentProduct.Sizes.IndexOf (currentProduct.Size));
var colorAdapter = new ArrayAdapter<ProductColor> (Activity, Android.Resource.Layout.SimpleSpinnerDropDownItem, currentProduct.Colors);
colorAdapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
colorSpinner.Adapter = colorAdapter;
}
public override void OnStart ()
{
base.OnStart ();
AnimateImages ();
}
public override void OnStop ()
{
base.OnStop ();
if (kenBurnsAlpha != null)
kenBurnsAlpha.Cancel ();
if (kenBurnsMovement != null)
kenBurnsMovement.Cancel ();
}
public override void OnCreateOptionsMenu (IMenu menu, MenuInflater inflater)
{
inflater.Inflate (Resource.Menu.menu, menu);
var cartItem = menu.FindItem (Resource.Id.cart_menu_item);
cartItem.SetIcon ((basketBadge = new BadgeDrawable (cartItem.Icon)));
var order = WebService.Shared.CurrentOrder;
basketBadge.Count = order.Products.Count;
order.ProductsChanged += (sender, e) => {
basketBadge.SetCountAnimated (order.Products.Count);
};
base.OnCreateOptionsMenu (menu, inflater);
}
public override Android.Animation.Animator OnCreateAnimator (FragmentTransit transit, bool enter, int nextAnim)
{
if (!enter && shouldAnimatePop)
return AnimatorInflater.LoadAnimator (View.Context, Resource.Animation.add_to_basket_in);
return base.OnCreateAnimator (transit, enter, nextAnim);
}
void AnimateImages ()
{
if (images.Length < 1)
return;
if (images.Length == 1) {
//No need to await the change
#pragma warning disable 4014
Images.SetImageFromUrlAsync (productImage, Product.ImageForSize (images [0], Images.ScreenWidth));
#pragma warning restore 4014
return;
}
productImage.ViewTreeObserver.AddOnGlobalLayoutListener (this);
}
public async void OnGlobalLayout ()
{
productImage.ViewTreeObserver.RemoveOnGlobalLayoutListener (this);
const int DeltaX = 100;
var img1 = Images.FromUrl (Product.ImageForSize (images [0], Images.ScreenWidth));
var img2 = Images.FromUrl (Product.ImageForSize (images [1], Images.ScreenWidth));
productDrawable = new KenBurnsDrawable (Color.DarkBlue);
productDrawable.FirstBitmap = await img1;
productDrawable.SecondBitmap = await img2;
productImage.SetImageDrawable (productDrawable);
currentIndex++;
// Check for null bitmaps due to decode errors:
if (productDrawable.FirstBitmap != null) {
var evaluator = new MatrixEvaluator ();
var finalMatrix = new Matrix ();
finalMatrix.SetTranslate (-DeltaX, -(float)productDrawable.FirstBitmap.Height / 1.3f + (float)productImage.Height);
finalMatrix.PostScale (1.27f, 1.27f);
kenBurnsMovement = ValueAnimator.OfObject (evaluator, new Matrix (), finalMatrix);
kenBurnsMovement.Update += (sender, e) => productDrawable.SetMatrix ((Matrix)e.Animation.AnimatedValue);
kenBurnsMovement.SetDuration (14000);
kenBurnsMovement.RepeatMode = ValueAnimatorRepeatMode.Reverse;
kenBurnsMovement.RepeatCount = ValueAnimator.Infinite;
kenBurnsMovement.Start ();
kenBurnsAlpha = ObjectAnimator.OfInt (productDrawable, "alpha", 0, 0, 0, 255, 255, 255);
kenBurnsAlpha.SetDuration (kenBurnsMovement.Duration);
kenBurnsAlpha.RepeatMode = ValueAnimatorRepeatMode.Reverse;
kenBurnsAlpha.RepeatCount = ValueAnimator.Infinite;
kenBurnsAlpha.AnimationRepeat += (sender, e) => NextImage ();
kenBurnsAlpha.Start ();
}
}
async void NextImage ()
{
currentIndex = (currentIndex + 1) % images.Length;
var image = images [currentIndex];
await Images.SetImageFromUrlAsync (productDrawable, Product.ImageForSize (image, Images.ScreenWidth));
PrecacheNextImage ();
}
void PrecacheNextImage()
{
if (currentIndex + 1 >= images.Length)
cached = true;
if (cached)
return;
var next = currentIndex + 1;
var image = images [next];
//No need to await the precache to finish
#pragma warning disable 4014
FileCache.Download (Product.ImageForSize (image, Images.ScreenWidth));
#pragma warning restore 4014
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Threading;
namespace Platform.VirtualFileSystem.Providers.Local
{
/// <summary>
/// Implementation of <see cref="IFile"/> for <see cref="LocalFileSystem"/>s.
/// </summary>
public class LocalFile
: AbstractFile, INativePathService
{
private readonly FileInfo fileInfo;
public override bool SupportsActivityEvents
{
get
{
return true;
}
}
public LocalFile(LocalFileSystem fileSystem, LocalNodeAddress address)
: base(address, fileSystem)
{
this.FileSystem = fileSystem;
this.fileInfo = new FileInfo(address.AbsoluteNativePath);
}
public override INode DoCreate(bool createParent)
{
if (createParent)
{
this.ParentDirectory.Refresh();
if (!this.ParentDirectory.Exists)
{
this.ParentDirectory.Create(true);
}
try
{
this.fileInfo.Create().Close();
}
catch (DirectoryNotFoundException)
{
}
this.ParentDirectory.Create(true);
try
{
this.fileInfo.Create().Close();
}
catch (DirectoryNotFoundException)
{
throw new DirectoryNodeNotFoundException(this.Address);
}
catch (FileNotFoundException)
{
throw new FileNodeNotFoundException(this.Address);
}
Refresh();
}
else
{
try
{
this.fileInfo.Create().Close();
}
catch (DirectoryNotFoundException)
{
throw new DirectoryNodeNotFoundException(this.Address);
}
catch (FileNotFoundException)
{
throw new FileNodeNotFoundException(this.Address);
}
}
return this;
}
protected override INode DoDelete()
{
try
{
Native.GetInstance().DeleteFileContent(this.fileInfo.FullName, null);
Refresh();
}
catch (FileNotFoundException)
{
throw new FileNodeNotFoundException(Address);
}
catch (DirectoryNotFoundException)
{
throw new DirectoryNodeNotFoundException(Address);
}
return this;
}
protected override INode DoCopyTo(INode target, bool overwrite)
{
return CopyTo(target, overwrite, false);
}
private INode CopyTo(INode target, bool overwrite, bool deleteOriginal)
{
string targetLocalPath = null;
if (target.NodeType.IsLikeDirectory)
{
target = target.ResolveFile(this.Address.Name);
}
try
{
var service = (INativePathService)target.GetService(typeof(INativePathService));
targetLocalPath = service.GetNativePath();
}
catch (NotSupportedException)
{
}
var thisLocalPath = ((LocalNodeAddress)this.Address).AbsoluteNativePath;
if (targetLocalPath == null
|| !Path.GetPathRoot(thisLocalPath).EqualsIgnoreCase(Path.GetPathRoot(targetLocalPath)))
{
if (deleteOriginal)
{
base.DoMoveTo(target, overwrite);
}
else
{
base.DoCopyTo(target, overwrite);
}
}
else
{
target.Refresh();
if (overwrite && target.Exists)
{
try
{
target.Delete();
}
catch (FileNodeNotFoundException)
{
}
}
try
{
if (deleteOriginal)
{
try
{
File.Move(thisLocalPath, targetLocalPath);
}
catch (System.IO.DirectoryNotFoundException)
{
throw new DirectoryNodeNotFoundException(this.Address);
}
catch (System.IO.FileNotFoundException)
{
throw new FileNodeNotFoundException(this.Address);
}
}
else
{
try
{
File.Copy(thisLocalPath, targetLocalPath);
}
catch (System.IO.DirectoryNotFoundException)
{
throw new DirectoryNodeNotFoundException(this.Address);
}
catch (System.IO.FileNotFoundException)
{
throw new FileNodeNotFoundException(this.Address);
}
}
return this;
}
catch (IOException)
{
if (overwrite && target.Exists)
{
try
{
target.Delete();
}
catch (FileNotFoundException)
{
}
}
else
{
throw;
}
}
if (deleteOriginal)
{
try
{
File.Move(thisLocalPath, targetLocalPath);
}
catch (System.IO.DirectoryNotFoundException)
{
throw new DirectoryNodeNotFoundException(this.Address);
}
catch (System.IO.FileNotFoundException)
{
throw new FileNodeNotFoundException(this.Address);
}
}
else
{
try
{
File.Copy(thisLocalPath, targetLocalPath);
}
catch (System.IO.DirectoryNotFoundException)
{
throw new DirectoryNodeNotFoundException(this.Address);
}
catch (System.IO.FileNotFoundException)
{
throw new FileNodeNotFoundException(this.Address);
}
}
}
return this;
}
protected override INode DoMoveTo(INode target, bool overwrite)
{
return CopyTo(target, overwrite, true);
}
private class LocalFileMovingService
: AbstractRunnableService
{
private readonly LocalFile localFile;
private readonly LocalFile destinationFile;
private readonly bool overwrite;
public override IMeter Progress
{
get
{
return this.progress;
}
}
private readonly MutableMeter progress = new MutableMeter(0, 1, 0, "files");
public LocalFileMovingService(LocalFile localFile, LocalFile destinationFile, bool overwrite)
{
this.localFile = localFile;
this.destinationFile = destinationFile;
this.overwrite = overwrite;
}
public override void DoRun()
{
this.progress.SetCurrentValue(0);
this.localFile.DoMoveTo(this.destinationFile, this.overwrite);
this.progress.SetCurrentValue(1);
}
}
public override IService GetService(ServiceType serviceType)
{
var typedServiceType = serviceType as NodeMovingServiceType;
if (typedServiceType != null)
{
if (typedServiceType.Destination is LocalFile)
{
if (typedServiceType.Destination.Address.RootUri.Equals(this.Address.RootUri))
{
return new LocalFileMovingService(this, (LocalFile)typedServiceType.Destination, typedServiceType.Overwrite);
}
}
}
else if (serviceType.Is(typeof(INativePathService)))
{
return this;
}
return base.GetService(serviceType);
}
protected override Stream DoOpenStream(string contentName, FileMode fileMode, FileAccess fileAccess, FileShare fileShare)
{
try
{
if (string.IsNullOrEmpty(contentName) || contentName == Native.GetInstance().DefaultContentName)
{
return new FileStream(this.fileInfo.FullName, fileMode, fileAccess, fileShare);
}
else
{
return Native.GetInstance().OpenAlternateContentStream
(
this.fileInfo.FullName,
contentName,
fileMode, fileAccess, fileShare
);
}
}
catch (FileNotFoundException)
{
throw new FileNodeNotFoundException(Address);
}
}
protected override Stream DoGetInputStream(string contentName, out string encoding, FileMode mode, FileShare sharing)
{
encoding = null;
try
{
if (string.IsNullOrEmpty(contentName)
|| contentName == Native.GetInstance().DefaultContentName)
{
for (var i = 0; i < 10; i++)
{
try
{
return new FileStream(this.fileInfo.FullName, mode, FileAccess.Read, sharing);
}
catch (DirectoryNotFoundException)
{
throw;
}
catch (FileNotFoundException)
{
throw;
}
catch (IOException)
{
if (i == 9)
{
throw;
}
Thread.Sleep(500);
}
}
throw new IOException();
}
else
{
return Native.GetInstance().OpenAlternateContentStream
(
this.fileInfo.FullName,
contentName,
mode, FileAccess.Read, sharing
);
}
}
catch (FileNotFoundException)
{
throw new FileNodeNotFoundException(Address);
}
catch (DirectoryNotFoundException)
{
throw new DirectoryNodeNotFoundException(Address);
}
}
protected override Stream DoGetOutputStream(string contentName, string encoding, FileMode mode, FileShare sharing)
{
try
{
if (string.IsNullOrEmpty(contentName) || contentName == Native.GetInstance().DefaultContentName)
{
return new FileStream(this.fileInfo.FullName, mode, FileAccess.Write, sharing);
}
else
{
return Native.GetInstance().OpenAlternateContentStream
(
this.fileInfo.FullName,
contentName,
mode, FileAccess.Write, sharing
);
}
}
catch (FileNotFoundException)
{
throw new FileNodeNotFoundException(Address);
}
catch (DirectoryNotFoundException)
{
throw new DirectoryNodeNotFoundException(Address);
}
}
protected override INodeAttributes CreateAttributes()
{
return new AutoRefreshingFileAttributes(new LocalFileAttributes(this, this.fileInfo), -1);
}
protected override bool SupportsAlternateContent()
{
return true;
}
string INativePathService.GetNativePath()
{
return ((LocalNodeAddress)this.Address).AbsoluteNativePath;
}
string INativePathService.GetNativeShortPath()
{
return Native.GetInstance().GetShortPath(((LocalNodeAddress)this.Address).AbsoluteNativePath);
}
public override string DefaultContentName
{
get
{
return Native.GetInstance().DefaultContentName;
}
}
public override System.Collections.Generic.IEnumerable<string> GetContentNames()
{
return Native.GetInstance().GetContentInfos(((LocalNodeAddress)this.Address).AbsoluteNativePath).Select(contentInfo => contentInfo.Name);
}
protected override void DeleteContent(string contentName)
{
if (contentName == null)
{
contentName = Native.GetInstance().DefaultContentName;
}
try
{
Native.GetInstance().DeleteFileContent(((LocalNodeAddress)this.Address).AbsoluteNativePath, contentName);
}
catch (FileNotFoundException)
{
throw new FileNodeNotFoundException(Address);
}
catch (DirectoryNotFoundException)
{
throw new DirectoryNodeNotFoundException(Address);
}
}
protected override INode DoRenameTo(string name, bool overwrite)
{
name = StringUriUtils.RemoveQuery(name);
var destPath = Path.Combine(this.fileInfo.DirectoryName, name);
for (var i = 0; i < 5; i++)
{
try
{
if (overwrite)
{
File.Delete(destPath);
}
//
// Don't use FileInfo.MoveTo as it changes the existing FileInfo
// use the new path.
//
File.Move(this.fileInfo.FullName, destPath);
this.fileInfo.Refresh();
break;
}
catch (IOException)
{
if (i == 4)
{
throw;
}
Thread.Sleep(500);
}
}
return this;
}
protected override IFile DoCreateHardLink(IFile targetFile, bool overwrite)
{
string target;
var path = this.fileInfo.FullName;
try
{
var service = (INativePathService)targetFile.GetService(typeof(INativePathService));
target = service.GetNativePath();
}
catch (NotSupportedException)
{
throw new NotSupportedException();
}
targetFile.Refresh();
if (this.Exists && !overwrite)
{
throw new IOException("Hardlink already exists");
}
else
{
ActionUtils.ToRetryAction<object>
(
delegate
{
if (this.Exists)
{
this.Delete();
}
try
{
Native.GetInstance().CreateHardLink(path, target);
}
catch (TooManyLinksException)
{
throw new TooManyLinksException(this, targetFile);
}
},
TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(0.25)
)(null);
}
return this;
}
}
}
| |
namespace Bog.Web.Dashboard.Areas.HelpPage
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
#region Constants
/// <summary>
/// The default collection size.
/// </summary>
private const int DefaultCollectionSize = 3;
#endregion
#region Fields
/// <summary>
/// The simple object generator.
/// </summary>
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
#endregion
#region Public Methods and Operators
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable
/// public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>,
/// <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from
/// <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>,
/// <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from
/// <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <returns>
/// An object of the given type.
/// </returns>
public object GenerateObject(Type type)
{
return this.GenerateObject(type, new Dictionary<Type, object>());
}
#endregion
#region Methods
/// <summary>
/// The generate array.
/// </summary>
/// <param name="arrayType">
/// The array type.
/// </param>
/// <param name="size">
/// The size.
/// </param>
/// <param name="createdObjectReferences">
/// The created object references.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
var objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
/// <summary>
/// The generate collection.
/// </summary>
/// <param name="collectionType">
/// The collection type.
/// </param>
/// <param name="size">
/// The size.
/// </param>
/// <param name="createdObjectReferences">
/// The created object references.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
private static object GenerateCollection(
Type collectionType,
int size,
Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
var objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
/// <summary>
/// The generate complex object.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <param name="createdObjectReferences">
/// The created object references.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
/// <summary>
/// The generate dictionary.
/// </summary>
/// <param name="dictionaryType">
/// The dictionary type.
/// </param>
/// <param name="size">
/// The size.
/// </param>
/// <param name="createdObjectReferences">
/// The created object references.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
private static object GenerateDictionary(
Type dictionaryType,
int size,
Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
var objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
var containsKey = (bool)containsMethod.Invoke(result, new[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new[] { newKey, newValue });
}
}
return result;
}
/// <summary>
/// The generate enum.
/// </summary>
/// <param name="enumType">
/// The enum type.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
/// <summary>
/// The generate generic type.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <param name="collectionSize">
/// The collection size.
/// </param>
/// <param name="createdObjectReferences">
/// The created object references.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
private static object GenerateGenericType(
Type type,
int collectionSize,
Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>)
|| genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(
genericArguments[0],
genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
/// <summary>
/// The generate key value pair.
/// </summary>
/// <param name="keyValuePairType">
/// The key value pair type.
/// </param>
/// <param name="createdObjectReferences">
/// The created object references.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
private static object GenerateKeyValuePair(
Type keyValuePairType,
Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
var objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
/// <summary>
/// The generate nullable.
/// </summary>
/// <param name="nullableType">
/// The nullable type.
/// </param>
/// <param name="createdObjectReferences">
/// The created object references.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
var objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
/// <summary>
/// The generate queryable.
/// </summary>
/// <param name="queryableType">
/// The queryable type.
/// </param>
/// <param name="size">
/// The size.
/// </param>
/// <param name="createdObjectReferences">
/// The created object references.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
private static object GenerateQueryable(
Type queryableType,
int size,
Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return ((IEnumerable)list).AsQueryable();
}
/// <summary>
/// The generate tuple.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <param name="createdObjectReferences">
/// The created object references.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
var parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
var objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
/// <summary>
/// The is tuple.
/// </summary>
/// <param name="genericTypeDefinition">
/// The generic type definition.
/// </param>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>)
|| genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>)
|| genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>)
|| genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
/// <summary>
/// The set public fields.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <param name="obj">
/// The obj.
/// </param>
/// <param name="createdObjectReferences">
/// The created object references.
/// </param>
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
var objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
/// <summary>
/// The set public properties.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <param name="obj">
/// The obj.
/// </param>
/// <param name="createdObjectReferences">
/// The created object references.
/// </param>
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(
property.PropertyType,
createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
/// <summary>
/// The generate object.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <param name="createdObjectReferences">
/// The created object references.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return this.SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
#endregion
/// <summary>
/// The simple type object generator.
/// </summary>
private class SimpleTypeObjectGenerator
{
#region Static Fields
/// <summary>
/// The default generators.
/// </summary>
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
#endregion
#region Fields
/// <summary>
/// The _index.
/// </summary>
private long _index;
#endregion
#region Public Methods and Operators
/// <summary>
/// The can generate object.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
/// <summary>
/// The generate object.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++this._index);
}
#endregion
#region Methods
/// <summary>
/// The initialize generators.
/// </summary>
/// <returns>
/// The <see cref="Dictionary"/>.
/// </returns>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity",
Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{
typeof(DateTimeOffset),
index => new DateTimeOffset(DateTime.Now)
},
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => index + 0.1 },
{ typeof(Guid), index => Guid.NewGuid() },
{
typeof(Int16),
index => (Int16)(index % short.MaxValue)
},
{
typeof(Int32),
index => (Int32)(index % int.MaxValue)
},
{ typeof(Int64), index => index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String),
index =>
{
return
string.Format(
CultureInfo.CurrentCulture,
"sample string {0}",
index);
}
},
{
typeof(TimeSpan),
index => { return TimeSpan.FromTicks(1234567); }
},
{
typeof(UInt16),
index => (UInt16)(index % ushort.MaxValue)
},
{
typeof(UInt32),
index => (UInt32)(index % uint.MaxValue)
},
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri),
index =>
{
return
new Uri(
string.Format(
CultureInfo.CurrentCulture,
"http://webapihelppage{0}.com",
index));
}
},
};
}
#endregion
}
}
}
| |
using System;
using System.Collections.Generic;
public interface ICommand
{
string[] CommandKeys { get; }
string[] MandatoryArgKeys { get; }
int Execute(Dictionary<string, string> argsLc, Dictionary<string, string> argsCased);
}
namespace JenkinsConsoleUtility
{
public static class JenkinsConsoleUtility
{
public static int Main(string[] args)
{
var commandLookup = FindICommands();
List<string> orderedCommands;
Dictionary<string, string> lcArgsByName, casedArgsByName;
ICommand tempCommand;
try
{
ExtractArgs(args, out orderedCommands, out lcArgsByName, out casedArgsByName);
var success = true;
foreach (var key in orderedCommands)
{
if (!commandLookup.TryGetValue(key, out tempCommand))
{
success = false;
FancyWriteToConsole("Unexpected command: " + key, null, ConsoleColor.Red);
}
}
if (orderedCommands.Count == 0)
FancyWriteToConsole("No commands given, no work will be done", null, ConsoleColor.DarkYellow);
if (!success || orderedCommands.Count == 0)
throw new Exception("Commands not input correctly");
}
catch (Exception)
{
FancyWriteToConsole("Run a sequence of ordered commands --<command> [--<command> ...] [-<argKey> <argValue> ...]\nValid commands:", commandLookup.Keys, ConsoleColor.Yellow);
FancyWriteToConsole("argValues can have spaces. Dashes in argValues can cause problems, and are not recommended.", null, ConsoleColor.Yellow);
FancyWriteToConsole("Quotes are considered part of the argKey or argValue, and are not parsed as tokens.", null, ConsoleColor.Yellow);
// TODO: Report list of available commands and valid/required args for commands
return Pause(1);
}
var returnCode = 0;
foreach (var key in orderedCommands)
{
if (returnCode == 0 && commandLookup.TryGetValue(key, out tempCommand))
{
returnCode = VerifyKeys(tempCommand, lcArgsByName);
if (returnCode == 0)
returnCode = tempCommand.Execute(lcArgsByName, casedArgsByName);
}
if (returnCode != 0)
{
FancyWriteToConsole(key + " command returned error code: " + returnCode, null, ConsoleColor.Yellow);
return Pause(returnCode);
}
}
return Pause(0);
}
/// <summary>
/// Try to find the given (lowercased) key in the command line arguments, or the environment variables.
/// If it is present, return it
/// Else getDefault (if defined), else throw an exception
/// Defined as empty string is considered a successful result
/// </summary>
/// <returns>The string associated with this key</returns>
public static string GetArgVar(Dictionary<string, string> args, string key, string getDefault = null)
{
string output;
if (TryGetArgVar(out output, args, key, getDefault))
return output;
if (getDefault != null) // Don't use string.IsNullOrEmpty() here, because there's a distinction between "undefined" and "empty"
{
FancyWriteToConsole("WARNING: " + key + " not found, reverting to: " + getDefault, null, ConsoleColor.DarkYellow);
return getDefault;
}
var msg = "ERROR: Required parameter: " + key + " not found";
FancyWriteToConsole(msg, null, ConsoleColor.Red);
throw new Exception(msg);
}
/// <summary>
/// Try to find the given key in the command line arguments, or the environment variables.
/// If it is present, return it.
/// Defined as empty string returns true
/// Falling through to getDefault always returns false
/// </summary>
/// <returns>True if the key is found</returns>
public static bool TryGetArgVar(out string output, Dictionary<string, string> args, string key, string getDefault = null)
{
var lcKey = key.ToLower();
// Check in args (not guaranteed to be lc-keys)
output = null;
foreach (var eachArgKey in args.Keys)
if (eachArgKey.ToLower() == lcKey)
output = args[eachArgKey];
if (output != null) // Don't use string.IsNullOrEmpty() here, because there's a distinction between "undefined" and "empty"
return true;
// Check in env-vars - Definitely not lc-keys
var allEnvVars = Environment.GetEnvironmentVariables();
foreach (string eachEnvKey in allEnvVars.Keys)
if (eachEnvKey.ToLower() == lcKey)
output = allEnvVars[eachEnvKey] as string;
if (output != null) // Don't use string.IsNullOrEmpty() here, because there's a distinction between "undefined" and "empty"
return true;
output = getDefault;
return false;
}
private static int VerifyKeys(ICommand cmd, Dictionary<string, string> argsByName)
{
if (cmd.MandatoryArgKeys == null || cmd.MandatoryArgKeys.Length == 0)
return 0;
var allEnvVars = Environment.GetEnvironmentVariables();
List<string> missingArgKeys = new List<string>();
foreach (var eachCmdKey in cmd.MandatoryArgKeys)
{
var expectedKey = eachCmdKey.ToLower();
var found = argsByName.ContainsKey(expectedKey);
if (!found)
foreach (string envKey in allEnvVars.Keys)
if (envKey.ToLower() == expectedKey)
found = true;
if (!found)
missingArgKeys.Add(expectedKey);
}
foreach (var eachCmdKey in missingArgKeys)
FancyWriteToConsole(cmd.CommandKeys[0] + " - Missing argument: " + eachCmdKey, null, ConsoleColor.Yellow);
return missingArgKeys.Count;
}
public static void FancyWriteToConsole(string msg = null, ICollection<string> multiLineMsg = null, ConsoleColor textColor = ConsoleColor.White)
{
Console.ForegroundColor = textColor;
if (!string.IsNullOrEmpty(msg))
Console.WriteLine(msg);
if (multiLineMsg != null)
foreach (var eachMsg in multiLineMsg)
Console.WriteLine(eachMsg);
Console.ForegroundColor = ConsoleColor.White;
}
private static int Pause(int code)
{
FancyWriteToConsole("Done! Press any key to close", null, code == 0 ? ConsoleColor.Green : ConsoleColor.DarkRed);
try
{
Console.ReadKey();
}
catch (InvalidOperationException)
{
// ReadKey fails when run from inside of Jenkins, so just ignore it.
}
return code;
}
private static Dictionary<string, ICommand> FindICommands()
{
// Just hard code the list for now
var commandLookup = new Dictionary<string, ICommand>();
var iCommands = typeof(ICommand);
var cmdTypes = new List<Type>();
foreach (var eachAssembly in AppDomain.CurrentDomain.GetAssemblies())
foreach (var eachType in eachAssembly.GetTypes())
if (iCommands.IsAssignableFrom(eachType) && eachType.Name != iCommands.Name)
cmdTypes.Add(eachType);
foreach (var eachPkgType in cmdTypes)
{
var eachInstance = (ICommand)Activator.CreateInstance(eachPkgType);
foreach (var eachCmdKey in eachInstance.CommandKeys)
commandLookup.Add(eachCmdKey.ToLower(), eachInstance);
}
return commandLookup;
}
/// <summary>
/// Extract command line arguments into target information
/// </summary>
private static void ExtractArgs(string[] args, out List<string> orderedCommands, out Dictionary<string, string> lcArgsByName, out Dictionary<string, string> casedArgsByName)
{
orderedCommands = new List<string>();
lcArgsByName = new Dictionary<string, string>();
casedArgsByName = new Dictionary<string, string>();
string activeKeyLc = null;
string activeKeyCased = null;
foreach (var eachArgCased in args)
{
var eachArgLc = eachArgCased.ToLower();
if (eachArgLc.StartsWith("--"))
{
activeKeyLc = eachArgLc.Substring(2);
activeKeyCased = eachArgCased.Substring(2);
orderedCommands.Add(activeKeyLc);
}
else if (eachArgLc.StartsWith("-"))
{
activeKeyLc = eachArgLc.Substring(1);
activeKeyCased = eachArgCased.Substring(1);
lcArgsByName[activeKeyLc] = "";
casedArgsByName[activeKeyCased] = "";
}
else if (activeKeyCased == null)
{
throw new Exception("Unexpected token: " + eachArgCased);
}
else
{
lcArgsByName[activeKeyLc] = (lcArgsByName[activeKeyLc] + " " + eachArgLc).Trim();
casedArgsByName[activeKeyCased] = (casedArgsByName[activeKeyCased] + " " + eachArgCased).Trim();
}
}
}
}
}
| |
#region Imports (using)
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Drawing.Text;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Collections;
#endregion
namespace CPrintReportStringDemo
{
#region public enums
public enum CharsPerLine {CPL80, CPL96,CPL120,CPL160};
public enum PrintOrientation {Portrait,Landscape};
public enum PrintPreview {Print,Preview};
public enum TitleStyle {Default,Bold,Italic,BoldItalic};
public enum MarginExtender {None,OneTenthInch,OneQuarterInch,OneHalfInch,ThreeQuarterInch,OneInch};
#endregion
public class CPrintReportString
{
public CPrintReportString()
{
//
// TODO: Add constructor logic here
//
}
#region Class Level Variables
// Print directives allow you to change properites
// dynamically within the print string.
// <:CH1>Heading 1
// <:CH2>Heading 2
// <:CH3>Heading 3
// <:CH4>Heading 4
// <:NEWPAGE>
// <:NOLINES>
// <:SUBTITLE>New SubTitle Line
// <:PAGENBR0> resets the page count
private string _ColHdr1;
private string _ColHdr2;
private string _ColHdr3;
private string _ColHdr4;
private string _SubTitle;
private string _SubTitle2;
private string _SubTitle3;
private string _SubTitle4;
private string _Title;
private bool _SepLines=false;
private Single _TitleFontSize;
private TitleStyle _TitleFontStyle;
private bool _PrintFooter=true;
private bool _DrawBox;
private MarginExtender _LeftMarginExtender;
private MarginExtender _RightMarginExtender;
private MarginExtender _TopMarginExtender;
private MarginExtender _BottomMarginExtender;
private PrintDocument PrintDoc;
private string msRptString;
private int miNL;
private int mI;
private int miChrPerLine;
private int PageNbr;
private bool Portrait=true;
private ArrayList ColHdrArrayList=new System.Collections.ArrayList();
private short ColHdrCount=0;
private Single DetailFontSize;
private string sFooter;
const string DETAIL_FONT="Courier New";
const int DETAIL_FONT_SIZE_80=10;
const int DETAIL_FONT_SIZE_96=9;
const int DETAIL_FONT_SIZE_120=8;
const int DETAIL_FONT_SIZE_160=6;
const bool DETAIL_FONT_BOLD=true;
private TBMemoLine tbm;
private Single LineHeight;
private Single LineWidth;
private Single xPos;
private Single yPos;
private Font PrintFont;
private string sLine;
private string sHdrLine;
private Single CharWidth;
private System.Drawing.SizeF sz;
private Single TextWidth;
private string sPageNbr;
private Single x1;
private Single y1;
private Single x2;
private Single y2;
private Pen drPen = new Pen(Color.Black,1);
private Single LeftMargin;
private Single RightMargin;
private Single TopMargin;
private Single BottomMargin;
#endregion
#region Public Properties
public string ColHdr1
{
get
{
return _ColHdr1;
}
set
{
_ColHdr1 = value;
}
}
public string ColHdr2
{
get
{
return _ColHdr2;
}
set
{
_ColHdr2 = value;
}
}
public string ColHdr3
{
get
{
return _ColHdr3;
}
set
{
_ColHdr3 = value;
}
}
public string ColHdr4
{
get
{
return _ColHdr4;
}
set
{
_ColHdr4 = value;
}
}
public string SubTitle
{
get
{
return _SubTitle;
}
set
{
_SubTitle = value;
}
}
public string SubTitle2
{
get
{
return _SubTitle2;
}
set
{
_SubTitle2 = value;
}
}
public string SubTitle3
{
get
{
return _SubTitle3;
}
set
{
_SubTitle3 = value;
}
}
public string SubTitle4
{
get
{
return _SubTitle4;
}
set
{
_SubTitle4 = value;
}
}
public string Title
{
get
{
return _Title;
}
set
{
_Title = value;
}
}
public bool SepLines
{
get
{
return _SepLines;
}
set
{
_SepLines = value;
}
}
public Single TitleFontSize
{
get
{
return _TitleFontSize;
}
set
{
_TitleFontSize = value;
}
}
public TitleStyle TitleFontStyle
{
get
{
return _TitleFontStyle;
}
set
{
_TitleFontStyle = value;
}
}
public bool PrintFooter
{
get
{
return _PrintFooter;
}
set
{
_PrintFooter = value;
}
}
public string Footer
{
get { return this.sFooter; }
set { this.sFooter = value; }
}
public bool DrawBox
{
get
{
return _DrawBox;
}
set
{
_DrawBox = value;
}
}
public MarginExtender LeftMarginExtender
{
get
{
return _LeftMarginExtender;
}
set
{
_LeftMarginExtender=value;
}
}
public MarginExtender RightMarginExtender
{
get
{
return _RightMarginExtender;
}
set
{
_RightMarginExtender=value;
}
}
public MarginExtender TopMarginExtender
{
get
{
return _TopMarginExtender;
}
set
{
_TopMarginExtender=value;
}
}
public MarginExtender BottomMarginExtender
{
get
{
return _BottomMarginExtender;
}
set
{
_BottomMarginExtender=value;
}
}
#endregion
#region Public Methods
public void PrintOrPreview(CharsPerLine CPL,
string PPrintBlock, string PTitle,
string PSubTitle, PrintPreview PVOption,
PrintOrientation Layout)
{
PrintOrPreview(CPL,PPrintBlock,PTitle,PSubTitle,PVOption,Layout,"","","","");
}
public void PrintOrPreview(CharsPerLine CPL,
string PPrintBlock, string PTitle,
string PSubTitle, PrintPreview PVOption,
PrintOrientation Layout,string ColHdr1)
{
PrintOrPreview(CPL,PPrintBlock,PTitle,PSubTitle,PVOption,Layout,ColHdr1,"","","");
}
public void PrintOrPreview(CharsPerLine CPL,
string PPrintBlock, string PTitle,
string PSubTitle, PrintPreview PVOption,
PrintOrientation Layout,string ColHdr1,string ColHdr2)
{
PrintOrPreview(CPL,PPrintBlock,PTitle,PSubTitle,PVOption,Layout,ColHdr1,ColHdr2,"","");
}
public void PrintOrPreview(CharsPerLine CPL,
string PPrintBlock, string PTitle,
string PSubTitle, PrintPreview PVOption,
PrintOrientation Layout,string ColHdr1,string ColHdr2,
string ColHdr3)
{
PrintOrPreview(CPL,PPrintBlock,PTitle,PSubTitle,PVOption,Layout,ColHdr1,ColHdr2,ColHdr3,"");
}
public void PrintOrPreview(CharsPerLine CPL,
string PPrintBlock, string PTitle,
string PSubTitle, PrintPreview PVOption,
PrintOrientation Layout,string ColHdr1,string ColHdr2,
string ColHdr3,string ColHdr4)
{
PrintPreviewDialog previewDialog;
tbm = new TBMemoLine();
Portrait =(Layout==PrintOrientation.Portrait);
msRptString=PPrintBlock;
_Title = PTitle;
_SubTitle=PSubTitle;
SetUpColHdrArray(ColHdr1,ColHdr2,ColHdr3,ColHdr4);
miChrPerLine=(int) CPL;
// create two memoline objects so that we can use
// nested calls to memoline w/o stepping
// on each other, used only when wordwrap is on
if (sFooter.Length == 0)
{
sFooter = "Printed on: " + DateTime.Now.ToString();
}
// chars per line will vary based on the margins
switch (CPL)
{
case CharsPerLine.CPL80:
DetailFontSize = DETAIL_FONT_SIZE_80;
break;
case CharsPerLine.CPL96:
DetailFontSize = DETAIL_FONT_SIZE_96;
break;
case CharsPerLine.CPL120:
DetailFontSize = DETAIL_FONT_SIZE_120;
break;
case CharsPerLine.CPL160:
DetailFontSize = DETAIL_FONT_SIZE_160;
break;
default:
throw new System.Exception("Invalid CharsPerLine parameter");
}
// set up memoline
miNL = tbm.MLCount(msRptString);
if(miNL==0)
{
MessageBox.Show("No lines to print in report string.");
return;
}
mI=0;
PrintDoc = new PrintDocument();
PrintDoc.PrintPage += new PrintPageEventHandler(this.OnPrintPage);
PrintDoc.DefaultPageSettings.Landscape=(Layout == PrintOrientation.Landscape);
PrintDoc.DocumentName=_Title;
if(PVOption == PrintPreview.Preview)
{
previewDialog = new PrintPreviewDialog();
previewDialog.Document = PrintDoc;
previewDialog.ShowDialog();
previewDialog.Dispose();
}
else
PrintDoc.Print();
}
#endregion
#region Private Methods
// Handles requests for print pages from PrintDoc object.
private void OnPrintPage(object sender,PrintPageEventArgs e)
{
int iLineLen = miChrPerLine;
// compute the margins after determining landscape or portrait
PrintFont = new Font(DETAIL_FONT,DetailFontSize);
sz = e.Graphics.MeasureString("M",PrintFont);
CharWidth = sz.Width;
// check for margin extenders
Single lmExt = 0;
Single rmExt = 0;
Single tmExt = 0;
Single bmExt = 0;
GetMarginExtenders(ref lmExt,ref rmExt,ref tmExt,ref bmExt);
// determine the print area
System.Drawing.Rectangle rect =
new System.Drawing.Rectangle((int) (e.PageBounds.X + 15 + lmExt),
(int) (e.PageBounds.Y + 15 + tmExt),
(int) (e.PageBounds.Width - (80 + rmExt)),
(int) (e.PageBounds.Height - (75 + bmExt)));
RightMargin = rect.Right;
LeftMargin = rect.Left;
TopMargin = rect.Top;
BottomMargin = rect.Bottom;
xPos = LeftMargin;
yPos=TopMargin;
if(_DrawBox)
{
Pen drPen2 = new Pen(Color.Black,2);
e.Graphics.DrawRectangle(drPen2,rect);
}
// print the header on this page first thing
// print the title
PrintTitle(e);
// print the subtitle1
PrintAllExtantSubTitles(e);
PrintFont = new Font(DETAIL_FONT,DetailFontSize,FontStyle.Bold);
PrintExtantColumnHeaders(e);
// we can now call memoline to get the print data
bool bBlank;
/* Print directives
<:CH1>Heading 1
<:CH2>Heading 2
<:CH3>Heading 3
<:CH4>Heading 4
<:NEWPAGE>
<:NOLINES>
<:LINES>
<:SUBTITLE>New SubTitle Line
<:SUBTITLE2>New SubTitle Line
<:SUBTITLE3>New SubTitle Line
<:SUBTITLE4>New SubTitle Line
<:PAGENBR0> resets the page count
*/
for(int i=mI; i < miNL; i++)
{
// print a detail line
sLine = tbm.MemoLine(i);
// ck for print directives
if(sLine.Length>0)
{
if(sLine.StartsWith("<:"))
{
short k=HandlePrintDirectives(sLine);
switch(k)
{
case 1: continue;
case 2:
EndPage(e);
e.HasMorePages=true;
mI= i + 1;
return;
default:break;
}
}
}
if(sLine==null || sLine.Length==0)
// dont print blank line, just bump yos
bBlank=true;
else
{
LineHeight=PrintFont.GetHeight(e.Graphics);
xPos=LeftMargin;
bBlank=false;
}
// print the detail line
PrintFont=new Font(DETAIL_FONT,DetailFontSize,FontStyle.Bold);
e.Graphics.DrawString(sLine,PrintFont,Brushes.Black,xPos,yPos,new StringFormat());
yPos += LineHeight;
// ck to see if we underline every line
if(_SepLines && !bBlank)
PrintSeparatorLine(e,ref xPos,ref yPos,LeftMargin);
// ck to see if at end of the page
if(yPos>=(BottomMargin-(2*LineHeight)))
{
// end of page, ck for more lines to print
EndPage(e);
// ck for more lines to print
if(i < miNL)
{
e.HasMorePages=true;
// set ptr to next line back
mI= i + 1;
return;
}
else
{
e.HasMorePages=false;
PageNbr=0;// in chase called again from preview
mI = 0;
return;
}
}// end ck for more pages
}// end for
e.HasMorePages = false;
mI = 0;
PageNbr = 0; // in case called again from preview print
//print a footer on the last page
yPos = BottomMargin - LineHeight;
x1 = LeftMargin;
y1 = yPos;
x2 = RightMargin;
y2 = yPos;
e.Graphics.DrawLine(drPen, x1, y1, x2, y2);
PrintFont.Dispose();
PrintFont = new Font("Arial", 10);
xPos = LeftMargin;
e.Graphics.DrawString(sFooter,
PrintFont,
Brushes.Black,
xPos,
yPos,
new StringFormat());
}// end PrintPage
private void EndPage(PrintPageEventArgs e)
{
yPos=BottomMargin-(2*LineHeight);
yPos+=10;
x1=LeftMargin;
y1=yPos;
x2=RightMargin;
y2=yPos;
if(_PrintFooter)
PrintFooterLine(e,ref xPos,ref yPos,LeftMargin);
}
private void PrintSeparatorLine(PrintPageEventArgs e,ref Single xPos,ref Single yPos,Single LeftMargin)
{
// insert a print separator line
yPos+=2;
x1=LeftMargin;
y1=yPos;
x2=RightMargin;
y2=yPos;
e.Graphics.DrawLine(drPen,x1,y1,x2,y2);
yPos+=2;
}
private void PrintFooterLine(PrintPageEventArgs e,ref Single xPos,ref Single yPos,Single LeftMargin)
{
e.Graphics.DrawLine(drPen,x1,y1,x2,y2);
yPos+=4;
PrintFont.Dispose();
PrintFont=new Font("Arial",10);
xPos=LeftMargin;
e.Graphics.DrawString(sFooter,PrintFont,Brushes.Black,xPos,yPos,new StringFormat());
}
private void PrintExtantColumnHeaders(PrintPageEventArgs e)
{
float LineHeight;
// if headings are extant print them
if(ColHdrCount>0)
{
for(short p=0;p<=ColHdrCount-1;p++)
{
yPos +=2;
if(ColHdrArrayList[p].ToString().Length>0)
{
xPos=LeftMargin;
LineHeight=PrintFont.GetHeight(e.Graphics);
sHdrLine=_SubTitle;
e.Graphics.DrawString(ColHdrArrayList[p].ToString(),PrintFont,Brushes.Black,xPos,yPos,new StringFormat());
yPos += LineHeight;
}
}
// now draw a line after column headers
yPos+=4;
x1=LeftMargin;
y1=yPos;
x2=RightMargin;
y2=yPos;
e.Graphics.DrawLine(drPen,x1,y1,x2,y2);
yPos+=4;
// print a second(double)line
x1 = LeftMargin;
y1 = yPos;
x2 = RightMargin;
y2 = yPos;
e.Graphics.DrawLine(drPen, x1, y1, x2, y2);
yPos += 4;
}
}
private void PrintTitle(PrintPageEventArgs e)
{
PageNbr++;
if(_TitleFontStyle==TitleStyle.BoldItalic)
PrintFont = new Font("Arial", _TitleFontSize,FontStyle.Italic | FontStyle.Bold);
else if(_TitleFontStyle==TitleStyle.Bold)
PrintFont = new Font("Arial",_TitleFontSize, FontStyle.Bold);
else if(_TitleFontStyle == TitleStyle.Italic)
PrintFont = new Font("Arial", _TitleFontSize,FontStyle.Italic);
else
PrintFont = new Font("Arial", _TitleFontSize);
LineHeight = PrintFont.GetHeight(e.Graphics);
sz = e.Graphics.MeasureString(_Title,PrintFont);
TextWidth = sz.Width;
LineWidth = RightMargin + LeftMargin;
xPos = (LineWidth - TextWidth) / 2;
e.Graphics.DrawString(_Title,PrintFont,Brushes.Black,
xPos, yPos,new StringFormat());
yPos += LineHeight;
}
private void PrintAllExtantSubTitles(PrintPageEventArgs e)
{
PrintFont = new Font("Arial",10,FontStyle.Bold);
xPos=LeftMargin;
LineHeight=PrintFont.GetHeight(e.Graphics);
sHdrLine=_SubTitle;
e.Graphics.DrawString(_SubTitle,PrintFont,Brushes.Black,
xPos, yPos,new StringFormat());
// print the page number on the right end of last subtitle line
if(_SubTitle2.Length==0)
{
sPageNbr = PageNbr.ToString();
xPos = RightMargin - (7 * CharWidth);
e.Graphics.DrawString("Page: " + sPageNbr, PrintFont, Brushes.Black, xPos, yPos, new StringFormat());
}
yPos += LineHeight;
// print subtitle2 if extant
if(_SubTitle2.Length>0)
{
PrintFont=new Font("Arial",10,FontStyle.Bold);
xPos = LeftMargin;
LineHeight = PrintFont.GetHeight(e.Graphics);
sHdrLine = _SubTitle2;
e.Graphics.DrawString(sHdrLine,PrintFont,Brushes.Black,xPos,yPos,new StringFormat());
if(_SubTitle3.Length==0)
{
sPageNbr = PageNbr.ToString();
xPos = RightMargin - (7 * CharWidth);
e.Graphics.DrawString("Page: " + sPageNbr,PrintFont,Brushes.Black,xPos,yPos,new StringFormat());
}
yPos += LineHeight;
}
// print subtitle3 if extant
if(_SubTitle3.Length>0)
{
PrintFont=new Font("Arial",10,FontStyle.Bold);
xPos = LeftMargin;
LineHeight = PrintFont.GetHeight(e.Graphics);
sHdrLine = _SubTitle3;
e.Graphics.DrawString(sHdrLine,PrintFont,Brushes.Black,xPos,yPos,new StringFormat());
if(_SubTitle4.Length==0)
{
sPageNbr = PageNbr.ToString();
xPos = RightMargin - (7 * CharWidth);
e.Graphics.DrawString("Page: " + sPageNbr,PrintFont,Brushes.Black,xPos,yPos,new StringFormat());
}
yPos += LineHeight;
}
// print subtitle4 if extant
if(_SubTitle4.Length>0)
{
PrintFont=new Font("Arial",10,FontStyle.Bold);
xPos = LeftMargin;
LineHeight = PrintFont.GetHeight(e.Graphics);
sHdrLine = _SubTitle4;
e.Graphics.DrawString(sHdrLine,PrintFont,Brushes.Black,xPos,yPos,new StringFormat());
sPageNbr = PageNbr.ToString();
xPos = RightMargin - (7 * CharWidth);
e.Graphics.DrawString("Page: " + sPageNbr,PrintFont,Brushes.Black,xPos,yPos,new StringFormat());
yPos += LineHeight;
}
// now draw a line after a little space
x1=LeftMargin;
y1=yPos;
x2=RightMargin;
y2=yPos;
e.Graphics.DrawLine(drPen,x1,y1,x2,y2);
}
private short HandlePrintDirectives(string sLine)
{
// return 0, if no goto action
// return 1 if goto next line
// return 2 if goto EndPage
// we have a print diretive telling us to change something
if(sLine.Substring(2,3)=="CH1")
{
// new col1 hdr
ColHdrArrayList[0]=sLine.Substring(6);
return 1;
}
else if(sLine.Substring(2,3)=="CH2")
{
ColHdrArrayList[1]=sLine.Substring(6);
return 1;
}
else if (sLine.Substring(2,3)=="CH3")
{
ColHdrArrayList[2]=sLine.Substring(6);
return 1;
}
else if(sLine.Substring(2,3)=="CH4")
{
ColHdrArrayList[3]=sLine.Substring(6);
return 1;
}
else if(sLine.Substring(2,7).StartsWith("NEWPAGE"))
return 2;
else if(sLine.Substring(2,5).StartsWith("LINES"))
{
_SepLines=true;
return 1;
}
else if(sLine.Substring(2,7)=="NOLINES")
{
_SepLines=false;
return 1;
}
else if(sLine.Substring(2,8).StartsWith("PAGENBR0"))
{
PageNbr=0;
return 1;
}
else if(sLine.Substring(2,9).StartsWith("SUBTITLE1"))
{
_SubTitle=sLine.Substring(12);
return 1;
}
else if(sLine.Substring(2,9).StartsWith("SUBTITLE2"))
{
_SubTitle2=sLine.Substring(12);
return 1;
}
else if(sLine.Substring(2,9).StartsWith("SUBTITLE3"))
{
_SubTitle3=sLine.Substring(12);
return 1;
}
else if(sLine.Substring(2,9).StartsWith("SUBTITLE4"))
{
_SubTitle4=sLine.Substring(12);
return 1;
}
return 1;
}
private void SetUpColHdrArray(string ColHdr1,string ColHdr2,string ColHdr3,string ColHdr4)
{
if(ColHdr1.Length>0)
{
ColHdrArrayList.Add(ColHdr1);
ColHdrCount++;
}
if(ColHdr2.Length>0)
{
ColHdrArrayList.Add(ColHdr2);
ColHdrCount++;
}
if(ColHdr3.Length>0)
{
ColHdrArrayList.Add(ColHdr3);
ColHdrCount++;
}
if(ColHdr4.Length>0)
{
ColHdrArrayList.Add(ColHdr4);
ColHdrCount++;
}
}
private void GetMarginExtenders(ref Single lmExt,ref Single rmExt,ref Single tmExt,ref Single bmExt)
{
lmExt = GetOneMarginExtender(_LeftMarginExtender);
rmExt = GetOneMarginExtender(_RightMarginExtender);
tmExt = GetOneMarginExtender(_TopMarginExtender);
bmExt = GetOneMarginExtender(_BottomMarginExtender);
}
private Single GetOneMarginExtender(MarginExtender ext)
{
const int oneTenth=5;
const int oneQtr=15;
const int oneHalf=30;
const int threeQtr=45;
const int oneInch=60;
switch (ext)
{
case MarginExtender.None:
return 0;
case MarginExtender.OneTenthInch:
return oneTenth;
case MarginExtender.OneQuarterInch:
return oneQtr;
case MarginExtender.OneHalfInch:
return oneHalf;
case MarginExtender.ThreeQuarterInch:
return threeQtr;
case MarginExtender.OneInch:
return oneInch;
default:
return 0;
}
}
#endregion
}
#region TBMemoLine Class
public class TBMemoLine
{
private TextBox tb;
//private string [] a;
// returns the requeste line from the memo string
public string MemoLine(int nL)
{
if(nL >= 0 && nL <= tb.Lines.Length)
return tb.Lines[nL];
//return a[nL];
else
return string.Empty;
}
// returns the number of lines in the memo string
public int MLCount(string s)
{
tb = new TextBox();
tb.Text = s;
//a=tb.Lines;
//return a.Length;
return tb.Lines.Length;
}
}//end class TBMemoline
#endregion
}// end namespace
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Cci;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Roslyn.Utilities;
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class EEAssemblyBuilder : PEAssemblyBuilderBase
{
internal readonly ImmutableHashSet<MethodSymbol> Methods;
public EEAssemblyBuilder(
SourceAssemblySymbol sourceAssembly,
EmitOptions emitOptions,
ImmutableArray<MethodSymbol> methods,
ModulePropertiesForSerialization serializationProperties,
ImmutableArray<NamedTypeSymbol> additionalTypes,
CompilationTestData testData) :
base(
sourceAssembly,
emitOptions,
outputKind: OutputKind.DynamicallyLinkedLibrary,
serializationProperties: serializationProperties,
manifestResources: SpecializedCollections.EmptyEnumerable<ResourceDescription>(),
assemblySymbolMapper: null,
additionalTypes: additionalTypes)
{
Methods = ImmutableHashSet.CreateRange(methods);
if (testData != null)
{
this.SetMethodTestData(testData.Methods);
testData.Module = this;
}
}
protected override IModuleReference TranslateModule(ModuleSymbol symbol, DiagnosticBag diagnostics)
{
var moduleSymbol = symbol as PEModuleSymbol;
if ((object)moduleSymbol != null)
{
var module = moduleSymbol.Module;
// Expose the individual runtime Windows.*.winmd modules as assemblies.
// (The modules were wrapped in a placeholder Windows.winmd assembly
// in MetadataUtilities.MakeAssemblyReferences.)
if (MetadataUtilities.IsWindowsComponent(module.MetadataReader, module.Name) &&
MetadataUtilities.IsWindowsAssemblyName(moduleSymbol.ContainingAssembly.Name))
{
var identity = module.ReadAssemblyIdentityOrThrow();
return new Microsoft.CodeAnalysis.ExpressionEvaluator.AssemblyReference(identity);
}
}
return base.TranslateModule(symbol, diagnostics);
}
internal override bool IgnoreAccessibility
{
get { return true; }
}
public override int CurrentGenerationOrdinal => 0;
internal override VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol symbol, MethodSymbol topLevelMethod)
{
var method = symbol as EEMethodSymbol;
if (((object)method != null) && Methods.Contains(method))
{
var defs = GetLocalDefinitions(method.Locals);
return new SlotAllocator(defs);
}
Debug.Assert(!Methods.Contains(symbol));
return null;
}
private static ImmutableArray<LocalDefinition> GetLocalDefinitions(ImmutableArray<LocalSymbol> locals)
{
var builder = ArrayBuilder<LocalDefinition>.GetInstance();
foreach (var local in locals)
{
if (local.DeclarationKind == LocalDeclarationKind.Constant)
{
continue;
}
var def = ToLocalDefinition(local, builder.Count);
Debug.Assert(((EELocalSymbol)local).Ordinal == def.SlotIndex);
builder.Add(def);
}
return builder.ToImmutableAndFree();
}
private static LocalDefinition ToLocalDefinition(LocalSymbol local, int index)
{
// See EvaluationContext.GetLocals.
TypeSymbol type;
LocalSlotConstraints constraints;
if (local.DeclarationKind == LocalDeclarationKind.FixedVariable)
{
type = ((PointerTypeSymbol)local.Type).PointedAtType;
constraints = LocalSlotConstraints.ByRef | LocalSlotConstraints.Pinned;
}
else
{
type = local.Type;
constraints = (local.IsPinned ? LocalSlotConstraints.Pinned : LocalSlotConstraints.None) |
((local.RefKind == RefKind.None) ? LocalSlotConstraints.None : LocalSlotConstraints.ByRef);
}
return new LocalDefinition(
local,
local.Name,
(Cci.ITypeReference)type,
slot: index,
synthesizedKind: (SynthesizedLocalKind)local.SynthesizedKind,
id: LocalDebugId.None,
pdbAttributes: Cci.PdbWriter.DefaultLocalAttributesValue,
constraints: constraints,
isDynamic: false,
dynamicTransformFlags: ImmutableArray<TypedConstant>.Empty);
}
private sealed class SlotAllocator : VariableSlotAllocator
{
private readonly ImmutableArray<LocalDefinition> _locals;
internal SlotAllocator(ImmutableArray<LocalDefinition> locals)
{
_locals = locals;
}
public override void AddPreviousLocals(ArrayBuilder<Cci.ILocalDefinition> builder)
{
builder.AddRange(_locals);
}
public override LocalDefinition GetPreviousLocal(
Cci.ITypeReference type,
ILocalSymbolInternal symbol,
string nameOpt,
SynthesizedLocalKind synthesizedKind,
LocalDebugId id,
uint pdbAttributes,
LocalSlotConstraints constraints,
bool isDynamic,
ImmutableArray<TypedConstant> dynamicTransformFlags)
{
var local = symbol as EELocalSymbol;
if ((object)local == null)
{
return null;
}
return _locals[local.Ordinal];
}
public override string PreviousStateMachineTypeName
{
get { return null; }
}
public override bool TryGetPreviousHoistedLocalSlotIndex(SyntaxNode currentDeclarator, Cci.ITypeReference currentType, SynthesizedLocalKind synthesizedKind, LocalDebugId currentId, out int slotIndex)
{
slotIndex = -1;
return false;
}
public override int PreviousHoistedLocalSlotCount
{
get { return 0; }
}
public override bool TryGetPreviousAwaiterSlotIndex(Cci.ITypeReference currentType, out int slotIndex)
{
slotIndex = -1;
return false;
}
public override bool TryGetPreviousClosure(SyntaxNode closureSyntax, out DebugId closureId)
{
closureId = default(DebugId);
return false;
}
public override bool TryGetPreviousLambda(SyntaxNode lambdaOrLambdaBodySyntax, bool isLambdaBody, out DebugId lambdaId)
{
lambdaId = default(DebugId);
return false;
}
public override int PreviousAwaiterSlotCount
{
get { return 0; }
}
public override DebugId? MethodId
{
get
{
return null;
}
}
}
}
}
| |
//
// 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 Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute.Models
{
/// <summary>
/// The List VM Images operation response.
/// </summary>
public partial class VirtualMachineVMImageListResponse : AzureOperationResponse, IEnumerable<VirtualMachineVMImageListResponse.VirtualMachineVMImage>
{
private IList<VirtualMachineVMImageListResponse.VirtualMachineVMImage> _vMImages;
/// <summary>
/// Optional. The virtual machine images associated with your
/// subscription.
/// </summary>
public IList<VirtualMachineVMImageListResponse.VirtualMachineVMImage> VMImages
{
get { return this._vMImages; }
set { this._vMImages = value; }
}
/// <summary>
/// Initializes a new instance of the VirtualMachineVMImageListResponse
/// class.
/// </summary>
public VirtualMachineVMImageListResponse()
{
this.VMImages = new LazyList<VirtualMachineVMImageListResponse.VirtualMachineVMImage>();
}
/// <summary>
/// Gets the sequence of VMImages.
/// </summary>
public IEnumerator<VirtualMachineVMImageListResponse.VirtualMachineVMImage> GetEnumerator()
{
return this.VMImages.GetEnumerator();
}
/// <summary>
/// Gets the sequence of VMImages.
/// </summary>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// The data disk configuration.
/// </summary>
public partial class DataDiskConfiguration
{
private string _hostCaching;
/// <summary>
/// Optional. Specifies the platform caching behavior of the data
/// disk blob for read/write efficiency. The default vault is
/// ReadOnly.
/// </summary>
public string HostCaching
{
get { return this._hostCaching; }
set { this._hostCaching = 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 int _logicalDiskSizeInGB;
/// <summary>
/// Optional. Specifies the size, in GB, of an empty VHD to be
/// attached to the virtual machine. The VHD can be created as
/// part of disk attach or create virtual machine calls by
/// specifying the value for this property. Azure creates the
/// empty VHD based on size preference and attaches the newly
/// created VHD to the virtual machine.
/// </summary>
public int LogicalDiskSizeInGB
{
get { return this._logicalDiskSizeInGB; }
set { this._logicalDiskSizeInGB = value; }
}
private int? _logicalUnitNumber;
/// <summary>
/// Optional. Specifies the Logical Unit Number (LUN) for the data
/// disk. The LUN specifies the slot in which the data drive
/// appears when mounted for usage by the virtual machine. This
/// element is only listed when more than one data disk is
/// attached to a virtual machine.
/// </summary>
public int? LogicalUnitNumber
{
get { return this._logicalUnitNumber; }
set { this._logicalUnitNumber = value; }
}
private Uri _mediaLink;
/// <summary>
/// Optional. Specifies the location of the disk in Windows Azure
/// storage.
/// </summary>
public Uri MediaLink
{
get { return this._mediaLink; }
set { this._mediaLink = value; }
}
private string _name;
/// <summary>
/// Optional. Specifies the name of the VHD to use to create the
/// data disk for the virtual machine.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
/// <summary>
/// Initializes a new instance of the DataDiskConfiguration class.
/// </summary>
public DataDiskConfiguration()
{
}
}
/// <summary>
/// The OS disk configuration.
/// </summary>
public partial class OSDiskConfiguration
{
private string _hostCaching;
/// <summary>
/// Optional. Specifies the platform caching behavior of the
/// operating system disk blob for read/write efficiency.
/// </summary>
public string HostCaching
{
get { return this._hostCaching; }
set { this._hostCaching = 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 int _logicalDiskSizeInGB;
/// <summary>
/// Optional. Specifies the size, in GB, of an empty VHD to be
/// attached to the virtual machine. The VHD can be created as
/// part of disk attach or create virtual machine calls by
/// specifying the value for this property. Azure creates the
/// empty VHD based on size preference and attaches the newly
/// created VHD to the virtual machine.
/// </summary>
public int LogicalDiskSizeInGB
{
get { return this._logicalDiskSizeInGB; }
set { this._logicalDiskSizeInGB = value; }
}
private Uri _mediaLink;
/// <summary>
/// Optional. Specifies the location of the disk in Windows Azure
/// storage.
/// </summary>
public Uri MediaLink
{
get { return this._mediaLink; }
set { this._mediaLink = value; }
}
private string _name;
/// <summary>
/// Optional. Specifies the name of an operating system image in
/// the image repository.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private string _operatingSystem;
/// <summary>
/// Optional. The operating system running in the virtual machine.
/// </summary>
public string OperatingSystem
{
get { return this._operatingSystem; }
set { this._operatingSystem = value; }
}
private string _oSState;
/// <summary>
/// Optional. The operating system state in the virtual machine.
/// </summary>
public string OSState
{
get { return this._oSState; }
set { this._oSState = value; }
}
/// <summary>
/// Initializes a new instance of the OSDiskConfiguration class.
/// </summary>
public OSDiskConfiguration()
{
}
}
/// <summary>
/// A virtual machine image associated with your subscription.
/// </summary>
public partial class VirtualMachineVMImage
{
private string _affinityGroup;
/// <summary>
/// Optional. The affinity group name of the virtual machine image.
/// </summary>
public string AffinityGroup
{
get { return this._affinityGroup; }
set { this._affinityGroup = value; }
}
private string _category;
/// <summary>
/// Optional. The classification of the virtual machine image.
/// </summary>
public string Category
{
get { return this._category; }
set { this._category = value; }
}
private System.DateTime? _createdTime;
/// <summary>
/// Optional. The date when the virtual machine image was created.
/// </summary>
public System.DateTime? CreatedTime
{
get { return this._createdTime; }
set { this._createdTime = value; }
}
private IList<VirtualMachineVMImageListResponse.DataDiskConfiguration> _dataDiskConfigurations;
/// <summary>
/// Optional. The data disk configurations.
/// </summary>
public IList<VirtualMachineVMImageListResponse.DataDiskConfiguration> DataDiskConfigurations
{
get { return this._dataDiskConfigurations; }
set { this._dataDiskConfigurations = value; }
}
private string _deploymentName;
/// <summary>
/// Optional. The deployment name of the virtual machine image.
/// </summary>
public string DeploymentName
{
get { return this._deploymentName; }
set { this._deploymentName = value; }
}
private string _description;
/// <summary>
/// Optional. The description of the virtual machine image.
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
private string _eula;
/// <summary>
/// Optional. Specifies the End User License Agreement that is
/// associated with the image. The value for this element is a
/// string, but it is recommended that the value be a URL that
/// points to a EULA.
/// </summary>
public string Eula
{
get { return this._eula; }
set { this._eula = value; }
}
private string _iconUri;
/// <summary>
/// Optional. Provides the URI to the icon for this Operating
/// System Image.
/// </summary>
public string IconUri
{
get { return this._iconUri; }
set { this._iconUri = value; }
}
private string _imageFamily;
/// <summary>
/// Optional. The image family of the virtual machine image.
/// </summary>
public string ImageFamily
{
get { return this._imageFamily; }
set { this._imageFamily = value; }
}
private bool? _isPremium;
/// <summary>
/// Optional. The indicator of whether the virtual machine image is
/// premium.
/// </summary>
public bool? IsPremium
{
get { return this._isPremium; }
set { this._isPremium = value; }
}
private string _label;
/// <summary>
/// Optional. An identifier for the virtual machine image.
/// </summary>
public string Label
{
get { return this._label; }
set { this._label = value; }
}
private string _language;
/// <summary>
/// Optional. The language of the virtual machine image.
/// </summary>
public string Language
{
get { return this._language; }
set { this._language = value; }
}
private string _location;
/// <summary>
/// Optional. The location name of the virtual machine image.
/// </summary>
public string Location
{
get { return this._location; }
set { this._location = value; }
}
private System.DateTime? _modifiedTime;
/// <summary>
/// Optional. The date when the virtual machine image was created.
/// </summary>
public System.DateTime? ModifiedTime
{
get { return this._modifiedTime; }
set { this._modifiedTime = value; }
}
private string _name;
/// <summary>
/// Optional. The name of the virtual machine image.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private VirtualMachineVMImageListResponse.OSDiskConfiguration _oSDiskConfiguration;
/// <summary>
/// Optional. The OS disk configuration.
/// </summary>
public VirtualMachineVMImageListResponse.OSDiskConfiguration OSDiskConfiguration
{
get { return this._oSDiskConfiguration; }
set { this._oSDiskConfiguration = value; }
}
private Uri _pricingDetailLink;
/// <summary>
/// Optional. Specifies the URI that points to the pricing detail.
/// </summary>
public Uri PricingDetailLink
{
get { return this._pricingDetailLink; }
set { this._pricingDetailLink = value; }
}
private Uri _privacyUri;
/// <summary>
/// Optional. Specifies the URI that points to a document that
/// contains the privacy policy related to the image.
/// </summary>
public Uri PrivacyUri
{
get { return this._privacyUri; }
set { this._privacyUri = value; }
}
private System.DateTime? _publishedDate;
/// <summary>
/// Optional. Specifies the date when the image was added to the
/// image repository.
/// </summary>
public System.DateTime? PublishedDate
{
get { return this._publishedDate; }
set { this._publishedDate = value; }
}
private string _publisherName;
/// <summary>
/// Optional. The name of the publisher of this VM Image in Azure.
/// </summary>
public string PublisherName
{
get { return this._publisherName; }
set { this._publisherName = value; }
}
private string _recommendedVMSize;
/// <summary>
/// Optional. The recommended size of the virtual machine image.
/// </summary>
public string RecommendedVMSize
{
get { return this._recommendedVMSize; }
set { this._recommendedVMSize = value; }
}
private string _roleName;
/// <summary>
/// Optional. The role name of the virtual machine image.
/// </summary>
public string RoleName
{
get { return this._roleName; }
set { this._roleName = value; }
}
private string _serviceName;
/// <summary>
/// Optional. The service name of the virtual machine image.
/// </summary>
public string ServiceName
{
get { return this._serviceName; }
set { this._serviceName = value; }
}
private bool? _showInGui;
/// <summary>
/// Optional. Specifies whether to show in Gui.
/// </summary>
public bool? ShowInGui
{
get { return this._showInGui; }
set { this._showInGui = value; }
}
private string _smallIconUri;
/// <summary>
/// Optional. Specifies the URI to the small icon that is displayed
/// when the image is presented in the Azure Management Portal.
/// </summary>
public string SmallIconUri
{
get { return this._smallIconUri; }
set { this._smallIconUri = value; }
}
/// <summary>
/// Initializes a new instance of the VirtualMachineVMImage class.
/// </summary>
public VirtualMachineVMImage()
{
this.DataDiskConfigurations = new LazyList<VirtualMachineVMImageListResponse.DataDiskConfiguration>();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public abstract class ImmutableDictionaryBuilderTestBase : ImmutablesTestBase
{
[Fact]
public void Add()
{
var builder = this.GetBuilder<string, int>();
builder.Add("five", 5);
builder.Add(new KeyValuePair<string, int>("six", 6));
Assert.Equal(5, builder["five"]);
Assert.Equal(6, builder["six"]);
Assert.False(builder.ContainsKey("four"));
}
/// <summary>
/// Verifies that "adding" an entry to the dictionary that already exists
/// with exactly the same key and value will *not* throw an exception.
/// </summary>
/// <remarks>
/// The BCL Dictionary type would throw in this circumstance.
/// But in an immutable world, not only do we not care so much since the result is the same.
/// </remarks>
[Fact]
public void AddExactDuplicate()
{
var builder = this.GetBuilder<string, int>();
builder.Add("five", 5);
builder.Add("five", 5);
Assert.Equal(1, builder.Count);
}
[Fact]
public void AddExistingKeyWithDifferentValue()
{
var builder = this.GetBuilder<string, int>();
builder.Add("five", 5);
Assert.Throws<ArgumentException>(() => builder.Add("five", 6));
}
[Fact]
public void Indexer()
{
var builder = this.GetBuilder<string, int>();
// Set and set again.
builder["five"] = 5;
Assert.Equal(5, builder["five"]);
builder["five"] = 5;
Assert.Equal(5, builder["five"]);
// Set to a new value.
builder["five"] = 50;
Assert.Equal(50, builder["five"]);
// Retrieve an invalid value.
Assert.Throws<KeyNotFoundException>(() => builder["foo"]);
}
[Fact]
public void ContainsPair()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5);
var builder = this.GetBuilder(map);
Assert.True(builder.Contains(new KeyValuePair<string, int>("five", 5)));
}
[Fact]
public void RemovePair()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
Assert.True(builder.Remove(new KeyValuePair<string, int>("five", 5)));
Assert.False(builder.Remove(new KeyValuePair<string, int>("foo", 1)));
Assert.Equal(1, builder.Count);
Assert.Equal(6, builder["six"]);
}
[Fact]
public void RemoveKey()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
builder.Remove("five");
Assert.Equal(1, builder.Count);
Assert.Equal(6, builder["six"]);
}
[Fact]
public void CopyTo()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5);
var builder = this.GetBuilder(map);
var array = new KeyValuePair<string, int>[2]; // intentionally larger than source.
builder.CopyTo(array, 1);
Assert.Equal(new KeyValuePair<string, int>(), array[0]);
Assert.Equal(new KeyValuePair<string, int>("five", 5), array[1]);
Assert.Throws<ArgumentNullException>(() => builder.CopyTo(null, 0));
}
[Fact]
public void IsReadOnly()
{
var builder = this.GetBuilder<string, int>();
Assert.False(builder.IsReadOnly);
}
[Fact]
public void Keys()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
CollectionAssertAreEquivalent(new[] { "five", "six" }, builder.Keys);
CollectionAssertAreEquivalent(new[] { "five", "six" }, ((IReadOnlyDictionary<string, int>)builder).Keys.ToArray());
}
[Fact]
public void Values()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
CollectionAssertAreEquivalent(new[] { 5, 6 }, builder.Values);
CollectionAssertAreEquivalent(new[] { 5, 6 }, ((IReadOnlyDictionary<string, int>)builder).Values.ToArray());
}
[Fact]
public void TryGetValue()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
int value;
Assert.True(builder.TryGetValue("five", out value) && value == 5);
Assert.True(builder.TryGetValue("six", out value) && value == 6);
Assert.False(builder.TryGetValue("four", out value));
Assert.Equal(0, value);
}
[Fact]
public void TryGetKey()
{
var builder = Empty<int>(StringComparer.OrdinalIgnoreCase)
.Add("a", 1).ToBuilder();
string actualKey;
Assert.True(TryGetKeyHelper(builder, "a", out actualKey));
Assert.Equal("a", actualKey);
Assert.True(TryGetKeyHelper(builder, "A", out actualKey));
Assert.Equal("a", actualKey);
Assert.False(TryGetKeyHelper(builder, "b", out actualKey));
Assert.Equal("b", actualKey);
}
[Fact]
public void EnumerateTest()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
using (var enumerator = builder.GetEnumerator())
{
Assert.True(enumerator.MoveNext());
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
}
var manualEnum = builder.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => manualEnum.Current);
while (manualEnum.MoveNext()) { }
Assert.False(manualEnum.MoveNext());
Assert.Throws<InvalidOperationException>(() => manualEnum.Current);
}
[Fact]
public void IDictionaryMembers()
{
var builder = this.GetBuilder<string, int>();
var dictionary = (IDictionary)builder;
dictionary.Add("a", 1);
Assert.True(dictionary.Contains("a"));
Assert.Equal(1, dictionary["a"]);
Assert.Equal(new[] { "a" }, dictionary.Keys.Cast<string>().ToArray());
Assert.Equal(new[] { 1 }, dictionary.Values.Cast<int>().ToArray());
dictionary["a"] = 2;
Assert.Equal(2, dictionary["a"]);
dictionary.Remove("a");
Assert.False(dictionary.Contains("a"));
Assert.False(dictionary.IsFixedSize);
Assert.False(dictionary.IsReadOnly);
}
[Fact]
public void IDictionaryEnumerator()
{
var builder = this.GetBuilder<string, int>();
var dictionary = (IDictionary)builder;
dictionary.Add("a", 1);
var enumerator = dictionary.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.True(enumerator.MoveNext());
Assert.Equal(enumerator.Entry, enumerator.Current);
Assert.Equal(enumerator.Key, enumerator.Entry.Key);
Assert.Equal(enumerator.Value, enumerator.Entry.Value);
Assert.Equal("a", enumerator.Key);
Assert.Equal(1, enumerator.Value);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.False(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.True(enumerator.MoveNext());
Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key);
Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value);
Assert.Equal("a", enumerator.Key);
Assert.Equal(1, enumerator.Value);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.False(enumerator.MoveNext());
}
[Fact]
public void ICollectionMembers()
{
var builder = this.GetBuilder<string, int>();
var collection = (ICollection)builder;
collection.CopyTo(new object[0], 0);
builder.Add("b", 2);
Assert.True(builder.ContainsKey("b"));
var array = new object[builder.Count + 1];
collection.CopyTo(array, 1);
Assert.Null(array[0]);
Assert.Equal(new object[] { null, new DictionaryEntry("b", 2), }, array);
Assert.False(collection.IsSynchronized);
Assert.NotNull(collection.SyncRoot);
Assert.Same(collection.SyncRoot, collection.SyncRoot);
}
protected abstract bool TryGetKeyHelper<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey equalKey, out TKey actualKey);
/// <summary>
/// Gets the Builder for a given dictionary instance.
/// </summary>
/// <typeparam name="TKey">The type of key.</typeparam>
/// <typeparam name="TValue">The type of value.</typeparam>
/// <returns>The builder.</returns>
protected abstract IDictionary<TKey, TValue> GetBuilder<TKey, TValue>(IImmutableDictionary<TKey, TValue> basis = null);
/// <summary>
/// Gets an empty immutable dictionary.
/// </summary>
/// <typeparam name="TKey">The type of key.</typeparam>
/// <typeparam name="TValue">The type of value.</typeparam>
/// <returns>The immutable dictionary.</returns>
protected abstract IImmutableDictionary<TKey, TValue> GetEmptyImmutableDictionary<TKey, TValue>();
protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer);
}
}
| |
/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using ZXing.Aztec.Internal;
using ZXing.Common;
namespace ZXing.Aztec.Test
{
/// <summary>
/// Tests for the Detector
/// @author Frank Yellin
/// </summary>
public class DetectorTest
{
[Test]
public void testErrorInParameterLocatorZeroZero()
{
// Layers=1, CodeWords=1. So the parameter info and its Reed-Solomon info
// will be completely zero!
testErrorInParameterLocator("X");
}
[Test]
public void testErrorInParameterLocatorCompact()
{
testErrorInParameterLocator("This is an example Aztec symbol for Wikipedia.");
}
[Test]
public void testErrorInParameterLocatorNotCompact()
{
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz";
testErrorInParameterLocator(alphabet + alphabet + alphabet);
}
// Test that we can tolerate errors in the parameter locator bits
private static void testErrorInParameterLocator(String data)
{
var aztec = Internal.Encoder.encode(data, 25, Internal.Encoder.DEFAULT_AZTEC_LAYERS);
var random = new Random(aztec.Matrix.GetHashCode()); // pseudo-random, but deterministic
var layers = aztec.Layers;
var compact = aztec.isCompact;
var orientationPoints = getOrientationPoints(aztec);
foreach (bool isMirror in new[] {false, true})
{
foreach (BitMatrix matrix in getRotations(aztec.Matrix))
{
// Systematically try every possible 1- and 2-bit error.
for (int error1 = 0; error1 < orientationPoints.Count; error1++)
{
for (int error2 = error1; error2 < orientationPoints.Count; error2++)
{
BitMatrix copy = isMirror ? transpose(matrix) : clone(matrix);
copy.flip(orientationPoints[error1].X, orientationPoints[error1].Y);
if (error2 > error1)
{
// if error2 == error1, we only test a single error
copy.flip(orientationPoints[error2].X, orientationPoints[error2].Y);
}
// The detector doesn't seem to work when matrix bits are only 1x1. So magnify.
AztecDetectorResult r = new Detector(makeLarger(copy, 3)).detect(isMirror);
Assert.IsNotNull(r);
Assert.AreEqual(r.NbLayers, layers);
Assert.AreEqual(r.Compact, compact);
DecoderResult res = new Internal.Decoder().decode(r);
Assert.AreEqual(data, res.Text);
}
}
// Try a few random three-bit errors;
for (int i = 0; i < 5; i++)
{
BitMatrix copy = clone(matrix);
ISet<int> errors = new SortedSet<int>();
while (errors.Count < 3)
{
// Quick and dirty way of getting three distinct integers between 1 and n.
errors.Add(random.Next(orientationPoints.Count));
}
foreach (int error in errors)
{
copy.flip(orientationPoints[error].X, orientationPoints[error].Y);
}
var result = new Detector(makeLarger(copy, 3)).detect(false);
if (result != null)
{
Assert.Fail("Should not reach here");
}
}
}
}
}
// Zooms a bit matrix so that each bit is factor x factor
private static BitMatrix makeLarger(BitMatrix input, int factor)
{
var width = input.Width;
var output = new BitMatrix(width*factor);
for (var inputY = 0; inputY < width; inputY++)
{
for (var inputX = 0; inputX < width; inputX++)
{
if (input[inputX, inputY])
{
output.setRegion(inputX*factor, inputY*factor, factor, factor);
}
}
}
return output;
}
// Returns a list of the four rotations of the BitMatrix.
private static List<BitMatrix> getRotations(BitMatrix matrix0)
{
BitMatrix matrix90 = rotateRight(matrix0);
BitMatrix matrix180 = rotateRight(matrix90);
BitMatrix matrix270 = rotateRight(matrix180);
return new List<BitMatrix> {matrix0, matrix90, matrix180, matrix270};
}
// Rotates a square BitMatrix to the right by 90 degrees
private static BitMatrix rotateRight(BitMatrix input)
{
var width = input.Width;
var result = new BitMatrix(width);
for (var x = 0; x < width; x++)
{
for (var y = 0; y < width; y++)
{
if (input[x, y])
{
result[y, width - x - 1] = true;
}
}
}
return result;
}
// Returns the transpose of a bit matrix, which is equivalent to rotating the
// matrix to the right, and then flipping it left-to-right
private static BitMatrix transpose(BitMatrix input)
{
var width = input.Width;
var result = new BitMatrix(width);
for (var x = 0; x < width; x++)
{
for (var y = 0; y < width; y++)
{
if (input[x, y])
{
result[y, x] = true;
}
}
}
return result;
}
private static BitMatrix clone(BitMatrix input)
{
var width = input.Width;
var result = new BitMatrix(width);
for (var x = 0; x < width; x++)
{
for (var y = 0; y < width; y++)
{
if (input[x, y])
{
result[x, y] = true;
}
}
}
return result;
}
private static List<Detector.Point> getOrientationPoints(AztecCode code)
{
var center = code.Matrix.Width/2;
var offset = code.isCompact ? 5 : 7;
var result = new List<Detector.Point>();
for (var xSign = -1; xSign <= 1; xSign += 2)
{
for (var ySign = -1; ySign <= 1; ySign += 2)
{
result.Add(new Detector.Point(center + xSign*offset, center + ySign*offset));
result.Add(new Detector.Point(center + xSign*(offset - 1), center + ySign*offset));
result.Add(new Detector.Point(center + xSign*offset, center + ySign*(offset - 1)));
}
}
return result;
}
public static void Shuffle<T>(IList<T> list, Random random)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = random.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
}
| |
#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.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Profiling;
using Grpc.Core.Utils;
using NUnit.Framework;
namespace Grpc.Core.Tests
{
public class ClientServerTest
{
const string Host = "127.0.0.1";
MockServiceHelper helper;
Server server;
Channel channel;
[SetUp]
public void Init()
{
helper = new MockServiceHelper(Host);
server = helper.GetServer();
server.Start();
channel = helper.GetChannel();
}
[TearDown]
public void Cleanup()
{
channel.ShutdownAsync().Wait();
server.ShutdownAsync().Wait();
}
[Test]
public async Task UnaryCall()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
return Task.FromResult(request);
});
Assert.AreEqual("ABC", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "ABC"));
Assert.AreEqual("ABC", await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "ABC"));
}
[Test]
public void UnaryCall_ServerHandlerThrows()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
throw new Exception("This was thrown on purpose by a test");
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode);
var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unknown, ex2.Status.StatusCode);
}
[Test]
public void UnaryCall_ServerHandlerThrowsRpcException()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
throw new RpcException(new Status(StatusCode.Unauthenticated, ""));
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode);
Assert.AreEqual(0, ex.Trailers.Count);
var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode);
Assert.AreEqual(0, ex.Trailers.Count);
}
[Test]
public void UnaryCall_ServerHandlerThrowsRpcExceptionWithTrailers()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
var trailers = new Metadata { {"xyz", "xyz-value"} };
throw new RpcException(new Status(StatusCode.Unauthenticated, ""), trailers);
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode);
Assert.AreEqual(1, ex.Trailers.Count);
Assert.AreEqual("xyz", ex.Trailers[0].Key);
Assert.AreEqual("xyz-value", ex.Trailers[0].Value);
var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode);
Assert.AreEqual(1, ex2.Trailers.Count);
Assert.AreEqual("xyz", ex2.Trailers[0].Key);
Assert.AreEqual("xyz-value", ex2.Trailers[0].Value);
}
[Test]
public void UnaryCall_ServerHandlerSetsStatus()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
context.Status = new Status(StatusCode.Unauthenticated, "");
return Task.FromResult("");
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode);
Assert.AreEqual(0, ex.Trailers.Count);
var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode);
Assert.AreEqual(0, ex2.Trailers.Count);
}
[Test]
public void UnaryCall_ServerHandlerSetsStatusAndTrailers()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
context.Status = new Status(StatusCode.Unauthenticated, "");
context.ResponseTrailers.Add("xyz", "xyz-value");
return Task.FromResult("");
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode);
Assert.AreEqual(1, ex.Trailers.Count);
Assert.AreEqual("xyz", ex.Trailers[0].Key);
Assert.AreEqual("xyz-value", ex.Trailers[0].Value);
var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode);
Assert.AreEqual(1, ex2.Trailers.Count);
Assert.AreEqual("xyz", ex2.Trailers[0].Key);
Assert.AreEqual("xyz-value", ex2.Trailers[0].Value);
}
[Test]
public async Task ClientStreamingCall()
{
helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
{
string result = "";
await requestStream.ForEachAsync((request) =>
{
result += request;
return TaskUtils.CompletedTask;
});
await Task.Delay(100);
return result;
});
var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall());
await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" });
Assert.AreEqual("ABC", await call.ResponseAsync);
Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode);
Assert.IsNotNull(call.GetTrailers());
}
[Test]
public async Task ServerStreamingCall()
{
helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) =>
{
await responseStream.WriteAllAsync(request.Split(new []{' '}));
context.ResponseTrailers.Add("xyz", "");
});
var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), "A B C");
CollectionAssert.AreEqual(new string[] { "A", "B", "C" }, await call.ResponseStream.ToListAsync());
Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode);
Assert.AreEqual("xyz", call.GetTrailers()[0].Key);
}
[Test]
public async Task ServerStreamingCall_EndOfStreamIsIdempotent()
{
helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>((request, responseStream, context) => TaskUtils.CompletedTask);
var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), "");
Assert.IsFalse(await call.ResponseStream.MoveNext());
Assert.IsFalse(await call.ResponseStream.MoveNext());
}
[Test]
public void ServerStreamingCall_ErrorCanBeAwaitedTwice()
{
helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>((request, responseStream, context) =>
{
context.Status = new Status(StatusCode.InvalidArgument, "");
return TaskUtils.CompletedTask;
});
var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), "");
var ex = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext());
Assert.AreEqual(StatusCode.InvalidArgument, ex.Status.StatusCode);
// attempting MoveNext again should result in throwing the same exception.
var ex2 = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext());
Assert.AreEqual(StatusCode.InvalidArgument, ex2.Status.StatusCode);
}
[Test]
public void ServerStreamingCall_TrailersFromMultipleSourcesGetConcatenated()
{
helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>((request, responseStream, context) =>
{
context.ResponseTrailers.Add("xyz", "xyz-value");
throw new RpcException(new Status(StatusCode.InvalidArgument, ""), new Metadata { {"abc", "abc-value"} });
});
var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), "");
var ex = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext());
Assert.AreEqual(StatusCode.InvalidArgument, ex.Status.StatusCode);
Assert.AreEqual(2, call.GetTrailers().Count);
Assert.AreEqual(2, ex.Trailers.Count);
Assert.AreEqual("xyz", ex.Trailers[0].Key);
Assert.AreEqual("xyz-value", ex.Trailers[0].Value);
Assert.AreEqual("abc", ex.Trailers[1].Key);
Assert.AreEqual("abc-value", ex.Trailers[1].Value);
}
[Test]
public async Task DuplexStreamingCall()
{
helper.DuplexStreamingHandler = new DuplexStreamingServerMethod<string, string>(async (requestStream, responseStream, context) =>
{
while (await requestStream.MoveNext())
{
await responseStream.WriteAsync(requestStream.Current);
}
context.ResponseTrailers.Add("xyz", "xyz-value");
});
var call = Calls.AsyncDuplexStreamingCall(helper.CreateDuplexStreamingCall());
await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" });
CollectionAssert.AreEqual(new string[] { "A", "B", "C" }, await call.ResponseStream.ToListAsync());
Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode);
Assert.AreEqual("xyz-value", call.GetTrailers()[0].Value);
}
[Test]
public async Task AsyncUnaryCall_EchoMetadata()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
foreach (Metadata.Entry metadataEntry in context.RequestHeaders)
{
if (metadataEntry.Key != "user-agent")
{
context.ResponseTrailers.Add(metadataEntry);
}
}
return Task.FromResult("");
});
var headers = new Metadata
{
{ "ascii-header", "abcdefg" },
{ "binary-header-bin", new byte[] { 1, 2, 3, 0, 0xff } }
};
var call = Calls.AsyncUnaryCall(helper.CreateUnaryCall(new CallOptions(headers: headers)), "ABC");
await call;
Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode);
var trailers = call.GetTrailers();
Assert.AreEqual(2, trailers.Count);
Assert.AreEqual(headers[0].Key, trailers[0].Key);
Assert.AreEqual(headers[0].Value, trailers[0].Value);
Assert.AreEqual(headers[1].Key, trailers[1].Key);
CollectionAssert.AreEqual(headers[1].ValueBytes, trailers[1].ValueBytes);
}
[Test]
public void UnknownMethodHandler()
{
var nonexistentMethod = new Method<string, string>(
MethodType.Unary,
MockServiceHelper.ServiceName,
"NonExistentMethod",
Marshallers.StringMarshaller,
Marshallers.StringMarshaller);
var callDetails = new CallInvocationDetails<string, string>(channel, nonexistentMethod, new CallOptions());
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(callDetails, "abc"));
Assert.AreEqual(StatusCode.Unimplemented, ex.Status.StatusCode);
}
[Test]
public void StatusDetailIsUtf8()
{
// some japanese and chinese characters
var nonAsciiString = "\u30a1\u30a2\u30a3 \u62b5\u6297\u662f\u5f92\u52b3\u7684";
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
context.Status = new Status(StatusCode.Unknown, nonAsciiString);
return Task.FromResult("");
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode);
Assert.AreEqual(nonAsciiString, ex.Status.Detail);
}
[Test]
public void ServerCallContext_PeerInfoPresent()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
return Task.FromResult(context.Peer);
});
string peer = Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc");
Assert.IsTrue(peer.Contains(Host));
}
[Test]
public void ServerCallContext_HostAndMethodPresent()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
Assert.IsTrue(context.Host.Contains(Host));
Assert.AreEqual("/tests.Test/Unary", context.Method);
return Task.FromResult("PASS");
});
Assert.AreEqual("PASS", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
}
[Test]
public void ServerCallContext_AuthContextNotPopulated()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
Assert.IsFalse(context.AuthContext.IsPeerAuthenticated);
Assert.AreEqual(0, context.AuthContext.Properties.Count());
return Task.FromResult("PASS");
});
Assert.AreEqual("PASS", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
}
}
}
| |
// Copyright (c) Pomelo Foundation. All rights reserved.
// Licensed under the MIT. See LICENSE in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Update;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Pomelo.EntityFrameworkCore.MySql.Update.Internal
{
// TODO: Revamp
public class MySqlUpdateSqlGenerator : UpdateSqlGenerator, IMySqlUpdateSqlGenerator
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public MySqlUpdateSqlGenerator(
[NotNull] UpdateSqlGeneratorDependencies dependencies)
: base(dependencies)
{
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual ResultSetMapping AppendBulkInsertOperation(
StringBuilder commandStringBuilder,
IReadOnlyList<IReadOnlyModificationCommand> modificationCommands,
int commandPosition)
{
var table = StoreObjectIdentifier.Table(modificationCommands[0].TableName, modificationCommands[0].Schema);
if (modificationCommands.Count == 1
&& modificationCommands[0].ColumnModifications.All(o =>
!o.IsKey
|| !o.IsRead
|| o.Property?.GetValueGenerationStrategy(table) == MySqlValueGenerationStrategy.IdentityColumn))
{
return AppendInsertOperation(commandStringBuilder, modificationCommands[0], commandPosition);
}
var readOperations = modificationCommands[0].ColumnModifications.Where(o => o.IsRead).ToList();
var writeOperations = modificationCommands[0].ColumnModifications.Where(o => o.IsWrite).ToList();
var keyOperations = modificationCommands[0].ColumnModifications.Where(o => o.IsKey).ToList();
var nonIdentityOperations = modificationCommands[0].ColumnModifications
.Where(o => o.Property?.GetValueGenerationStrategy(table) != MySqlValueGenerationStrategy.IdentityColumn)
.ToList();
var defaultValuesOnly = writeOperations.Count == 0;
if (defaultValuesOnly)
{
if (nonIdentityOperations.Count == 0
|| readOperations.Count == 0)
{
foreach (var modification in modificationCommands)
{
AppendInsertOperation(commandStringBuilder, modification, commandPosition);
}
return readOperations.Count == 0
? ResultSetMapping.NoResultSet
: ResultSetMapping.LastInResultSet;
}
if (nonIdentityOperations.Count > 1)
{
nonIdentityOperations = new List<IColumnModification> { nonIdentityOperations.First() };
}
}
if (readOperations.Count == 0)
{
return AppendBulkInsertWithoutServerValues(commandStringBuilder, modificationCommands, writeOperations);
}
foreach (var modification in modificationCommands)
{
AppendInsertOperation(commandStringBuilder, modification, commandPosition);
}
return ResultSetMapping.LastInResultSet;
}
private ResultSetMapping AppendBulkInsertWithoutServerValues(
StringBuilder commandStringBuilder,
IReadOnlyList<IReadOnlyModificationCommand> modificationCommands,
List<IColumnModification> writeOperations)
{
Debug.Assert(writeOperations.Count > 0);
var name = modificationCommands[0].TableName;
var schema = modificationCommands[0].Schema;
AppendInsertCommandHeader(commandStringBuilder, name, schema, writeOperations);
AppendValuesHeader(commandStringBuilder, writeOperations);
AppendValues(commandStringBuilder, name, schema, writeOperations);
for (var i = 1; i < modificationCommands.Count; i++)
{
commandStringBuilder.Append(",").AppendLine();
AppendValues(commandStringBuilder, name, schema, modificationCommands[i].ColumnModifications.Where(o => o.IsWrite).ToList());
}
commandStringBuilder.Append(SqlGenerationHelper.StatementTerminator).AppendLine();
return ResultSetMapping.NoResultSet;
}
protected override void AppendInsertCommandHeader(
StringBuilder commandStringBuilder,
string name,
string schema,
IReadOnlyList<IColumnModification> operations)
{
Check.NotNull(commandStringBuilder, nameof(commandStringBuilder));
Check.NotEmpty(name, nameof(name));
Check.NotNull(operations, nameof(operations));
base.AppendInsertCommandHeader(commandStringBuilder, name, schema, operations);
if (operations.Count <= 0)
{
// An empty column and value list signales MySQL that only default values should be used.
// If not all columns have default values defined, an error occurs if STRICT_ALL_TABLES has been set.
commandStringBuilder.Append(" ()");
}
}
protected override void AppendValuesHeader(
StringBuilder commandStringBuilder,
IReadOnlyList<IColumnModification> operations)
{
Check.NotNull(commandStringBuilder, nameof(commandStringBuilder));
Check.NotNull(operations, nameof(operations));
commandStringBuilder.AppendLine();
commandStringBuilder.Append("VALUES ");
}
protected override void AppendValues(
StringBuilder commandStringBuilder,
string name,
string schema,
IReadOnlyList<IColumnModification> operations)
{
base.AppendValues(commandStringBuilder, name, schema, operations);
if (operations.Count <= 0)
{
commandStringBuilder.Append("()");
}
}
protected override ResultSetMapping AppendSelectAffectedCountCommand(StringBuilder commandStringBuilder, string name, string schema, int commandPosition)
{
commandStringBuilder
.Append("SELECT ROW_COUNT()")
.Append(SqlGenerationHelper.StatementTerminator).AppendLine()
.AppendLine();
return ResultSetMapping.LastInResultSet;
}
protected override void AppendWhereAffectedClause(
StringBuilder commandStringBuilder,
IReadOnlyList<IColumnModification> operations)
{
Check.NotNull(commandStringBuilder, nameof(commandStringBuilder));
Check.NotNull(operations, nameof(operations));
// If a compound key consists of an auto_increment column and a database generated column (e.g. a DEFAULT
// value), then we only want to filter by `LAST_INSERT_ID()`, because we can't know what the other generated
// values are.
// Therefore, we filter out the key columns that are marked as `read`, but are not an auto_increment column,
// so that `AppendIdentityWhereCondition()` can safely called for the remaining auto_increment column.
// Because we currently use `MySqlValueGenerationStrategy.IdentityColumn` for auto_increment columns as well
// as CURRENT_TIMESTAMP columns, we need to use `MySqlPropertyExtensions.IsCompatibleAutoIncrementColumn()`
// to ensure, that the column is actually an auto_increment column.
// See https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql/issues/1300
var nonDefaultOperations = operations
.Where(
o => !o.IsKey ||
!o.IsRead ||
o.Property == null ||
!o.Property.ValueGenerated.HasFlag(ValueGenerated.OnAdd) ||
MySqlPropertyExtensions.IsCompatibleAutoIncrementColumn(o.Property))
.ToList()
.AsReadOnly();
base.AppendWhereAffectedClause(commandStringBuilder, nonDefaultOperations);
}
protected override void AppendIdentityWhereCondition(StringBuilder commandStringBuilder, IColumnModification columnModification)
{
SqlGenerationHelper.DelimitIdentifier(commandStringBuilder, columnModification.ColumnName);
commandStringBuilder.Append(" = ")
.Append("LAST_INSERT_ID()");
}
protected override void AppendRowsAffectedWhereCondition(StringBuilder commandStringBuilder, int expectedRowsAffected)
=> commandStringBuilder
.Append("ROW_COUNT() = ")
.Append(expectedRowsAffected.ToString(CultureInfo.InvariantCulture));
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.CodeAnalysis;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X
{
public class ViewComponentTagHelperDescriptorFactoryTest
{
private static readonly Assembly _assembly = typeof(ViewComponentTagHelperDescriptorFactoryTest).GetTypeInfo().Assembly;
[Fact]
public void CreateDescriptor_UnderstandsStringParameters()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(StringParameterViewComponent).FullName);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var expectedDescriptor = TagHelperDescriptorBuilder.Create(
ViewComponentTagHelperConventions.Kind,
"__Generated__StringParameterViewComponentTagHelper",
typeof(StringParameterViewComponent).GetTypeInfo().Assembly.GetName().Name)
.TypeName("__Generated__StringParameterViewComponentTagHelper")
.DisplayName("StringParameterViewComponentTagHelper")
.TagMatchingRuleDescriptor(rule =>
rule
.RequireTagName("vc:string-parameter")
.RequireAttributeDescriptor(attribute => attribute.Name("foo"))
.RequireAttributeDescriptor(attribute => attribute.Name("bar")))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("foo")
.PropertyName("foo")
.TypeName(typeof(string).FullName)
.DisplayName("string StringParameterViewComponentTagHelper.foo"))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("bar")
.PropertyName("bar")
.TypeName(typeof(string).FullName)
.DisplayName("string StringParameterViewComponentTagHelper.bar"))
.AddMetadata(ViewComponentTagHelperMetadata.Name, "StringParameter")
.Build();
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
Assert.Equal(expectedDescriptor, descriptor, TagHelperDescriptorComparer.Default);
}
[Fact]
public void CreateDescriptor_UnderstandsVariousParameterTypes()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(VariousParameterViewComponent).FullName);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var expectedDescriptor = TagHelperDescriptorBuilder.Create(
ViewComponentTagHelperConventions.Kind,
"__Generated__VariousParameterViewComponentTagHelper",
typeof(VariousParameterViewComponent).GetTypeInfo().Assembly.GetName().Name)
.TypeName("__Generated__VariousParameterViewComponentTagHelper")
.DisplayName("VariousParameterViewComponentTagHelper")
.TagMatchingRuleDescriptor(rule =>
rule
.RequireTagName("vc:various-parameter")
.RequireAttributeDescriptor(attribute => attribute.Name("test-enum"))
.RequireAttributeDescriptor(attribute => attribute.Name("test-string"))
.RequireAttributeDescriptor(attribute => attribute.Name("baz")))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("test-enum")
.PropertyName("testEnum")
.TypeName(typeof(VariousParameterViewComponent).FullName + "." + nameof(VariousParameterViewComponent.TestEnum))
.AsEnum()
.DisplayName(typeof(VariousParameterViewComponent).FullName + "." + nameof(VariousParameterViewComponent.TestEnum) + " VariousParameterViewComponentTagHelper.testEnum"))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("test-string")
.PropertyName("testString")
.TypeName(typeof(string).FullName)
.DisplayName("string VariousParameterViewComponentTagHelper.testString"))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("baz")
.PropertyName("baz")
.TypeName(typeof(int).FullName)
.DisplayName("int VariousParameterViewComponentTagHelper.baz"))
.AddMetadata(ViewComponentTagHelperMetadata.Name, "VariousParameter")
.Build();
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
Assert.Equal(expectedDescriptor, descriptor, TagHelperDescriptorComparer.Default);
}
[Fact]
public void CreateDescriptor_UnderstandsGenericParameters()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(GenericParameterViewComponent).FullName);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var expectedDescriptor = TagHelperDescriptorBuilder.Create(
ViewComponentTagHelperConventions.Kind,
"__Generated__GenericParameterViewComponentTagHelper",
typeof(GenericParameterViewComponent).GetTypeInfo().Assembly.GetName().Name)
.TypeName("__Generated__GenericParameterViewComponentTagHelper")
.DisplayName("GenericParameterViewComponentTagHelper")
.TagMatchingRuleDescriptor(rule =>
rule
.RequireTagName("vc:generic-parameter")
.RequireAttributeDescriptor(attribute => attribute.Name("foo")))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("foo")
.PropertyName("Foo")
.TypeName("System.Collections.Generic.List<System.String>")
.DisplayName("System.Collections.Generic.List<System.String> GenericParameterViewComponentTagHelper.Foo"))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("bar")
.PropertyName("Bar")
.TypeName("System.Collections.Generic.Dictionary<System.String, System.Int32>")
.AsDictionaryAttribute("bar-", typeof(int).FullName)
.DisplayName("System.Collections.Generic.Dictionary<System.String, System.Int32> GenericParameterViewComponentTagHelper.Bar"))
.AddMetadata(ViewComponentTagHelperMetadata.Name, "GenericParameter")
.Build();
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
Assert.Equal(expectedDescriptor, descriptor, TagHelperDescriptorComparer.Default);
}
[Fact]
public void CreateDescriptor_AddsDiagnostic_ForViewComponentWithNoInvokeMethod()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(ViewComponentWithoutInvokeMethod).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_CannotFindMethod.Id, diagnostic.Id);
}
[Fact]
public void CreateDescriptor_ForViewComponentWithInvokeAsync_UnderstandsGenericTask()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(AsyncViewComponentWithGenericTask).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
Assert.Empty(descriptor.GetAllDiagnostics());
}
[Fact]
public void CreateDescriptor_ForViewComponentWithInvokeAsync_UnderstandsNonGenericTask()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(AsyncViewComponentWithNonGenericTask).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
Assert.Empty(descriptor.GetAllDiagnostics());
}
[Fact]
public void CreateDescriptor_ForViewComponentWithInvokeAsync_DoesNotUnderstandVoid()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(AsyncViewComponentWithString).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_AsyncMethod_ShouldReturnTask.Id, diagnostic.Id);
}
[Fact]
public void CreateDescriptor_ForViewComponentWithInvokeAsync_DoesNotUnderstandString()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(AsyncViewComponentWithString).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_AsyncMethod_ShouldReturnTask.Id, diagnostic.Id);
}
[Fact]
public void CreateDescriptor_ForViewComponentWithInvoke_DoesNotUnderstandVoid()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(SyncViewComponentWithVoid).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_SyncMethod_ShouldReturnValue.Id, diagnostic.Id);
}
[Fact]
public void CreateDescriptor_ForViewComponentWithInvoke_DoesNotUnderstandNonGenericTask()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(SyncViewComponentWithNonGenericTask).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_SyncMethod_CannotReturnTask.Id, diagnostic.Id);
}
[Fact]
public void CreateDescriptor_ForViewComponentWithInvoke_DoesNotUnderstandGenericTask()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(SyncViewComponentWithGenericTask).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_SyncMethod_CannotReturnTask.Id, diagnostic.Id);
}
}
public class StringParameterViewComponent
{
public string Invoke(string foo, string bar) => null;
}
public class VariousParameterViewComponent
{
public string Invoke(TestEnum testEnum, string testString, int baz = 5) => null;
public enum TestEnum
{
A = 1,
B = 2,
C = 3
}
}
public class GenericParameterViewComponent
{
public string Invoke(List<string> Foo, Dictionary<string, int> Bar) => null;
}
public class ViewComponentWithoutInvokeMethod
{
}
public class AsyncViewComponentWithGenericTask
{
public Task<string> InvokeAsync() => null;
}
public class AsyncViewComponentWithNonGenericTask
{
public Task InvokeAsync() => null;
}
public class AsyncViewComponentWithVoid
{
public void InvokeAsync() { }
}
public class AsyncViewComponentWithString
{
public string InvokeAsync() => null;
}
public class SyncViewComponentWithVoid
{
public void Invoke() { }
}
public class SyncViewComponentWithNonGenericTask
{
public Task Invoke() => null;
}
public class SyncViewComponentWithGenericTask
{
public Task<string> Invoke() => null;
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics.Performance;
namespace osu.Framework.Tests.Graphics
{
[TestFixture]
public class LifetimeEntryManagerTest
{
private TestLifetimeEntryManager manager;
[SetUp]
public void Setup()
{
manager = new TestLifetimeEntryManager();
}
[Test]
public void TestBasic()
{
manager.AddEntry(new LifetimeEntry { LifetimeStart = -1, LifetimeEnd = 1 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 1 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 2 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 1, LifetimeEnd = 2 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 2, LifetimeEnd = 2 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 2, LifetimeEnd = 3 });
checkCountAliveAt(0, 3);
checkCountAliveAt(1, 2);
checkCountAliveAt(2, 1);
checkCountAliveAt(0, 3);
checkCountAliveAt(3, 0);
}
[Test]
public void TestRemoveAndReAdd()
{
var entry = new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 1 };
manager.AddEntry(entry);
checkCountAliveAt(0, 1);
manager.RemoveEntry(entry);
checkCountAliveAt(0, 0);
manager.AddEntry(entry);
checkCountAliveAt(0, 1);
}
[Test]
public void TestDynamicChange()
{
manager.AddEntry(new LifetimeEntry { LifetimeStart = -1, LifetimeEnd = 0 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 1 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 1 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 1, LifetimeEnd = 2 });
checkCountAliveAt(0, 2);
manager.Entries[0].LifetimeEnd = 1;
manager.Entries[1].LifetimeStart = 1;
manager.Entries[2].LifetimeEnd = 0;
manager.Entries[3].LifetimeStart = 0;
checkCountAliveAt(0, 2);
foreach (var entry in manager.Entries)
{
entry.LifetimeEnd += 1;
entry.LifetimeStart += 1;
}
checkCountAliveAt(0, 1);
foreach (var entry in manager.Entries)
{
entry.LifetimeStart -= 1;
entry.LifetimeEnd -= 1;
}
checkCountAliveAt(0, 2);
}
[Test]
public void TestBoundaryCrossing()
{
manager.AddEntry(new LifetimeEntry { LifetimeStart = -1, LifetimeEnd = 0 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 1 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 1, LifetimeEnd = 2 });
// No crossings for the first update.
manager.Update(0);
checkNoCrossing(manager.Entries[0]);
checkNoCrossing(manager.Entries[1]);
checkNoCrossing(manager.Entries[2]);
manager.Update(2);
checkNoCrossing(manager.Entries[0]);
checkCrossing(manager.Entries[1], 0, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Forward);
checkCrossing(manager.Entries[2], 0, LifetimeBoundaryKind.Start, LifetimeBoundaryCrossingDirection.Forward);
checkCrossing(manager.Entries[2], 1, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Forward);
manager.Update(1);
checkNoCrossing(manager.Entries[0]);
checkNoCrossing(manager.Entries[1]);
checkCrossing(manager.Entries[2], 0, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Backward);
manager.Update(-1);
checkCrossing(manager.Entries[0], 0, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Backward);
checkCrossing(manager.Entries[1], 0, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Backward);
checkCrossing(manager.Entries[1], 1, LifetimeBoundaryKind.Start, LifetimeBoundaryCrossingDirection.Backward);
checkCrossing(manager.Entries[2], 0, LifetimeBoundaryKind.Start, LifetimeBoundaryCrossingDirection.Backward);
}
[Test]
public void TestLifetimeChangeOnCallback()
{
int updateTime = 0;
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 1 });
manager.EntryCrossedBoundary += (entry, kind, direction) =>
{
switch (kind)
{
case LifetimeBoundaryKind.End when direction == LifetimeBoundaryCrossingDirection.Forward:
entry.LifetimeEnd = 2;
break;
case LifetimeBoundaryKind.Start when direction == LifetimeBoundaryCrossingDirection.Backward:
entry.LifetimeEnd = 1;
break;
case LifetimeBoundaryKind.Start when direction == LifetimeBoundaryCrossingDirection.Forward:
entry.LifetimeStart = entry.LifetimeStart == 0 ? 1 : 0;
break;
}
// Lifetime changes are applied in the _next_ update.
// ReSharper disable once AccessToModifiedClosure - intentional.
manager.Update(updateTime);
};
manager.Update(updateTime = 0);
checkCountAliveAt(updateTime = 1, 1);
checkCountAliveAt(updateTime = -1, 0);
checkCountAliveAt(updateTime = 0, 0);
checkCountAliveAt(updateTime = 1, 1);
}
[Test]
public void TestUpdateWithTimeRange()
{
manager.AddEntry(new LifetimeEntry { LifetimeStart = -1, LifetimeEnd = 1 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 1 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 2 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 1, LifetimeEnd = 2 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 2, LifetimeEnd = 2 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 2, LifetimeEnd = 3 });
checkCountAliveAt(-3, -2, 0);
checkCountAliveAt(-3, -1, 1);
checkCountAliveAt(-2, 4, 6);
checkCountAliveAt(-1, 4, 6);
checkCountAliveAt(0, 4, 6);
checkCountAliveAt(1, 4, 4);
checkCountAliveAt(2, 4, 1);
checkCountAliveAt(3, 4, 0);
checkCountAliveAt(4, 4, 0);
}
[Test]
public void TestRemoveFutureAfterLifetimeChange()
{
manager.AddEntry(new LifetimeEntry { LifetimeStart = 1, LifetimeEnd = 2 });
checkCountAliveAt(0, 0);
manager.Entries[0].LifetimeEnd = 3;
manager.RemoveEntry(manager.Entries[0]);
checkCountAliveAt(1, 0);
}
[Test]
public void TestRemovePastAfterLifetimeChange()
{
manager.AddEntry(new LifetimeEntry { LifetimeStart = -2, LifetimeEnd = -1 });
checkCountAliveAt(0, 0);
manager.Entries[0].LifetimeStart = -3;
manager.RemoveEntry(manager.Entries[0]);
checkCountAliveAt(-2, 0);
}
[Test]
public void TestFuzz()
{
var rng = new Random(2222);
int currentTime = 0;
addEntry();
manager.EntryCrossedBoundary += (entry, kind, direction) => changeLifetime();
manager.Update(0);
int count = 1;
for (int i = 0; i < 1000; i++)
{
switch (rng.Next(3))
{
case 0:
if (count < 20)
{
addEntry();
count += 1;
}
else
{
removeEntry();
count -= 1;
}
break;
case 1:
changeLifetime();
break;
case 2:
changeTime();
break;
}
}
void randomLifetime(out double l, out double r)
{
l = rng.Next(5);
r = rng.Next(5);
if (l > r)
(l, r) = (r, l);
++r;
}
// ReSharper disable once AccessToModifiedClosure - intentional.
void checkAll() => checkAlivenessAt(currentTime);
void addEntry()
{
randomLifetime(out var l, out var r);
manager.AddEntry(new LifetimeEntry { LifetimeStart = l, LifetimeEnd = r });
checkAll();
}
void removeEntry()
{
var entry = manager.Entries[rng.Next(manager.Entries.Count)];
manager.RemoveEntry(entry);
checkAll();
}
void changeLifetime()
{
var entry = manager.Entries[rng.Next(manager.Entries.Count)];
randomLifetime(out var l, out var r);
entry.LifetimeStart = l;
entry.LifetimeEnd = r;
checkAll();
}
void changeTime()
{
int time = rng.Next(6);
currentTime = time;
checkAll();
}
}
private void checkCountAliveAt(int time, int expectedCount) => checkCountAliveAt(time, time, expectedCount);
private void checkCountAliveAt(int startTime, int endTime, int expectedCount)
{
checkAlivenessAt(startTime, endTime);
Assert.That(manager.Entries.Count(entry => entry.State == LifetimeEntryState.Current), Is.EqualTo(expectedCount));
}
private void checkAlivenessAt(int time) => checkAlivenessAt(time, time);
private void checkAlivenessAt(int startTime, int endTime)
{
manager.Update(startTime, endTime);
for (int i = 0; i < manager.Entries.Count; i++)
{
var entry = manager.Entries[i];
bool isAlive = entry.State == LifetimeEntryState.Current;
bool shouldBeAlive = endTime >= entry.LifetimeStart && startTime < entry.LifetimeEnd;
Assert.That(isAlive, Is.EqualTo(shouldBeAlive), $"Aliveness is invalid for entry {i}");
}
}
private void checkNoCrossing(LifetimeEntry entry) => Assert.That(manager.Crossings, Does.Not.Contain(entry));
private void checkCrossing(LifetimeEntry entry, int index, LifetimeBoundaryKind kind, LifetimeBoundaryCrossingDirection direction)
=> Assert.That(manager.Crossings[entry][index], Is.EqualTo((kind, direction)));
private class TestLifetimeEntryManager : LifetimeEntryManager
{
public IReadOnlyList<LifetimeEntry> Entries => entries;
private readonly List<LifetimeEntry> entries = new List<LifetimeEntry>();
public IReadOnlyDictionary<LifetimeEntry, List<(LifetimeBoundaryKind kind, LifetimeBoundaryCrossingDirection direction)>> Crossings => crossings;
private readonly Dictionary<LifetimeEntry, List<(LifetimeBoundaryKind kind, LifetimeBoundaryCrossingDirection direction)>> crossings =
new Dictionary<LifetimeEntry, List<(LifetimeBoundaryKind kind, LifetimeBoundaryCrossingDirection direction)>>();
public TestLifetimeEntryManager()
{
EntryCrossedBoundary += (entry, kind, direction) =>
{
if (!crossings.ContainsKey(entry))
crossings[entry] = new List<(LifetimeBoundaryKind kind, LifetimeBoundaryCrossingDirection direction)>();
crossings[entry].Add((kind, direction));
};
}
public new void AddEntry(LifetimeEntry entry)
{
entries.Add(entry);
base.AddEntry(entry);
}
public new bool RemoveEntry(LifetimeEntry entry)
{
if (base.RemoveEntry(entry))
{
entries.Remove(entry);
return true;
}
return false;
}
public new void ClearEntries()
{
entries.Clear();
base.ClearEntries();
}
public new bool Update(double time)
{
crossings.Clear();
return base.Update(time);
}
}
}
}
| |
// 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 AddUInt64()
{
var test = new SimpleBinaryOpTest__AddUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddUInt64
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt64);
private const int Op2ElementCount = VectorSize / sizeof(UInt64);
private const int RetElementCount = VectorSize / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64> _dataTable;
static SimpleBinaryOpTest__AddUInt64()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__AddUInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64>(_data1, _data2, new UInt64[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Add(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Add(
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Add(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = Sse2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AddUInt64();
var result = Sse2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt64> left, Vector128<UInt64> right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
if ((ulong)(left[0] + right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ulong)(left[i] + right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Add)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Threading.Tasks;
using EasyNetQ.Consumer;
using EasyNetQ.FluentConfiguration;
using EasyNetQ.Producer;
namespace EasyNetQ
{
/// <summary>
/// Provides a simple Publish/Subscribe and Request/Response API for a message bus.
/// </summary>
public interface IBus : IDisposable
{
/// <summary>
/// Publishes a message.
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="message">The message to publish</param>
void Publish<T>(T message) where T : class;
/// <summary>
/// Publishes a message.
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="message">The message to publish</param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithTopic("*.brighton").WithPriority(2)
/// </param>
void Publish<T>(T message, Action<IPublishConfiguration> configure) where T : class;
/// <summary>
/// Publishes a message with a topic
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="message">The message to publish</param>
/// <param name="topic">The topic string</param>
void Publish<T>(T message, string topic) where T : class;
/// <summary>
/// Publishes a message.
/// When used with publisher confirms the task completes when the publish is confirmed.
/// Task will throw an exception if the confirm is NACK'd or times out.
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="message">The message to publish</param>
/// <returns></returns>
Task PublishAsync<T>(T message) where T : class;
/// <summary>
/// Publishes a message.
/// When used with publisher confirms the task completes when the publish is confirmed.
/// Task will throw an exception if the confirm is NACK'd or times out.
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="message">The message to publish</param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithTopic("*.brighton").WithPriority(2)
/// </param>
/// <returns></returns>
Task PublishAsync<T>(T message, Action<IPublishConfiguration> configure) where T : class;
/// <summary>
/// Publishes a message with a topic.
/// When used with publisher confirms the task completes when the publish is confirmed.
/// Task will throw an exception if the confirm is NACK'd or times out.
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="message">The message to publish</param>
/// <param name="topic">The topic string</param>
/// <returns></returns>
Task PublishAsync<T>(T message, string topic) where T : class;
/// <summary>
/// Subscribes to a stream of messages that match a .NET type.
/// </summary>
/// <typeparam name="T">The type to subscribe to</typeparam>
/// <param name="subscriptionId">
/// A unique identifier for the subscription. Two subscriptions with the same subscriptionId
/// and type will get messages delivered in turn. This is useful if you want multiple subscribers
/// to load balance a subscription in a round-robin fashion.
/// </param>
/// <param name="onMessage">
/// The action to run when a message arrives. When onMessage completes the message
/// recipt is Ack'd. All onMessage delegates are processed on a single thread so you should
/// avoid long running blocking IO operations. Consider using SubscribeAsync
/// </param>
/// <returns>
/// An <see cref="ISubscriptionResult"/>
/// Call Dispose on it or on its <see cref="ISubscriptionResult.ConsumerCancellation"/> to cancel the subscription.
/// </returns>
ISubscriptionResult Subscribe<T>(string subscriptionId, Action<T> onMessage) where T : class;
/// <summary>
/// Subscribes to a stream of messages that match a .NET type.
/// </summary>
/// <typeparam name="T">The type to subscribe to</typeparam>
/// <param name="subscriptionId">
/// A unique identifier for the subscription. Two subscriptions with the same subscriptionId
/// and type will get messages delivered in turn. This is useful if you want multiple subscribers
/// to load balance a subscription in a round-robin fashion.
/// </param>
/// <param name="onMessage">
/// The action to run when a message arrives. When onMessage completes the message
/// recipt is Ack'd. All onMessage delegates are processed on a single thread so you should
/// avoid long running blocking IO operations. Consider using SubscribeAsync
/// </param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithTopic("uk.london")
/// </param>
/// <returns>
/// An <see cref="ISubscriptionResult"/>
/// Call Dispose on it or on its <see cref="ISubscriptionResult.ConsumerCancellation"/> to cancel the subscription.
/// </returns>
ISubscriptionResult Subscribe<T>(string subscriptionId, Action<T> onMessage, Action<ISubscriptionConfiguration> configure)
where T : class;
/// <summary>
/// Subscribes to a stream of messages that match a .NET type.
/// Allows the subscriber to complete asynchronously.
/// </summary>
/// <typeparam name="T">The type to subscribe to</typeparam>
/// <param name="subscriptionId">
/// A unique identifier for the subscription. Two subscriptions with the same subscriptionId
/// and type will get messages delivered in turn. This is useful if you want multiple subscribers
/// to load balance a subscription in a round-robin fashion.
/// </param>
/// <param name="onMessage">
/// The action to run when a message arrives. onMessage can immediately return a Task and
/// then continue processing asynchronously. When the Task completes the message will be
/// Ack'd.
/// </param>
/// <returns>
/// An <see cref="ISubscriptionResult"/>
/// Call Dispose on it or on its <see cref="ISubscriptionResult.ConsumerCancellation"/> to cancel the subscription.
/// </returns>
ISubscriptionResult SubscribeAsync<T>(string subscriptionId, Func<T, Task> onMessage) where T : class;
/// <summary>
/// Subscribes to a stream of messages that match a .NET type.
/// </summary>
/// <typeparam name="T">The type to subscribe to</typeparam>
/// <param name="subscriptionId">
/// A unique identifier for the subscription. Two subscriptions with the same subscriptionId
/// and type will get messages delivered in turn. This is useful if you want multiple subscribers
/// to load balance a subscription in a round-robin fashion.
/// </param>
/// <param name="onMessage">
/// The action to run when a message arrives. onMessage can immediately return a Task and
/// then continue processing asynchronously. When the Task completes the message will be
/// Ack'd.
/// </param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithTopic("uk.london").WithArgument("x-message-ttl", "60")
/// </param>
/// <returns>
/// An <see cref="ISubscriptionResult"/>
/// Call Dispose on it or on its <see cref="ISubscriptionResult.ConsumerCancellation"/> to cancel the subscription.
/// </returns>
ISubscriptionResult SubscribeAsync<T>(string subscriptionId, Func<T, Task> onMessage, Action<ISubscriptionConfiguration> configure)
where T : class;
/// <summary>
/// Makes an RPC style request
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type.</typeparam>
/// <param name="request">The request message.</param>
/// <returns>The response</returns>
TResponse Request<TRequest, TResponse>(TRequest request)
where TRequest : class
where TResponse : class;
/// <summary>
/// Makes an RPC style request
/// </summary>
/// <typeparam name="TResponse">The response type.</typeparam>
/// <param name="endpoint">endpoint</param>
/// <param name="request">The request message.</param>
/// <param name="timeout">The timeout for this request</param>
/// <returns>The response</returns>
Task<TResponse> RequestAsync<TResponse>(string endpoint, object request, TimeSpan timeout)
where TResponse : class;
/// <summary>
/// Makes an RPC style request
/// </summary>
/// <typeparam name="TResponse">The response type.</typeparam>
/// <param name="endpoint">endpoint</param>
/// <param name="request">The request message.</param>
/// <param name="timeout">The timeout for this request</param>
/// <param name="topic">optional topic</param>
/// <returns>The response</returns>
Task<TResponse> RequestAsync<TResponse>(string endpoint, object request, TimeSpan timeout, string topic)
where TResponse : class;
/// <summary>
/// Makes an RPC style request.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type.</typeparam>
/// <param name="request">The request message.</param>
/// <returns>A task that completes when the response returns</returns>
Task<TResponse> RequestAsync<TRequest, TResponse>(TRequest request)
where TRequest : class
where TResponse : class;
/// <summary>
/// Responds to an RPC request.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type.</typeparam>
/// <param name="responder">
/// A function to run when the request is received. It should return the response.
/// </param>
IDisposable Respond<TRequest, TResponse>(Func<TRequest, TResponse> responder)
where TRequest : class
where TResponse : class;
/// <summary>
/// Responds to an RPC request.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type.</typeparam>
/// <param name="endpoint">endpoint</param>
/// <param name="responder">
/// A function to run when the request is received. It should return the response.
/// </param>
/// <param name="configure">
/// A function for responder configuration
/// </param>
IDisposable Respond<TRequest, TResponse>(string endpoint, Func<TRequest, TResponse> responder, Action<IResponderConfiguration> configure)
where TRequest : class
where TResponse : class;
/// <summary>
/// Responds to an RPC request.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type.</typeparam>
/// <param name="responder">
/// A function to run when the request is received. It should return the response.
/// </param>
/// <param name="configure">
/// A function for responder configuration
/// </param>
IDisposable Respond<TRequest, TResponse>(Func<TRequest, TResponse> responder, Action<IResponderConfiguration> configure)
where TRequest : class
where TResponse : class;
/// <summary>
/// Responds to an RPC request asynchronously.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type</typeparam>
/// <param name="responder">
/// A function to run when the request is received.
/// </param>
IDisposable RespondAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder)
where TRequest : class
where TResponse : class;
/// <summary>
/// Responds to an RPC request asynchronously.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type</typeparam>
/// <param name="responder">
/// A function to run when the request is received.
/// </param>
/// <param name="configure">
/// A function for responder configuration
/// </param>
IDisposable RespondAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder, Action<IResponderConfiguration> configure)
where TRequest : class
where TResponse : class;
/// <summary>
/// Responds to an RPC request asynchronously.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type</typeparam>
/// <param name="endpoint">endpoint</param>
/// <param name="responder">
/// A function to run when the request is received.
/// </param>
IDisposable RespondAsync<TRequest, TResponse>(string endpoint, Func<TRequest, Task<TResponse>> responder)
where TRequest : class
where TResponse : class;
/// <summary>
/// Responds to an RPC request asynchronously.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type</typeparam>
/// <param name="endpoint">endpoint</param>
/// <param name="responder">
/// A function to run when the request is received.
/// </param>
/// <param name="subscriptionId">optional subscriptionId</param>
IDisposable RespondAsync<TRequest, TResponse>(string endpoint, Func<TRequest, Task<TResponse>> responder, string subscriptionId)
where TRequest : class
where TResponse : class;
/// <summary>
/// Responds to an RPC request asynchronously.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type</typeparam>
/// <param name="endpoint">endpoint</param>
/// <param name="responder">
/// A function to run when the request is received.
/// </param>
/// <param name="subscriptionId">optional subscriptionId</param>
/// <param name="configure"></param>
IDisposable RespondAsync<TRequest, TResponse>(string endpoint, Func<TRequest, Task<TResponse>> responder, string subscriptionId, Action<ISubscriptionConfiguration> configure)
where TRequest : class
where TResponse : class;
/// <summary>
/// Send a message directly to a queue
/// </summary>
/// <typeparam name="T">The type of message to send</typeparam>
/// <param name="queue">The queue to send to</param>
/// <param name="message">The message</param>
void Send<T>(string queue, T message) where T : class;
/// <summary>
/// Send a message directly to a queue
/// </summary>
/// <typeparam name="T">The type of message to send</typeparam>
/// <param name="queue">The queue to send to</param>
/// <param name="message">The message</param>
Task SendAsync<T>(string queue, T message) where T : class;
/// <summary>
/// Receive messages from a queue.
/// Multiple calls to Receive for the same queue, but with different message types
/// will add multiple message handlers to the same consumer.
/// </summary>
/// <typeparam name="T">The type of message to receive</typeparam>
/// <param name="queue">The queue to receive from</param>
/// <param name="onMessage">The message handler</param>
IDisposable Receive<T>(string queue, Action<T> onMessage) where T : class;
/// <summary>
/// Receive messages from a queue.
/// Multiple calls to Receive for the same queue, but with different message types
/// will add multiple message handlers to the same consumer.
/// </summary>
/// <typeparam name="T">The type of message to receive</typeparam>
/// <param name="queue">The queue to receive from</param>
/// <param name="onMessage">The message handler</param>
/// <param name="configure">Action to configure consumer with</param>
IDisposable Receive<T>(string queue, Action<T> onMessage, Action<IConsumerConfiguration> configure) where T : class;
/// <summary>
/// Receive messages from a queue.
/// Multiple calls to Receive for the same queue, but with different message types
/// will add multiple message handlers to the same consumer.
/// </summary>
/// <typeparam name="T">The type of message to receive</typeparam>
/// <param name="queue">The queue to receive from</param>
/// <param name="onMessage">The asychronous message handler</param>
IDisposable Receive<T>(string queue, Func<T, Task> onMessage) where T : class;
/// <summary>
/// Receive messages from a queue.
/// Multiple calls to Receive for the same queue, but with different message types
/// will add multiple message handlers to the same consumer.
/// </summary>
/// <typeparam name="T">The type of message to receive</typeparam>
/// <param name="queue">The queue to receive from</param>
/// <param name="onMessage">The asychronous message handler</param>
/// <param name="configure">Action to configure consumer with</param>
IDisposable Receive<T>(string queue, Func<T, Task> onMessage, Action<IConsumerConfiguration> configure) where T : class;
/// <summary>
/// Receive a message from the specified queue. Dispatch them to the given handlers
/// </summary>
/// <param name="queue">The queue to take messages from</param>
/// <param name="addHandlers">A function to add handlers</param>
/// <returns>Consumer cancellation. Call Dispose to stop consuming</returns>
IDisposable Receive(string queue, Action<IReceiveRegistration> addHandlers);
/// <summary>
/// Receive a message from the specified queue. Dispatch them to the given handlers
/// </summary>
/// <param name="queue">The queue to take messages from</param>
/// <param name="addHandlers">A function to add handlers</param>
/// <param name="configure">Action to configure consumer with</param>
/// <returns>Consumer cancellation. Call Dispose to stop consuming</returns>
IDisposable Receive(string queue, Action<IReceiveRegistration> addHandlers, Action<IConsumerConfiguration> configure);
/// <summary>
/// True if the bus is connected, False if it is not.
/// </summary>
bool IsConnected { get; }
/// <summary>
/// Return the advanced EasyNetQ advanced API.
/// </summary>
IAdvancedBus Advanced { get; }
}
}
| |
using System;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using gov.va.medora.utils;
using System.IO;
namespace gov.va.medora.mdo
{
public class SiteTable
{
SortedList regions;
SortedList sites;
ArrayList sources;
SortedList states;
SortedList cities;
SortedList visnsByState;
public SiteTable(String filepath)
{
regions = new SortedList();
sites = new SortedList();
sources = new ArrayList();
parse(filepath);
}
public SortedList Regions
{
get
{
return regions;
}
}
public SortedList Sites
{
get
{
return sites;
}
}
public ArrayList Sources
{
get
{
return sources;
}
}
public Site getSite(String siteId)
{
return (Site)sites[siteId];
}
public Site[] getSites(string sitelist)
{
string[] sitecodes = StringUtils.split(sitelist, StringUtils.COMMA);
sitecodes = StringUtils.trimArray(sitecodes);
if (sitecodes.Length == 0)
{
return null;
}
Site[] sites = new Site[sitecodes.Length];
for (int i = 0; i < sitecodes.Length; i++)
{
sites[i] = getSite(sitecodes[i]);
}
return sites;
}
public Site[] getSites(SiteId[] siteIds)
{
if (siteIds == null || siteIds.Length == 0)
{
return null;
}
Site[] sites = new Site[siteIds.Length];
for (int i = 0; i < siteIds.Length; i++)
{
sites[i] = getSite(siteIds[i].Id);
}
return sites;
}
public Region getRegion(String regionId)
{
return (Region)regions[Convert.ToInt32(regionId)];
}
public SortedList States
{
get { return states; }
}
public State getState(string abbr)
{
if (states == null)
{
return null;
}
foreach (DictionaryEntry de in states)
{
State s = (State)de.Value;
if (s.Abbr == abbr)
{
return s;
}
}
throw new Exception("No such state: " + abbr);
}
private void parse(String filepath)
{
if (String.IsNullOrEmpty(filepath))
{
throw new ArgumentNullException("No source for site table");
}
Region currentRegion = null;
ArrayList currentSites = null;
Site currentSite = null;
DataSource dataSource = null;
ArrayList currentSources = null;
#if DEBUG
string currentDirStr = Directory.GetCurrentDirectory();
#endif
XmlReader reader = null;
try
{
reader = new XmlTextReader(filepath);
while (reader.Read())
{
switch ((int)reader.NodeType)
{
case (int)XmlNodeType.Element:
String name = reader.Name;
if (name == "VhaVisn")
{
currentRegion = new Region();
currentRegion.Id = Convert.ToInt32(reader.GetAttribute("ID"));
currentRegion.Name = reader.GetAttribute("name");
currentSites = new ArrayList();
}
else if (name == "VhaSite")
{
currentSite = new Site();
currentSite.Id = reader.GetAttribute("ID");
currentSite.Name = reader.GetAttribute("name");
String displayName = reader.GetAttribute("displayname");
if (displayName == null)
{
displayName = currentSite.Name;
}
currentSite.DisplayName = displayName;
currentSite.Moniker = reader.GetAttribute("moniker");
currentSite.RegionId = Convert.ToString(currentRegion.Id);
currentSources = new ArrayList();
currentSites.Add(currentSite);
}
else if (name == "DataSource")
{
dataSource = new DataSource();
KeyValuePair<string, string> kvp =
new KeyValuePair<string, string>(currentSite.Id, currentSite.Name);
dataSource.SiteId = new SiteId(kvp.Key, kvp.Value);
dataSource.Modality = reader.GetAttribute("modality");
dataSource.Protocol = reader.GetAttribute("protocol");
dataSource.Provider = reader.GetAttribute("source");
dataSource.Status = reader.GetAttribute("status");
String sTmp = reader.GetAttribute("port");
if (String.IsNullOrEmpty(sTmp)) // StringUtils.isEmpty(sTmp))
{
if (String.Equals(dataSource.Protocol, "VISTA", StringComparison.CurrentCultureIgnoreCase))
{
dataSource.Port = 9200;
}
else if (String.Equals(dataSource.Protocol, "HL7", StringComparison.CurrentCultureIgnoreCase))
{
dataSource.Port = 5000;
}
}
else
{
dataSource.Port = Convert.ToInt32(sTmp);
}
sTmp = reader.GetAttribute("provider");
if (sTmp != null)
{
dataSource.Provider = sTmp;
}
sTmp = reader.GetAttribute("description");
if (sTmp != null)
{
dataSource.Description = sTmp;
}
sTmp = reader.GetAttribute("vendor");
if (sTmp != null)
{
dataSource.Vendor = sTmp;
}
sTmp = reader.GetAttribute("version");
if (sTmp != null)
{
dataSource.Version = sTmp;
}
sTmp = reader.GetAttribute("context");
if (sTmp != null)
{
dataSource.Context = sTmp;
}
sTmp = reader.GetAttribute("connectionString");
if (!String.IsNullOrEmpty(sTmp))
{
dataSource.ConnectionString = sTmp;
}
sTmp = reader.GetAttribute("test");
if (!String.IsNullOrEmpty(sTmp))
{
dataSource.IsTestSource = true;
}
currentSources.Add(dataSource);
sources.Add(dataSource);
}
break;
case (int)XmlNodeType.EndElement:
name = reader.Name;
if (name == "VhaVisn")
{
currentRegion.Sites = currentSites;
regions.Add(currentRegion.Id, currentRegion);
}
else if (name == "VhaSite")
{
currentSite.Sources = (DataSource[])currentSources.ToArray(typeof(DataSource));
sites.Add(currentSite.Id, currentSite);
}
break;
}
}
}
catch (Exception) { /* do nothing */ }
finally
{
if (reader != null)
{
reader.Close();
}
}
}
public void parseStateCityFile(string filepath)
{
if (String.IsNullOrEmpty(filepath))
{
throw new ArgumentNullException("No source for state/city file");
}
states = new SortedList();
State currentState = null;
SortedList currentCities = null;
City currentCity = null;
ArrayList currentSites = null;
Site currentSite = null;
XmlReader reader = null;
try
{
reader = new XmlTextReader(filepath);
while (reader.Read())
{
switch ((int)reader.NodeType)
{
case (int)XmlNodeType.Element:
String name = reader.Name;
if (name == "state")
{
currentState = new State();
currentState.Name = reader.GetAttribute("name");
currentState.Abbr = reader.GetAttribute("abbr");
currentCities = new SortedList();
}
else if (name == "city")
{
currentCity = new City();
currentCity.Name = reader.GetAttribute("name");
currentCity.State = currentState.Abbr;
currentCities.Add(currentCity.Name, currentCity);
currentSites = new ArrayList();
}
else if (name == "site")
{
currentSite = new Site();
currentSite.Name = reader.GetAttribute("name");
currentSite.City = currentCity.Name;
currentSite.State = currentState.Abbr;
currentSite.Id = reader.GetAttribute("sitecode");
currentSite.SiteType = reader.GetAttribute("type");
currentSites.Add(currentSite);
}
break;
case (int)XmlNodeType.EndElement:
name = reader.Name;
if (name == "state")
{
currentState.Cities = currentCities;
states.Add(currentState.Name, currentState);
}
else if (name == "city")
{
currentCity.Sites = (Site[])currentSites.ToArray(typeof(Site));
}
else if (name == "site")
{
}
break;
}
}
}
catch (Exception) { /* do nothing */ }
finally
{
if (reader != null)
{
reader.Close();
}
}
}
public void parseStateFile(string filepath)
{
if (String.IsNullOrEmpty(filepath))
{
throw new ArgumentNullException("No source for state file");
}
states = new SortedList();
State currentState = null;
SortedList currentSites = null;
Site currentSite = null;
ArrayList currentClinics = null;
Site currentClinic = null;
XmlReader reader = null;
try
{
reader = new XmlTextReader(filepath);
while (reader.Read())
{
switch ((int)reader.NodeType)
{
case (int)XmlNodeType.Element:
String name = reader.Name;
if (name == "state")
{
currentState = new State();
currentState.Name = reader.GetAttribute("name");
currentState.Abbr = reader.GetAttribute("abbr");
currentSites = new SortedList();
}
else if (name == "vamc")
{
currentSite = new Site();
currentSite.Id = reader.GetAttribute("sitecode");
currentSite.Name = reader.GetAttribute("name");
currentSite.City = reader.GetAttribute("city");
currentSite.SystemName = reader.GetAttribute("system");
currentSites.Add(currentSite.Name, currentSite);
currentClinics = new ArrayList();
}
else if (name == "clinic")
{
currentClinic = new Site();
currentClinic.Name = reader.GetAttribute("name");
currentClinic.City = reader.GetAttribute("city");
currentClinic.State = reader.GetAttribute("state");
//if (StringUtils.isEmpty(currentClinic.State))
if (String.IsNullOrEmpty(currentClinic.State))
{
currentClinic.State = currentState.Abbr;
}
currentClinic.ParentSiteId = currentSite.Id;
currentClinics.Add(currentClinic);
}
break;
case (int)XmlNodeType.EndElement:
name = reader.Name;
if (name == "state")
{
currentState.Sites = currentSites;
states.Add(currentState.Name, currentState);
}
else if (name == "vamc")
{
currentSite.ChildSites = (Site[])currentClinics.ToArray(typeof(Site));
}
else if (name == "clinic")
{
}
break;
}
}
}
catch (Exception) { /* do nothing */ }
finally
{
if (reader != null)
{
reader.Close();
}
}
}
public SortedList VisnsByState
{
get{ return visnsByState; }
}
public void parseVisnsByState(string filepath)
{
if (String.IsNullOrEmpty(filepath))
{
throw new ArgumentNullException("No source for state file");
}
visnsByState = new SortedList();
XmlReader reader = null;
try
{
reader = new XmlTextReader(filepath);
while (reader.Read())
{
switch ((int)reader.NodeType)
{
case (int)XmlNodeType.Element:
String name = reader.Name;
if (name == "state")
{
State state = new State();
state.Name = reader.GetAttribute("name");
state.Abbr = reader.GetAttribute("abbr");
string visns = reader.GetAttribute("visns");
state.VisnIds = StringUtils.split(visns, StringUtils.COMMA);
visnsByState.Add(state.Abbr, state);
}
break;
}
}
}
catch (Exception) { /* do nothing */ }
finally
{
if (reader != null)
{
reader.Close();
}
}
}
}
}
| |
using System;
using System.Data;
using System.Collections.Generic;
using Gtk;
using Mono.Unix;
using Hyena.Data.Sqlite;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.MediaEngine;
using Banshee.Gui;
using Banshee.ServiceStack;
using Hyena;
namespace Banshee.Bookmarks
{
public class BookmarksService : IExtensionService, IDisposable
{
private BookmarkUI ui;
public BookmarksService ()
{
}
void IExtensionService.Initialize ()
{
Bookmark.Initialize();
ui = BookmarkUI.Instance;
}
public void Dispose ()
{
if (ui != null)
ui.Dispose();
}
string IService.ServiceName {
get { return "BookmarksService"; }
}
}
public class BookmarkUI
{
private Menu bookmark_menu;
private Menu remove_menu;
private ImageMenuItem bookmark_item;
private ImageMenuItem new_item;
private ImageMenuItem remove_item;
private SeparatorMenuItem separator;
private List<Bookmark> bookmarks = new List<Bookmark>();
private Dictionary<Bookmark, MenuItem> select_items = new Dictionary<Bookmark, MenuItem>();
private Dictionary<Bookmark, MenuItem> remove_items = new Dictionary<Bookmark, MenuItem>();
private Dictionary<MenuItem, Bookmark> bookmark_map = new Dictionary<MenuItem, Bookmark>();
private InterfaceActionService action_service;
private ActionGroup actions;
private uint ui_manager_id;
private static BookmarkUI instance = null;
public static BookmarkUI Instance {
get {
if (instance == null)
instance = new BookmarkUI();
return instance;
}
}
public static bool Instantiated {
get { return instance != null; }
}
private BookmarkUI()
{
action_service = ServiceManager.Get<InterfaceActionService> ("InterfaceActionService");
actions = new ActionGroup("Bookmarks");
actions.Add(new ActionEntry [] {
new ActionEntry("BookmarksAction", null,
Catalog.GetString("_Bookmarks"), null,
null, null),
new ActionEntry("BookmarksAddAction", Stock.Add,
Catalog.GetString("_Add Bookmark"), "<control>D",
Catalog.GetString("Bookmark the Position in the Current Track"),
HandleNewBookmark)
});
action_service.UIManager.InsertActionGroup(actions, 0);
ui_manager_id = action_service.UIManager.AddUiFromResource("BookmarksMenu.xml");
bookmark_item = action_service.UIManager.GetWidget("/MainMenu/ToolsMenu/Bookmarks") as ImageMenuItem;
new_item = action_service.UIManager.GetWidget("/MainMenu/ToolsMenu/Bookmarks/Add") as ImageMenuItem;
bookmark_menu = bookmark_item.Submenu as Menu;
bookmark_item.Selected += HandleMenuShown;
remove_item = new ImageMenuItem(Catalog.GetString("_Remove Bookmark"));
remove_item.Sensitive = false;
remove_item.Image = new Image(Stock.Remove, IconSize.Menu);
remove_item.Submenu = remove_menu = new Menu();
bookmark_menu.Append(remove_item);
LoadBookmarks ();
}
private void HandleMenuShown(object sender, EventArgs args)
{
new_item.Sensitive = (ServiceManager.PlayerEngine.CurrentTrack != null);
}
private void HandleNewBookmark(object sender, EventArgs args)
{
DatabaseTrackInfo track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo;
if (track != null) {
try {
Bookmark bookmark = new Bookmark(track.TrackId, ServiceManager.PlayerEngine.Position);
AddBookmark(bookmark);
} catch (Exception e) {
Log.Warning("Unable to Add New Bookmark", e.ToString(), false);
}
}
}
private void LoadBookmarks ()
{
separator = new SeparatorMenuItem();
foreach (Bookmark bookmark in Bookmark.LoadAll()) {
AddBookmark(bookmark);
}
bookmark_item.ShowAll();
}
public void AddBookmark(Bookmark bookmark)
{
if (select_items.ContainsKey(bookmark))
return;
bookmarks.Add(bookmark);
if (bookmarks.Count == 1) {
bookmark_menu.Append(separator);
remove_item.Sensitive = true;
}
// Add menu item to jump to this bookmark
ImageMenuItem select_item = new ImageMenuItem(bookmark.Name.Replace("_", "__"));
select_item.Image = new Image(Stock.JumpTo, IconSize.Menu);
select_item.Activated += delegate {
Console.WriteLine ("item delegate, main thread? {0}", Banshee.Base.ThreadAssist.InMainThread);
bookmark.JumpTo();
};
bookmark_menu.Append(select_item);
select_items[bookmark] = select_item;
// Add menu item to remove this bookmark
ImageMenuItem rem = new ImageMenuItem(bookmark.Name.Replace("_", "__"));
rem.Image = new Image(Stock.Remove, IconSize.Menu);
rem.Activated += delegate {
bookmark.Remove();
};
remove_menu.Append(rem);
remove_items[bookmark] = rem;
bookmark_map[rem] = bookmark;
bookmark_menu.ShowAll();
}
public void RemoveBookmark(Bookmark bookmark)
{
if (!remove_items.ContainsKey(bookmark))
return;
bookmark_menu.Remove(select_items[bookmark]);
remove_menu.Remove(remove_items[bookmark]);
bookmarks.Remove(bookmark);
select_items.Remove(bookmark);
bookmark_map.Remove(remove_items[bookmark]);
remove_items.Remove(bookmark);
if (bookmarks.Count == 0) {
bookmark_menu.Remove(separator);
remove_item.Sensitive = false;
}
}
public void Dispose()
{
action_service.UIManager.RemoveUi(ui_manager_id);
action_service.UIManager.RemoveActionGroup(actions);
actions = null;
instance = null;
}
}
public class Bookmark
{
private int id;
private int track_id;
private uint position;
private DateTime created_at;
// Translators: This is used to generate bookmark names. {0} is track title, {1} is minutes
// (possibly more than two digits) and {2} is seconds (between 00 and 60).
private readonly string bookmark_format = Catalog.GetString("{0} ({1}:{2:00})");
private string name;
public string Name {
get { return name; }
set { name = value; }
}
public DateTime CreatedAt {
get { return created_at; }
}
public TrackInfo Track {
get { return DatabaseTrackInfo.Provider.FetchSingle(track_id); }
}
private Bookmark(int id, int track_id, uint position, DateTime created_at)
{
this.id = id;
this.track_id = track_id;
this.position = position;
this.created_at = created_at;
uint position_seconds = position/1000;
Name = String.Format(bookmark_format, Track.DisplayTrackTitle, position_seconds/60, position_seconds%60);
}
public Bookmark(int track_id, uint position)
{
Console.WriteLine ("Bookmark, main thread? {0}", Banshee.Base.ThreadAssist.InMainThread);
this.track_id = track_id;
this.position = position;
this.created_at = DateTime.Now;
uint position_seconds = position/1000;
Name = String.Format(bookmark_format, Track.DisplayTrackTitle, position_seconds/60, position_seconds%60);
this.id = ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@"
INSERT INTO Bookmarks
(TrackID, Position, CreatedAt)
VALUES (?, ?, ?)",
track_id, position, DateTimeUtil.FromDateTime(created_at) ));
}
public void JumpTo()
{
DatabaseTrackInfo track = Track as DatabaseTrackInfo;
DatabaseTrackInfo current_track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo;
if (track != null) {
if (current_track == null || current_track.TrackId != track.TrackId) {
ServiceManager.PlayerEngine.ConnectEvent (HandleStateChanged, PlayerEvent.StateChange);
ServiceManager.PlayerEngine.OpenPlay (track);
} else {
if (ServiceManager.PlayerEngine.CanSeek) {
ServiceManager.PlayerEngine.Position = position;
} else {
ServiceManager.PlayerEngine.ConnectEvent (HandleStateChanged, PlayerEvent.StateChange);
ServiceManager.PlayerEngine.Play ();
}
}
} else {
Remove();
}
}
private void HandleStateChanged (PlayerEventArgs args)
{
if (((PlayerEventStateChangeArgs)args).Current == PlayerState.Playing) {
ServiceManager.PlayerEngine.DisconnectEvent (HandleStateChanged);
if (!ServiceManager.PlayerEngine.CurrentTrack.IsLive) {
// Sleep in 5ms increments for at most 250ms waiting for CanSeek to be true
int count = 0;
while (count < 50 && !ServiceManager.PlayerEngine.CanSeek) {
System.Threading.Thread.Sleep (5);
count++;
}
}
if (ServiceManager.PlayerEngine.CanSeek) {
ServiceManager.PlayerEngine.Position = position;
}
}
}
public void Remove()
{
try {
ServiceManager.DbConnection.Execute(String.Format(
"DELETE FROM Bookmarks WHERE BookmarkID = {0}", id
));
if (BookmarkUI.Instantiated)
BookmarkUI.Instance.RemoveBookmark(this);
} catch (Exception e) {
Log.Warning("Error Removing Bookmark", e.ToString(), false);
}
}
public static List<Bookmark> LoadAll()
{
List<Bookmark> bookmarks = new List<Bookmark>();
IDataReader reader = ServiceManager.DbConnection.Query(
"SELECT BookmarkID, TrackID, Position, CreatedAt FROM Bookmarks"
);
while (reader.Read()) {
try {
bookmarks.Add(new Bookmark(
reader.GetInt32 (0), reader.GetInt32 (1), Convert.ToUInt32 (reader[2]),
DateTimeUtil.ToDateTime(Convert.ToInt64(reader[3]))
));
} catch (Exception e) {
ServiceManager.DbConnection.Execute(String.Format(
"DELETE FROM Bookmarks WHERE BookmarkID = {0}", reader.GetInt32 (0)
));
Log.Warning("Error Loading Bookmark", e.ToString(), false);
}
}
reader.Dispose();
return bookmarks;
}
public static void Initialize()
{
if (!ServiceManager.DbConnection.TableExists("Bookmarks")) {
ServiceManager.DbConnection.Execute(@"
CREATE TABLE Bookmarks (
BookmarkID INTEGER PRIMARY KEY,
TrackID INTEGER NOT NULL,
Position INTEGER NOT NULL,
CreatedAt INTEGER NOT NULL
)
");
}
}
}
}
| |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// 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.
namespace Castle.DynamicProxy.Generators
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
#if FEATURE_SERIALIZATION
using System.Runtime.Serialization;
using System.Xml.Serialization;
#endif
using Castle.Core.Internal;
using Castle.Core.Logging;
using Castle.DynamicProxy.Contributors;
using Castle.DynamicProxy.Generators.Emitters;
using Castle.DynamicProxy.Generators.Emitters.CodeBuilders;
using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using Castle.DynamicProxy.Internal;
#if SILVERLIGHT
using Castle.DynamicProxy.SilverlightExtensions;
#endif
/// <summary>
/// Base class that exposes the common functionalities
/// to proxy generation.
/// </summary>
public abstract class BaseProxyGenerator
{
protected readonly Type targetType;
private readonly ModuleScope scope;
private ILogger logger = NullLogger.Instance;
private ProxyGenerationOptions proxyGenerationOptions;
protected BaseProxyGenerator(ModuleScope scope, Type targetType)
{
this.scope = scope;
this.targetType = targetType;
}
public ILogger Logger
{
get { return logger; }
set { logger = value; }
}
protected ProxyGenerationOptions ProxyGenerationOptions
{
get
{
if (proxyGenerationOptions == null)
{
throw new InvalidOperationException("ProxyGenerationOptions must be set before being retrieved.");
}
return proxyGenerationOptions;
}
set
{
if (proxyGenerationOptions != null)
{
throw new InvalidOperationException("ProxyGenerationOptions can only be set once.");
}
proxyGenerationOptions = value;
}
}
protected ModuleScope Scope
{
get { return scope; }
}
protected void AddMapping(Type @interface, ITypeContributor implementer, IDictionary<Type, ITypeContributor> mapping)
{
Debug.Assert(implementer != null, "implementer != null");
Debug.Assert(@interface != null, "@interface != null");
Debug.Assert(@interface.GetTypeInfo().IsInterface, "@interface.IsInterface");
if (!mapping.ContainsKey(@interface))
{
AddMappingNoCheck(@interface, implementer, mapping);
}
}
#if FEATURE_SERIALIZATION
protected void AddMappingForISerializable(IDictionary<Type, ITypeContributor> typeImplementerMapping,
ITypeContributor instance)
{
AddMapping(typeof(ISerializable), instance, typeImplementerMapping);
}
#endif
/// <summary>
/// It is safe to add mapping (no mapping for the interface exists)
/// </summary>
/// <param name = "implementer"></param>
/// <param name = "interface"></param>
/// <param name = "mapping"></param>
protected void AddMappingNoCheck(Type @interface, ITypeContributor implementer,
IDictionary<Type, ITypeContributor> mapping)
{
mapping.Add(@interface, implementer);
}
protected void AddToCache(CacheKey key, Type type)
{
scope.RegisterInCache(key, type);
}
protected virtual ClassEmitter BuildClassEmitter(string typeName, Type parentType, IEnumerable<Type> interfaces)
{
CheckNotGenericTypeDefinition(parentType, "parentType");
CheckNotGenericTypeDefinitions(interfaces, "interfaces");
return new ClassEmitter(Scope, typeName, parentType, interfaces);
}
protected void CheckNotGenericTypeDefinition(Type type, string argumentName)
{
if (type != null && type.GetTypeInfo().IsGenericTypeDefinition)
{
throw new ArgumentException("Type cannot be a generic type definition. Type: " + type.FullName, argumentName);
}
}
protected void CheckNotGenericTypeDefinitions(IEnumerable<Type> types, string argumentName)
{
if (types == null)
{
return;
}
foreach (var t in types)
{
CheckNotGenericTypeDefinition(t, argumentName);
}
}
protected void CompleteInitCacheMethod(ConstructorCodeBuilder constCodeBuilder)
{
constCodeBuilder.AddStatement(new ReturnStatement());
}
protected virtual void CreateFields(ClassEmitter emitter)
{
CreateOptionsField(emitter);
CreateSelectorField(emitter);
CreateInterceptorsField(emitter);
}
protected void CreateInterceptorsField(ClassEmitter emitter)
{
var interceptorsField = emitter.CreateField("__interceptors", typeof(IInterceptor[]));
#if FEATURE_SERIALIZATION
emitter.DefineCustomAttributeFor<XmlIgnoreAttribute>(interceptorsField);
#endif
}
protected FieldReference CreateOptionsField(ClassEmitter emitter)
{
return emitter.CreateStaticField("proxyGenerationOptions", typeof(ProxyGenerationOptions));
}
protected void CreateSelectorField(ClassEmitter emitter)
{
if (ProxyGenerationOptions.Selector == null)
{
return;
}
emitter.CreateField("__selector", typeof(IInterceptorSelector));
}
protected virtual void CreateTypeAttributes(ClassEmitter emitter)
{
emitter.AddCustomAttributes(ProxyGenerationOptions);
#if FEATURE_SERIALIZATION
emitter.DefineCustomAttribute<XmlIncludeAttribute>(new object[] { targetType });
#endif
}
protected void EnsureOptionsOverrideEqualsAndGetHashCode(ProxyGenerationOptions options)
{
if (Logger.IsWarnEnabled)
{
// Check the proxy generation hook
if (!OverridesEqualsAndGetHashCode(options.Hook.GetType()))
{
Logger.WarnFormat("The IProxyGenerationHook type {0} does not override both Equals and GetHashCode. " +
"If these are not correctly overridden caching will fail to work causing performance problems.",
options.Hook.GetType().FullName);
}
// Interceptor selectors no longer need to override Equals and GetHashCode
}
}
protected void GenerateConstructor(ClassEmitter emitter, ConstructorInfo baseConstructor,
params FieldReference[] fields)
{
ArgumentReference[] args;
ParameterInfo[] baseConstructorParams = null;
if (baseConstructor != null)
{
baseConstructorParams = baseConstructor.GetParameters();
}
if (baseConstructorParams != null && baseConstructorParams.Length != 0)
{
args = new ArgumentReference[fields.Length + baseConstructorParams.Length];
var offset = fields.Length;
for (var i = offset; i < offset + baseConstructorParams.Length; i++)
{
var paramInfo = baseConstructorParams[i - offset];
args[i] = new ArgumentReference(paramInfo.ParameterType);
}
}
else
{
args = new ArgumentReference[fields.Length];
}
for (var i = 0; i < fields.Length; i++)
{
args[i] = new ArgumentReference(fields[i].Reference.FieldType);
}
var constructor = emitter.CreateConstructor(args);
if (baseConstructorParams != null && baseConstructorParams.Length != 0)
{
var last = baseConstructorParams.Last();
if (last.ParameterType.GetTypeInfo().IsArray && last.HasAttribute<ParamArrayAttribute>())
{
var parameter = constructor.ConstructorBuilder.DefineParameter(args.Length, ParameterAttributes.None, last.Name);
var builder = AttributeUtil.CreateBuilder<ParamArrayAttribute>();
parameter.SetCustomAttribute(builder);
}
}
for (var i = 0; i < fields.Length; i++)
{
constructor.CodeBuilder.AddStatement(new AssignStatement(fields[i], args[i].ToExpression()));
}
// Invoke base constructor
if (baseConstructor != null)
{
Debug.Assert(baseConstructorParams != null);
var slice = new ArgumentReference[baseConstructorParams.Length];
Array.Copy(args, fields.Length, slice, 0, baseConstructorParams.Length);
constructor.CodeBuilder.InvokeBaseConstructor(baseConstructor, slice);
}
else
{
constructor.CodeBuilder.InvokeBaseConstructor();
}
constructor.CodeBuilder.AddStatement(new ReturnStatement());
}
protected void GenerateConstructors(ClassEmitter emitter, Type baseType, params FieldReference[] fields)
{
var constructors =
baseType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var constructor in constructors)
{
if (!IsConstructorVisible(constructor))
{
continue;
}
GenerateConstructor(emitter, constructor, fields);
}
}
/// <summary>
/// Generates a parameters constructor that initializes the proxy
/// state with <see cref = "StandardInterceptor" /> just to make it non-null.
/// <para>
/// This constructor is important to allow proxies to be XML serializable
/// </para>
/// </summary>
protected void GenerateParameterlessConstructor(ClassEmitter emitter, Type baseClass, FieldReference interceptorField)
{
// Check if the type actually has a default constructor
var defaultConstructor = baseClass.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes,
null);
if (defaultConstructor == null)
{
defaultConstructor = baseClass.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes,
null);
if (defaultConstructor == null || defaultConstructor.IsPrivate)
{
return;
}
}
var constructor = emitter.CreateConstructor();
// initialize fields with an empty interceptor
constructor.CodeBuilder.AddStatement(new AssignStatement(interceptorField,
new NewArrayExpression(1, typeof(IInterceptor))));
constructor.CodeBuilder.AddStatement(
new AssignArrayStatement(interceptorField, 0, new NewInstanceExpression(typeof(StandardInterceptor), new Type[0])));
// Invoke base constructor
constructor.CodeBuilder.InvokeBaseConstructor(defaultConstructor);
constructor.CodeBuilder.AddStatement(new ReturnStatement());
}
protected ConstructorEmitter GenerateStaticConstructor(ClassEmitter emitter)
{
return emitter.CreateTypeConstructor();
}
protected Type GetFromCache(CacheKey key)
{
return scope.GetFromCache(key);
}
protected void HandleExplicitlyPassedProxyTargetAccessor(ICollection<Type> targetInterfaces,
ICollection<Type> additionalInterfaces)
{
var interfaceName = typeof(IProxyTargetAccessor).ToString();
//ok, let's determine who tried to sneak the IProxyTargetAccessor in...
string message;
if (targetInterfaces.Contains(typeof(IProxyTargetAccessor)))
{
message =
string.Format(
"Target type for the proxy implements {0} which is a DynamicProxy infrastructure interface and you should never implement it yourself. Are you trying to proxy an existing proxy?",
interfaceName);
}
else if (ProxyGenerationOptions.MixinData.ContainsMixin(typeof(IProxyTargetAccessor)))
{
var mixinType = ProxyGenerationOptions.MixinData.GetMixinInstance(typeof(IProxyTargetAccessor)).GetType();
message =
string.Format(
"Mixin type {0} implements {1} which is a DynamicProxy infrastructure interface and you should never implement it yourself. Are you trying to mix in an existing proxy?",
mixinType.Name, interfaceName);
}
else if (additionalInterfaces.Contains(typeof(IProxyTargetAccessor)))
{
message =
string.Format(
"You passed {0} as one of additional interfaces to proxy which is a DynamicProxy infrastructure interface and is implemented by every proxy anyway. Please remove it from the list of additional interfaces to proxy.",
interfaceName);
}
else
{
// this can technicaly never happen
message = string.Format("It looks like we have a bug with regards to how we handle {0}. Please report it.",
interfaceName);
}
throw new ProxyGenerationException("This is a DynamicProxy2 error: " + message);
}
protected void InitializeStaticFields(Type builtType)
{
builtType.SetStaticField("proxyGenerationOptions", BindingFlags.Public, ProxyGenerationOptions);
}
protected Type ObtainProxyType(CacheKey cacheKey, Func<string, INamingScope, Type> factory)
{
Type cacheType;
using (var locker = Scope.Lock.ForReading())
{
cacheType = GetFromCache(cacheKey);
if (cacheType != null)
{
Logger.DebugFormat("Found cached proxy type {0} for target type {1}.", cacheType.FullName, targetType.FullName);
return cacheType;
}
}
// This is to avoid generating duplicate types under heavy multithreaded load.
using (var locker = Scope.Lock.ForReadingUpgradeable())
{
// Only one thread at a time may enter an upgradable read lock.
// See if an earlier lock holder populated the cache.
cacheType = GetFromCache(cacheKey);
if (cacheType != null)
{
Logger.DebugFormat("Found cached proxy type {0} for target type {1}.", cacheType.FullName, targetType.FullName);
return cacheType;
}
// Log details about the cache miss
Logger.DebugFormat("No cached proxy type was found for target type {0}.", targetType.FullName);
EnsureOptionsOverrideEqualsAndGetHashCode(ProxyGenerationOptions);
var name = Scope.NamingScope.GetUniqueName("Castle.Proxies." + targetType.Name + "Proxy");
var proxyType = factory.Invoke(name, Scope.NamingScope.SafeSubScope());
// Upgrade the lock to a write lock.
locker.Upgrade();
AddToCache(cacheKey, proxyType);
return proxyType;
}
}
private bool IsConstructorVisible(ConstructorInfo constructor)
{
return constructor.IsPublic
|| constructor.IsFamily
|| constructor.IsFamilyOrAssembly
#if !SILVERLIGHT
|| (constructor.IsAssembly && InternalsUtil.IsInternalToDynamicProxy(constructor.DeclaringType.Assembly));
#else
;
#endif
}
private bool OverridesEqualsAndGetHashCode(Type type)
{
var equalsMethod = type.GetMethod("Equals", BindingFlags.Public | BindingFlags.Instance);
if (equalsMethod == null || equalsMethod.DeclaringType == typeof(object) || equalsMethod.IsAbstract)
{
return false;
}
var getHashCodeMethod = type.GetMethod("GetHashCode", BindingFlags.Public | BindingFlags.Instance);
if (getHashCodeMethod == null || getHashCodeMethod.DeclaringType == typeof(object) || getHashCodeMethod.IsAbstract)
{
return false;
}
return true;
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Cassandra.SessionManagement;
using Cassandra.IntegrationTests.Policies.Util;
using Cassandra.IntegrationTests.SimulacronAPI;
using Cassandra.IntegrationTests.TestBase;
using Cassandra.IntegrationTests.TestClusterManagement;
using Cassandra.IntegrationTests.TestClusterManagement.Simulacron;
using NUnit.Framework;
using Cassandra.Tests;
namespace Cassandra.IntegrationTests.Core
{
[TestFixture, Category(TestCategory.Short)]
public class PoolShortTests : TestGlobals
{
[TearDown]
public void OnTearDown()
{
TestClusterManager.TryRemove();
}
[Test, TestTimeout(1000 * 60 * 4), TestCase(false), TestCase(true)]
public void StopForce_With_Inflight_Requests(bool useStreamMode)
{
using (var testCluster = SimulacronCluster.CreateNew(2))
{
const int connectionLength = 4;
var builder = ClusterBuilder()
.AddContactPoint(testCluster.InitialContactPoint)
.WithPoolingOptions(new PoolingOptions()
.SetCoreConnectionsPerHost(HostDistance.Local, connectionLength)
.SetMaxConnectionsPerHost(HostDistance.Local, connectionLength)
.SetHeartBeatInterval(0))
.WithRetryPolicy(AlwaysIgnoreRetryPolicy.Instance)
.WithSocketOptions(new SocketOptions().SetReadTimeoutMillis(0).SetStreamMode(useStreamMode))
.WithLoadBalancingPolicy(new RoundRobinPolicy());
using (var cluster = builder.Build())
{
var session = (IInternalSession)cluster.Connect();
testCluster.PrimeFluent(
b => b.WhenQuery("SELECT * FROM ks1.table1 WHERE id1 = ?, id2 = ?")
.ThenRowsSuccess(new[] { ("id1", DataType.Int), ("id2", DataType.Int) }, rows => rows.WithRow(2, 3)).WithIgnoreOnPrepare(true));
var ps = session.Prepare("SELECT * FROM ks1.table1 WHERE id1 = ?, id2 = ?");
var t = ExecuteMultiple(testCluster, session, ps, false, 1, 100);
t.Wait();
Assert.AreEqual(2, t.Result.Length, "The 2 hosts must have been used");
// Wait for all connections to be opened
Thread.Sleep(1000);
var hosts = cluster.AllHosts().ToArray();
TestHelper.WaitUntil(() =>
hosts.Sum(h => session
.GetOrCreateConnectionPool(h, HostDistance.Local)
.OpenConnections
) == hosts.Length * connectionLength);
Assert.AreEqual(
hosts.Length * connectionLength,
hosts.Sum(h => session.GetOrCreateConnectionPool(h, HostDistance.Local).OpenConnections));
ExecuteMultiple(testCluster, session, ps, true, 8000, 200000).Wait();
}
}
}
private Task<string[]> ExecuteMultiple(SimulacronCluster testCluster, IInternalSession session, PreparedStatement ps, bool stopNode, int maxConcurrency, int repeatLength)
{
var hosts = new ConcurrentDictionary<string, bool>();
var tcs = new TaskCompletionSource<string[]>();
var receivedCounter = 0L;
var sendCounter = 0L;
var currentlySentCounter = 0L;
var stopMark = repeatLength / 8L;
Action sendNew = null;
sendNew = () =>
{
var sent = Interlocked.Increment(ref sendCounter);
if (sent > repeatLength)
{
return;
}
Interlocked.Increment(ref currentlySentCounter);
var statement = ps.Bind(DateTime.Now.Millisecond, (int)sent);
var executeTask = session.ExecuteAsync(statement);
executeTask.ContinueWith(t =>
{
if (t.Exception != null)
{
tcs.TrySetException(t.Exception.InnerException);
return;
}
hosts.AddOrUpdate(t.Result.Info.QueriedHost.ToString(), true, (k, v) => v);
var received = Interlocked.Increment(ref receivedCounter);
if (stopNode && received == stopMark)
{
Task.Factory.StartNew(() =>
{
testCluster.GetNodes().Skip(1).First().Stop();
}, TaskCreationOptions.LongRunning);
}
if (received == repeatLength)
{
// Mark this as finished
tcs.TrySetResult(hosts.Keys.ToArray());
return;
}
sendNew();
}, TaskContinuationOptions.ExecuteSynchronously);
};
for (var i = 0; i < maxConcurrency; i++)
{
sendNew();
}
return tcs.Task;
}
[Test]
public async Task MarkHostDown_PartialPoolConnection()
{
using (var sCluster = SimulacronCluster.CreateNew(new SimulacronOptions()))
{
const int connectionLength = 4;
var builder = ClusterBuilder()
.AddContactPoint(sCluster.InitialContactPoint)
.WithPoolingOptions(new PoolingOptions()
.SetCoreConnectionsPerHost(HostDistance.Local, connectionLength)
.SetMaxConnectionsPerHost(HostDistance.Local, connectionLength)
.SetHeartBeatInterval(2000))
.WithReconnectionPolicy(new ConstantReconnectionPolicy(long.MaxValue));
using (var cluster = builder.Build())
{
var session = (IInternalSession)cluster.Connect();
var allHosts = cluster.AllHosts();
TestHelper.WaitUntil(() =>
allHosts.Sum(h => session
.GetOrCreateConnectionPool(h, HostDistance.Local)
.OpenConnections
) == allHosts.Count * connectionLength);
var h1 = allHosts.FirstOrDefault();
var pool = session.GetOrCreateConnectionPool(h1, HostDistance.Local);
var ports = await sCluster.GetConnectedPortsAsync().ConfigureAwait(false);
// 4 pool connections + the control connection
await TestHelper.RetryAssertAsync(async () =>
{
ports = await sCluster.GetConnectedPortsAsync().ConfigureAwait(false);
Assert.AreEqual(5, ports.Count);
}, 100, 200).ConfigureAwait(false);
sCluster.DisableConnectionListener().Wait();
// Remove the first connections
for (var i = 0; i < 3; i++)
{
// Closure
var index = i;
var expectedOpenConnections = 5 - index;
await TestHelper.RetryAssertAsync(async () =>
{
ports = await sCluster.GetConnectedPortsAsync().ConfigureAwait(false);
Assert.AreEqual(expectedOpenConnections, ports.Count, "Cassandra simulator contains unexpected number of connected clients");
}, 100, 200).ConfigureAwait(false);
sCluster.DropConnection(ports.Last().Address.ToString(), ports.Last().Port).Wait();
// Host pool could have between pool.OpenConnections - i and pool.OpenConnections - i - 1
TestHelper.WaitUntil(() => pool.OpenConnections >= 4 - index - 1 && pool.OpenConnections <= 4 - index);
Assert.LessOrEqual(pool.OpenConnections, 4 - index);
Assert.GreaterOrEqual(pool.OpenConnections, 4 - index - 1);
Assert.IsTrue(h1.IsUp);
}
await TestHelper.RetryAssertAsync(async () =>
{
ports = await sCluster.GetConnectedPortsAsync().ConfigureAwait(false);
Assert.AreEqual(2, ports.Count);
}, 100, 200).ConfigureAwait(false);
sCluster.DropConnection(ports.Last().Address.ToString(), ports.Last().Port).Wait();
sCluster.DropConnection(ports.First().Address.ToString(), ports.First().Port).Wait();
TestHelper.WaitUntil(() => pool.OpenConnections == 0 && !h1.IsUp);
Assert.IsFalse(h1.IsUp);
}
}
}
/// <summary>
/// Tests that if no host is available at Cluster.Init(), it will initialize next time it is invoked
/// </summary>
[Test]
public void Cluster_Initialization_Recovers_From_NoHostAvailableException()
{
using (var testCluster = SimulacronCluster.CreateNew(1))
{
var nodes = testCluster.GetNodes().ToList();
nodes[0].Stop().GetAwaiter().GetResult();
using (var cluster = ClusterBuilder()
.AddContactPoint(testCluster.InitialContactPoint)
.Build())
{
//initially it will throw as there is no node reachable
Assert.Throws<NoHostAvailableException>(() => cluster.Connect());
// wait for the node to be up
nodes[0].Start().GetAwaiter().GetResult();
TestUtils.WaitForUp(testCluster.InitialContactPoint.Address.ToString(), 9042, 5);
// Now the node is ready to accept connections
var session = cluster.Connect("system");
TestHelper.ParallelInvoke(() => session.Execute("SELECT * from local"), 20);
}
}
}
[Test, Category(TestCategory.RealCluster)]
public void Connect_With_Ssl_Test()
{
try
{
//use ssl
var testCluster = TestClusterManager.CreateNew(1, new TestClusterOptions { UseSsl = true });
using (var cluster = ClusterBuilder()
.AddContactPoint(testCluster.InitialContactPoint)
.WithSSL(new SSLOptions().SetRemoteCertValidationCallback((a, b, c, d) => true))
.Build())
{
Assert.DoesNotThrow(() =>
{
var session = cluster.Connect();
TestHelper.Invoke(() => session.Execute("select * from system.local"), 10);
});
}
}
finally
{
TestClusterManager.TryRemove();
}
}
[Test]
[TestCase(ProtocolVersion.MaxSupported, 1)]
[TestCase(ProtocolVersion.V2, 2)]
public async Task PoolingOptions_Create_Based_On_Protocol(ProtocolVersion protocolVersion, int coreConnectionLength)
{
var options1 = PoolingOptions.Create(protocolVersion);
using (var sCluster = SimulacronCluster.CreateNew(new SimulacronOptions()))
using (var cluster = ClusterBuilder()
.AddContactPoint(sCluster.InitialContactPoint)
.WithPoolingOptions(options1)
.Build())
{
var session = (IInternalSession)cluster.Connect();
var allHosts = cluster.AllHosts();
var host = allHosts.First();
var pool = session.GetOrCreateConnectionPool(host, HostDistance.Local);
TestHelper.WaitUntil(() =>
pool.OpenConnections == coreConnectionLength);
var ports = await sCluster.GetConnectedPortsAsync().ConfigureAwait(false);
await TestHelper.RetryAssertAsync(async () =>
{
ports = await sCluster.GetConnectedPortsAsync().ConfigureAwait(false);
//coreConnectionLength + 1 (the control connection)
Assert.AreEqual(coreConnectionLength + 1, ports.Count);
}, 100, 200).ConfigureAwait(false);
}
}
[Test]
public async Task Should_Create_Core_Connections_To_Hosts_In_Local_Dc_When_Warmup_Is_Enabled()
{
const int nodeLength = 4;
var poolingOptions = PoolingOptions.Create().SetCoreConnectionsPerHost(HostDistance.Local, 5);
// Use multiple DCs: 4 nodes in first DC and 3 nodes in second DC
using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = $"{nodeLength},3" }))
using (var cluster = ClusterBuilder()
.AddContactPoint(testCluster.InitialContactPoint)
.WithPoolingOptions(poolingOptions).Build())
{
var session = await cluster.ConnectAsync().ConfigureAwait(false);
var state = session.GetState();
var hosts = state.GetConnectedHosts();
Assert.AreEqual(nodeLength, hosts.Count);
foreach (var host in hosts)
{
Assert.AreEqual(poolingOptions.GetCoreConnectionsPerHost(HostDistance.Local),
state.GetOpenConnections(host));
}
}
}
[Test]
public async Task ControlConnection_Should_Reconnect_To_Up_Host()
{
const int connectionLength = 1;
var builder = ClusterBuilder()
.WithPoolingOptions(new PoolingOptions()
.SetCoreConnectionsPerHost(HostDistance.Local, connectionLength)
.SetMaxConnectionsPerHost(HostDistance.Local, connectionLength)
.SetHeartBeatInterval(1000))
.WithReconnectionPolicy(new ConstantReconnectionPolicy(100));
using (var testCluster = SimulacronCluster.CreateNew(3))
using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
{
var session = (Session)cluster.Connect();
var allHosts = cluster.AllHosts();
Assert.AreEqual(3, allHosts.Count);
await TestHelper.TimesLimit(() =>
session.ExecuteAsync(new SimpleStatement("SELECT * FROM system.local")), 100, 16).ConfigureAwait(false);
// 1 per hosts + control connection
await TestHelper.RetryAssertAsync(async () =>
{
Assert.AreEqual(4, (await testCluster.GetConnectedPortsAsync().ConfigureAwait(false)).Count);
}, 100, 200).ConfigureAwait(false);
var ccAddress = cluster.InternalRef.GetControlConnection().EndPoint.GetHostIpEndPointWithFallback();
Assert.NotNull(ccAddress);
var simulacronNode = testCluster.GetNode(ccAddress);
// Disable new connections to the first host
await simulacronNode.Stop().ConfigureAwait(false);
TestHelper.WaitUntil(() => !cluster.GetHost(ccAddress).IsUp);
Assert.False(cluster.GetHost(ccAddress).IsUp);
TestHelper.WaitUntil(() => !cluster.InternalRef.GetControlConnection().EndPoint.GetHostIpEndPointWithFallback().Address.Equals(ccAddress.Address));
Assert.NotNull(cluster.InternalRef.GetControlConnection().EndPoint.GetHostIpEndPointWithFallback());
Assert.AreNotEqual(ccAddress.Address, cluster.InternalRef.GetControlConnection().EndPoint.GetHostIpEndPointWithFallback().Address);
// Previous host is still DOWN
Assert.False(cluster.GetHost(ccAddress).IsUp);
// New host is UP
ccAddress = cluster.InternalRef.GetControlConnection().EndPoint.GetHostIpEndPointWithFallback();
Assert.True(cluster.GetHost(ccAddress).IsUp);
}
}
[Test]
public async Task ControlConnection_Should_Reconnect_After_Failed_Attemps()
{
const int connectionLength = 1;
var builder = ClusterBuilder()
.WithPoolingOptions(new PoolingOptions()
.SetCoreConnectionsPerHost(HostDistance.Local, connectionLength)
.SetMaxConnectionsPerHost(HostDistance.Local, connectionLength)
.SetHeartBeatInterval(1000))
.WithReconnectionPolicy(new ConstantReconnectionPolicy(100L));
using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3" }))
using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
{
var session = (Session)cluster.Connect();
var allHosts = cluster.AllHosts();
Assert.AreEqual(3, allHosts.Count);
await TestHelper.TimesLimit(() =>
session.ExecuteAsync(new SimpleStatement("SELECT * FROM system.local")), 100, 16).ConfigureAwait(false);
var serverConnections = await testCluster.GetConnectedPortsAsync().ConfigureAwait(false);
// 1 per hosts + control connection
await TestHelper.RetryAssertAsync(async () =>
{
serverConnections = await testCluster.GetConnectedPortsAsync().ConfigureAwait(false);
//coreConnectionLength + 1 (the control connection)
Assert.AreEqual(4, serverConnections.Count);
}, 100, 10).ConfigureAwait(false);
// Disable all connections
await testCluster.DisableConnectionListener().ConfigureAwait(false);
var ccAddress = cluster.InternalRef.GetControlConnection().EndPoint.GetHostIpEndPointWithFallback();
// Drop all connections to hosts
foreach (var connection in serverConnections)
{
await testCluster.DropConnection(connection).ConfigureAwait(false);
}
TestHelper.WaitUntil(() => !cluster.GetHost(ccAddress).IsUp);
// All host should be down by now
TestHelper.WaitUntil(() => cluster.AllHosts().All(h => !h.IsUp));
Assert.False(cluster.GetHost(ccAddress).IsUp);
// Allow new connections to be created
await testCluster.EnableConnectionListener().ConfigureAwait(false);
TestHelper.WaitUntil(() => cluster.AllHosts().All(h => h.IsUp));
ccAddress = cluster.InternalRef.GetControlConnection().EndPoint.GetHostIpEndPointWithFallback();
Assert.True(cluster.GetHost(ccAddress).IsUp);
// Once all connections are created, the control connection should be usable
await TestHelper.RetryAssertAsync(async () =>
{
serverConnections = await testCluster.GetConnectedPortsAsync().ConfigureAwait(false);
//coreConnectionLength + 1 (the control connection)
Assert.AreEqual(4, serverConnections.Count, "2");
}, 100, 10).ConfigureAwait(false);
TestHelper.RetryAssert(() =>
{
Assert.DoesNotThrowAsync(() => cluster.InternalRef.GetControlConnection().QueryAsync("SELECT * FROM system.local"));
}, 100, 100);
}
}
[Test]
public async Task Should_Use_Next_Host_When_First_Host_Is_Busy()
{
const int connectionLength = 2;
const int maxRequestsPerConnection = 100;
var builder = ClusterBuilder()
.WithPoolingOptions(
PoolingOptions.Create()
.SetCoreConnectionsPerHost(HostDistance.Local, connectionLength)
.SetMaxConnectionsPerHost(HostDistance.Local, connectionLength)
.SetHeartBeatInterval(0)
.SetMaxRequestsPerConnection(maxRequestsPerConnection))
.WithLoadBalancingPolicy(new TestHelper.OrderedLoadBalancingPolicy());
using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3" }))
using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
{
const string query = "SELECT * FROM simulated_ks.table1";
testCluster.PrimeFluent(b => b.WhenQuery(query).ThenVoidSuccess().WithDelayInMs(3000));
var session = await cluster.ConnectAsync().ConfigureAwait(false);
var hosts = cluster.AllHosts().ToArray();
// Wait until all connections to first host are created
await TestHelper.WaitUntilAsync(() =>
session.GetState().GetInFlightQueries(hosts[0]) == connectionLength).ConfigureAwait(false);
const int overflowToNextHost = 10;
var length = maxRequestsPerConnection * connectionLength + Environment.ProcessorCount +
overflowToNextHost;
var tasks = new List<Task<RowSet>>(length);
for (var i = 0; i < length; i++)
{
tasks.Add(session.ExecuteAsync(new SimpleStatement(query)));
}
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
// At least the first n (maxRequestsPerConnection * connectionLength) went to the first host
Assert.That(results.Count(r => r.Info.QueriedHost.Equals(hosts[0].Address)),
Is.GreaterThanOrEqualTo(maxRequestsPerConnection * connectionLength));
// At least the following m (overflowToNextHost) went to the second host
Assert.That(results.Count(r => r.Info.QueriedHost.Equals(hosts[1].Address)),
Is.GreaterThanOrEqualTo(overflowToNextHost));
}
}
[Test]
public async Task Should_Throw_NoHostAvailableException_When_All_Host_Are_Busy()
{
const int connectionLength = 2;
const int maxRequestsPerConnection = 50;
var lbp = new TestHelper.OrderedLoadBalancingPolicy().UseRoundRobin();
var builder = ClusterBuilder()
.WithPoolingOptions(
PoolingOptions.Create()
.SetCoreConnectionsPerHost(HostDistance.Local, connectionLength)
.SetMaxConnectionsPerHost(HostDistance.Local, connectionLength)
.SetHeartBeatInterval(0)
.SetMaxRequestsPerConnection(maxRequestsPerConnection))
.WithSocketOptions(new SocketOptions().SetReadTimeoutMillis(0))
.WithLoadBalancingPolicy(lbp);
using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3" }))
using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
{
const string query = "SELECT * FROM simulated_ks.table1";
testCluster.PrimeFluent(b => b.WhenQuery(query).ThenVoidSuccess().WithDelayInMs(3000));
var session = await cluster.ConnectAsync().ConfigureAwait(false);
var hosts = cluster.AllHosts().ToArray();
await TestHelper.TimesLimit(() =>
session.ExecuteAsync(new SimpleStatement("SELECT key FROM system.local")), 100, 16).ConfigureAwait(false);
// Wait until all connections to all host are created
await TestHelper.WaitUntilAsync(() =>
{
var state = session.GetState();
return state.GetConnectedHosts().All(h => state.GetInFlightQueries(h) == connectionLength);
}).ConfigureAwait(false);
lbp.UseFixedOrder();
const int busyExceptions = 10;
var length = maxRequestsPerConnection * connectionLength * hosts.Length + Environment.ProcessorCount +
busyExceptions;
var tasks = new List<Task<Exception>>(length);
for (var i = 0; i < length; i++)
{
tasks.Add(TestHelper.EatUpException(session.ExecuteAsync(new SimpleStatement(query))));
}
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
// Only successful responses or NoHostAvailableException expected
Assert.Null(results.FirstOrDefault(e => e != null && !(e is NoHostAvailableException)));
// At least the first n (maxRequestsPerConnection * connectionLength * hosts.length) succeeded
Assert.That(results.Count(e => e == null),
Is.GreaterThanOrEqualTo(maxRequestsPerConnection * connectionLength * hosts.Length));
// At least the following m (busyExceptions) failed
var failed = results.Where(e => e is NoHostAvailableException).Cast<NoHostAvailableException>()
.ToArray();
Assert.That(failed, Has.Length.GreaterThanOrEqualTo(busyExceptions));
foreach (var ex in failed)
{
Assert.That(ex.Errors, Has.Count.EqualTo(hosts.Length));
foreach (var kv in ex.Errors)
{
Assert.IsInstanceOf<BusyPoolException>(kv.Value);
var busyException = (BusyPoolException)kv.Value;
Assert.AreEqual(kv.Key, busyException.Address);
Assert.That(busyException.ConnectionLength, Is.EqualTo(connectionLength));
Assert.That(busyException.MaxRequestsPerConnection, Is.EqualTo(maxRequestsPerConnection));
Assert.That(busyException.Message, Is.EqualTo(
$"All connections to host {busyException.Address} are busy, {maxRequestsPerConnection}" +
$" requests are in-flight on each {connectionLength} connection(s)"));
}
}
}
}
[Test]
public async Task Should_Use_Single_Host_When_Configured_At_Statement_Level()
{
const string query = "SELECT * FROM system.local";
var builder = ClusterBuilder().WithLoadBalancingPolicy(new TestHelper.OrderedLoadBalancingPolicy());
using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3" }))
using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
{
var session = await cluster.ConnectAsync().ConfigureAwait(false);
var firstHost = cluster.AllHosts().First();
var lastHost = cluster.AllHosts().Last();
// The test load-balancing policy targets always the first host
await TestHelper.TimesLimit(async () =>
{
var rs = await session.ExecuteAsync(new SimpleStatement(query)).ConfigureAwait(false);
Assert.AreEqual(rs.Info.QueriedHost, firstHost.Address);
return rs;
}, 10, 10).ConfigureAwait(false);
// Use a specific host
var statement = new SimpleStatement(query).SetHost(lastHost);
await TestHelper.TimesLimit(async () =>
{
var rs = await session.ExecuteAsync(statement).ConfigureAwait(false);
// The queried host should be the last one
Assert.AreEqual(rs.Info.QueriedHost, lastHost.Address);
return rs;
}, 10, 10).ConfigureAwait(false);
}
}
[Test]
public void Should_Throw_NoHostAvailableException_When_Targeting_Single_Ignored_Host()
{
const string query = "SELECT * FROM system.local";
// Mark the last host as ignored
var lbp = new TestHelper.CustomLoadBalancingPolicy(
(cluster, ks, stmt) => cluster.AllHosts(),
(cluster, host) => host.Equals(cluster.AllHosts().Last()) ? HostDistance.Ignored : HostDistance.Local);
var builder = ClusterBuilder().WithLoadBalancingPolicy(lbp);
using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3" }))
using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
{
var session = cluster.Connect();
var lastHost = cluster.AllHosts().Last();
// Use the last host
var statement = new SimpleStatement(query).SetHost(lastHost);
Parallel.For(0, 10, _ =>
{
var ex = Assert.ThrowsAsync<NoHostAvailableException>(() => session.ExecuteAsync(statement));
Assert.That(ex.Errors.Count, Is.EqualTo(1));
Assert.That(ex.Errors.First().Key, Is.EqualTo(lastHost.Address));
});
}
}
[Test]
public async Task Should_Throw_NoHostAvailableException_When_Targeting_Single_Host_With_No_Connections()
{
var builder = ClusterBuilder();
using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3" }))
using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
{
var session = await cluster.ConnectAsync().ConfigureAwait(false);
var lastHost = cluster.AllHosts().Last();
// 1 for the control connection and 1 connection per each host
await TestHelper.RetryAssertAsync(async () =>
{
var ports = await testCluster.GetConnectedPortsAsync().ConfigureAwait(false);
Assert.AreEqual(4, ports.Count);
}, 100, 200).ConfigureAwait(false);
var simulacronNode = testCluster.GetNode(lastHost.Address);
// Disable new connections to the first host
await simulacronNode.DisableConnectionListener().ConfigureAwait(false);
var connections = await simulacronNode.GetConnectionsAsync().ConfigureAwait(false);
await TestHelper.RetryAssertAsync(async () =>
{
connections = await simulacronNode.GetConnectionsAsync().ConfigureAwait(false);
Assert.AreEqual(1, connections.Count);
}, 100, 200).ConfigureAwait(false);
await testCluster.DropConnection(connections[0]).ConfigureAwait(false);
await TestHelper.RetryAssertAsync(async () =>
{
connections = await simulacronNode.GetConnectionsAsync().ConfigureAwait(false);
Assert.AreEqual(0, connections.Count);
}, 100, 200).ConfigureAwait(false);
TestHelper.RetryAssert(() =>
{
var openConnections = session.GetState().GetOpenConnections(session.Cluster.GetHost(simulacronNode.IpEndPoint));
Assert.AreEqual(0, openConnections);
}, 100, 200);
// Drop connections to the host last host
await TestHelper.RetryAssertAsync(async () =>
{
var ports = await testCluster.GetConnectedPortsAsync().ConfigureAwait(false);
Assert.AreEqual(3, ports.Count);
}, 100, 200).ConfigureAwait(false);
Parallel.For(0, 10, _ =>
{
var statement = new SimpleStatement("SELECT * FROM system.local").SetHost(lastHost)
.SetIdempotence(true);
var ex = Assert.ThrowsAsync<NoHostAvailableException>(() => session.ExecuteAsync(statement));
Assert.That(ex.Errors.Count, Is.EqualTo(1));
Assert.That(ex.Errors.First().Key, Is.EqualTo(lastHost.Address));
});
}
}
[Test]
public void The_Query_Plan_Should_Contain_A_Single_Host_When_Targeting_Single_Host()
{
var builder = ClusterBuilder();
using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3" }))
using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
{
const string query = "SELECT * FROM simulated_ks.table1";
testCluster.PrimeFluent(b => b.WhenQuery(query).ThenOverloaded("Test overloaded error"));
var session = cluster.Connect();
var host = cluster.AllHosts().Last();
var statement = new SimpleStatement(query).SetHost(host).SetIdempotence(true);
// Overloaded exceptions should be retried on the next host
// but only 1 host in the query plan is expected
var ex = Assert.Throws<NoHostAvailableException>(() => session.Execute(statement));
Assert.That(ex.Errors, Has.Count.EqualTo(1));
Assert.IsInstanceOf<OverloadedException>(ex.Errors.First().Value);
Assert.That(ex.Errors.First().Key, Is.EqualTo(host.Address));
}
}
[Test]
public async Task Should_Not_Use_The_LoadBalancingPolicy_When_Targeting_Single_Host()
{
var queryPlanCounter = 0;
var lbp = new TestHelper.CustomLoadBalancingPolicy((cluster, ks, stmt) =>
{
Interlocked.Increment(ref queryPlanCounter);
return cluster.AllHosts();
});
var builder = ClusterBuilder().WithLoadBalancingPolicy(lbp);
using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3" }))
using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
{
var session = await cluster.ConnectAsync().ConfigureAwait(false);
var host = cluster.AllHosts().Last();
Interlocked.Exchange(ref queryPlanCounter, 0);
await TestHelper.TimesLimit(() =>
{
var statement = new SimpleStatement("SELECT * FROM system.local").SetHost(host);
return session.ExecuteAsync(statement);
}, 1, 1).ConfigureAwait(false);
Assert.Zero(Volatile.Read(ref queryPlanCounter));
}
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Text;
using NBitcoin.BouncyCastle.Utilities;
using NBitcoin.BouncyCastle.Utilities.Encoders;
namespace NBitcoin.BouncyCastle.Asn1.Utilities
{
public sealed class Asn1Dump
{
private static readonly string NewLine = Platform.NewLine;
private Asn1Dump()
{
}
private const string Tab = " ";
private const int SampleSize = 32;
/**
* dump a Der object as a formatted string with indentation
*
* @param obj the Asn1Object to be dumped out.
*/
private static void AsString(
string indent,
bool verbose,
Asn1Object obj,
StringBuilder buf)
{
if (obj is Asn1Sequence)
{
string tab = indent + Tab;
buf.Append(indent);
if (obj is BerSequence)
{
buf.Append("BER Sequence");
}
else if (obj is DerSequence)
{
buf.Append("DER Sequence");
}
else
{
buf.Append("Sequence");
}
buf.Append(NewLine);
foreach (Asn1Encodable o in ((Asn1Sequence)obj))
{
if (o == null || o is Asn1Null)
{
buf.Append(tab);
buf.Append("NULL");
buf.Append(NewLine);
}
else
{
AsString(tab, verbose, o.ToAsn1Object(), buf);
}
}
}
else if (obj is DerTaggedObject)
{
string tab = indent + Tab;
buf.Append(indent);
if (obj is BerTaggedObject)
{
buf.Append("BER Tagged [");
}
else
{
buf.Append("Tagged [");
}
DerTaggedObject o = (DerTaggedObject)obj;
buf.Append(((int)o.TagNo).ToString());
buf.Append(']');
if (!o.IsExplicit())
{
buf.Append(" IMPLICIT ");
}
buf.Append(NewLine);
if (o.IsEmpty())
{
buf.Append(tab);
buf.Append("EMPTY");
buf.Append(NewLine);
}
else
{
AsString(tab, verbose, o.GetObject(), buf);
}
}
else if (obj is BerSet)
{
string tab = indent + Tab;
buf.Append(indent);
buf.Append("BER Set");
buf.Append(NewLine);
foreach (Asn1Encodable o in ((Asn1Set)obj))
{
if (o == null)
{
buf.Append(tab);
buf.Append("NULL");
buf.Append(NewLine);
}
else
{
AsString(tab, verbose, o.ToAsn1Object(), buf);
}
}
}
else if (obj is DerSet)
{
string tab = indent + Tab;
buf.Append(indent);
buf.Append("DER Set");
buf.Append(NewLine);
foreach (Asn1Encodable o in ((Asn1Set)obj))
{
if (o == null)
{
buf.Append(tab);
buf.Append("NULL");
buf.Append(NewLine);
}
else
{
AsString(tab, verbose, o.ToAsn1Object(), buf);
}
}
}
else if (obj is DerObjectIdentifier)
{
buf.Append(indent + "ObjectIdentifier(" + ((DerObjectIdentifier)obj).Id + ")" + NewLine);
}
else if (obj is DerBoolean)
{
buf.Append(indent + "Boolean(" + ((DerBoolean)obj).IsTrue + ")" + NewLine);
}
else if (obj is DerInteger)
{
buf.Append(indent + "Integer(" + ((DerInteger)obj).Value + ")" + NewLine);
}
else if (obj is BerOctetString)
{
byte[] octets = ((Asn1OctetString)obj).GetOctets();
string extra = verbose ? dumpBinaryDataAsString(indent, octets) : "";
buf.Append(indent + "BER Octet String" + "[" + octets.Length + "] " + extra + NewLine);
}
else if (obj is DerOctetString)
{
byte[] octets = ((Asn1OctetString)obj).GetOctets();
string extra = verbose ? dumpBinaryDataAsString(indent, octets) : "";
buf.Append(indent + "DER Octet String" + "[" + octets.Length + "] " + extra + NewLine);
}
else if (obj is DerBitString)
{
DerBitString bt = (DerBitString)obj;
byte[] bytes = bt.GetBytes();
string extra = verbose ? dumpBinaryDataAsString(indent, bytes) : "";
buf.Append(indent + "DER Bit String" + "[" + bytes.Length + ", " + bt.PadBits + "] " + extra + NewLine);
}
else if (obj is DerIA5String)
{
buf.Append(indent + "IA5String(" + ((DerIA5String)obj).GetString() + ") " + NewLine);
}
else if (obj is DerUtf8String)
{
buf.Append(indent + "UTF8String(" + ((DerUtf8String)obj).GetString() + ") " + NewLine);
}
else if (obj is DerPrintableString)
{
buf.Append(indent + "PrintableString(" + ((DerPrintableString)obj).GetString() + ") " + NewLine);
}
else if (obj is DerVisibleString)
{
buf.Append(indent + "VisibleString(" + ((DerVisibleString)obj).GetString() + ") " + NewLine);
}
else if (obj is DerBmpString)
{
buf.Append(indent + "BMPString(" + ((DerBmpString)obj).GetString() + ") " + NewLine);
}
else if (obj is DerT61String)
{
buf.Append(indent + "T61String(" + ((DerT61String)obj).GetString() + ") " + NewLine);
}
else if (obj is DerUtcTime)
{
buf.Append(indent + "UTCTime(" + ((DerUtcTime)obj).TimeString + ") " + NewLine);
}
else if (obj is DerGeneralizedTime)
{
buf.Append(indent + "GeneralizedTime(" + ((DerGeneralizedTime)obj).GetTime() + ") " + NewLine);
}
else if (obj is BerApplicationSpecific)
{
buf.Append(outputApplicationSpecific("BER", indent, verbose, (BerApplicationSpecific)obj));
}
else if (obj is DerApplicationSpecific)
{
buf.Append(outputApplicationSpecific("DER", indent, verbose, (DerApplicationSpecific)obj));
}
else if (obj is DerEnumerated)
{
DerEnumerated en = (DerEnumerated)obj;
buf.Append(indent + "DER Enumerated(" + en.Value + ")" + NewLine);
}
else if (obj is DerExternal)
{
DerExternal ext = (DerExternal)obj;
buf.Append(indent + "External " + NewLine);
string tab = indent + Tab;
if (ext.DirectReference != null)
{
buf.Append(tab + "Direct Reference: " + ext.DirectReference.Id + NewLine);
}
if (ext.IndirectReference != null)
{
buf.Append(tab + "Indirect Reference: " + ext.IndirectReference.ToString() + NewLine);
}
if (ext.DataValueDescriptor != null)
{
AsString(tab, verbose, ext.DataValueDescriptor, buf);
}
buf.Append(tab + "Encoding: " + ext.Encoding + NewLine);
AsString(tab, verbose, ext.ExternalContent, buf);
}
else
{
buf.Append(indent + obj.ToString() + NewLine);
}
}
private static string outputApplicationSpecific(
string type,
string indent,
bool verbose,
DerApplicationSpecific app)
{
StringBuilder buf = new StringBuilder();
if (app.IsConstructed())
{
try
{
Asn1Sequence s = Asn1Sequence.GetInstance(app.GetObject(Asn1Tags.Sequence));
buf.Append(indent + type + " ApplicationSpecific[" + app.ApplicationTag + "]" + NewLine);
foreach (Asn1Encodable ae in s)
{
AsString(indent + Tab, verbose, ae.ToAsn1Object(), buf);
}
}
catch (IOException e)
{
buf.Append(e);
}
return buf.ToString();
}
return indent + type + " ApplicationSpecific[" + app.ApplicationTag + "] ("
+ Hex.ToHexString(app.GetContents()) + ")" + NewLine;
}
[Obsolete("Use version accepting Asn1Encodable")]
public static string DumpAsString(
object obj)
{
if (obj is Asn1Encodable)
{
StringBuilder buf = new StringBuilder();
AsString("", false, ((Asn1Encodable)obj).ToAsn1Object(), buf);
return buf.ToString();
}
return "unknown object type " + obj.ToString();
}
/**
* dump out a DER object as a formatted string, in non-verbose mode
*
* @param obj the Asn1Encodable to be dumped out.
* @return the resulting string.
*/
public static string DumpAsString(
Asn1Encodable obj)
{
return DumpAsString(obj, false);
}
/**
* Dump out the object as a string
*
* @param obj the Asn1Encodable to be dumped out.
* @param verbose if true, dump out the contents of octet and bit strings.
* @return the resulting string.
*/
public static string DumpAsString(
Asn1Encodable obj,
bool verbose)
{
StringBuilder buf = new StringBuilder();
AsString("", verbose, obj.ToAsn1Object(), buf);
return buf.ToString();
}
private static string dumpBinaryDataAsString(string indent, byte[] bytes)
{
indent += Tab;
StringBuilder buf = new StringBuilder(NewLine);
for (int i = 0; i < bytes.Length; i += SampleSize)
{
if (bytes.Length - i > SampleSize)
{
buf.Append(indent);
buf.Append(Hex.ToHexString(bytes, i, SampleSize));
buf.Append(Tab);
buf.Append(calculateAscString(bytes, i, SampleSize));
buf.Append(NewLine);
}
else
{
buf.Append(indent);
buf.Append(Hex.ToHexString(bytes, i, bytes.Length - i));
for (int j = bytes.Length - i; j != SampleSize; j++)
{
buf.Append(" ");
}
buf.Append(Tab);
buf.Append(calculateAscString(bytes, i, bytes.Length - i));
buf.Append(NewLine);
}
}
return buf.ToString();
}
private static string calculateAscString(
byte[] bytes,
int off,
int len)
{
StringBuilder buf = new StringBuilder();
for (int i = off; i != off + len; i++)
{
char c = (char)bytes[i];
if (c >= ' ' && c <= '~')
{
buf.Append(c);
}
}
return buf.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Qwack.Core.Basic;
using Qwack.Core.Instruments;
using Qwack.Core.Models;
using Qwack.Math.Extensions;
using Qwack.Models.Models;
using Qwack.Transport.BasicTypes;
using static System.Math;
using static Qwack.Core.Basic.Capital.SaCcrParameters;
namespace Qwack.Models.Risk
{
public static class SaCcrHelper
{
public const double DefaultAlpha = 1.4;
public const double MultiplerFloor = 0.05;
public static double SaCcrEad(this Portfolio portfolio, IAssetFxModel model, Currency reportingCurrency, Dictionary<string, string> assetIdToTypeMap, Dictionary<string, SaCcrAssetClass> typeToAssetClassMap, ICurrencyProvider currencyProvider, double? pv = null, double alpha = DefaultAlpha)
{
foreach (ISaCcrEnabledCommodity ins in portfolio.Instruments)
{
ins.CommodityType = assetIdToTypeMap[(ins as IAssetInstrument).AssetIds.First()];
ins.AssetClass = typeToAssetClassMap[ins.CommodityType];
}
IAssetFxModel m;
if (model.FundingModel.FxMatrix.BaseCurrency != reportingCurrency)
{
var newFm = FundingModel.RemapBaseCurrency(model.FundingModel, reportingCurrency, currencyProvider);
m = model.Clone(newFm);
}
else
{
m = model.Clone();
}
return SaCcrEad(portfolio, m, pv, alpha);
}
public static double SaCcrEad(this Portfolio portfolio, IAssetFxModel model, double? pv = null, double alpha = DefaultAlpha) => alpha * (Max(0,pv ?? Rc(portfolio, model)) + Pfe(portfolio, model, pv));
public static double SaCcrEad_Margined(this Portfolio portfolio, IAssetFxModel model, SaCcrCollateralSpec collateralSpec, double? pv = null, double alpha = DefaultAlpha)
=> alpha * (Max(0, collateralSpec.Rc(portfolio, model, pv)) + Pfe(portfolio, model, pv, collateralSpec.MPOR, collateralSpec.Collateral));
public static double Rc(Portfolio portfolio, IAssetFxModel model) => Max(0, portfolio.PV(model).SumOfAllRows);
public static double Pfe(Portfolio portfolio, IAssetFxModel model, double? pv=null, double? MPOR = null, double? collateral=null)
{
var addon = AggregateAddOn(portfolio, model, MPOR);
return addon==0?0.0:Multipler(portfolio, model, pv, addon, collateral) * addon;
}
public static double Multipler(Portfolio portfolio, IAssetFxModel model, double? pv = null, double? addOn = null, double? collateral = null)
{
var v = (pv ?? Rc(portfolio, model));
var vMinusC = collateral.HasValue ? v - collateral.Value : v;
var multiplier = Min(1.0, MultiplerFloor + (1 - MultiplerFloor) * Exp(vMinusC / (2.0 * (1 - MultiplerFloor) * (addOn ?? AggregateAddOn(portfolio, model)))));
return multiplier;
}
public static double AggregateAddOn(Portfolio portfolio, IAssetFxModel model, double? MPOR = null) => AddOnIr(portfolio, model, MPOR) + AddOnCredit(portfolio, model, MPOR) + AddOnCommodity(portfolio, model, MPOR) + AddOnFx(portfolio, model, MPOR) + AddOnEquity(portfolio, model, MPOR);
public static double AddOnIr(Portfolio portfolio, IAssetFxModel model, double? MPOR = null)
{
var population = portfolio.Instruments.Where(x => x is ISaCcrEnabledIR).GroupBy(x => x.Currency);
var baseCcy = model.FundingModel.FxMatrix.BaseCurrency;
var addOnIr = 0.0;
foreach (var ccyGroup in population)
{
var fxToBase = baseCcy == null ? 1.0 : model.FundingModel.GetFxRate(model.BuildDate, $"{ccyGroup.Key}/{baseCcy.Ccy}");
var irTrades = ccyGroup.Select(ir => ir as ISaCcrEnabledIR).ToArray();
var irTradeBuckets = irTrades.GroupBy(x => x.MaturityBucket(model.BuildDate));
var buckets = new[] { 1, 2, 3 };
var D = new double[buckets.Max()+1];
foreach (var bucket in buckets)
{
var tradesThisBucket = irTradeBuckets.FirstOrDefault(irtb => irtb.Key == bucket);
if (tradesThisBucket != null)
D[bucket] = tradesThisBucket.Sum(t =>
t.SupervisoryDelta(model) * fxToBase * t.SupervisoryDuration(model.BuildDate) * t.TradeNotional * t.MaturityFactor(model.BuildDate, MPOR));
}
var effNotional = Sqrt(D[1] * D[1] + D[2] * D[2] + D[3] * D[3] + 1.4 * D[1] * D[2] + 1.4 * D[2] * D[3] + 0.6 * D[1] * D[3]);
var addOnForCcy = effNotional * SupervisoryFactors[SaCcrAssetClass.InterestRate];
addOnIr += addOnForCcy;
}
return addOnIr;
}
public static double AddOnFx(Portfolio portfolio, IAssetFxModel model, double? MPOR = null)
{
var population = portfolio.Instruments.Select(x => x as ISaccrEnabledFx).Where(x => x != null).GroupBy(x => x.Pair);
var baseCcy = model.FundingModel.FxMatrix.BaseCurrency;
var addOnFx = 0.0;
foreach (var pairGroup in population)
{
var pair = pairGroup.Key;
var fCccy = pair.Substring(pair.Length - 3, 3);
var fxToBase = baseCcy == null ? 1.0 : model.FundingModel.GetFxRate(model.BuildDate, $"{fCccy}/{baseCcy.Ccy}");
var effNotional = pairGroup.Sum(t => t.SupervisoryDelta(model) * t.ForeignNotional * fxToBase * t.MaturityFactor(model.BuildDate, MPOR));
var addOnForPair = Abs(effNotional) * SupervisoryFactors[SaCcrAssetClass.Fx];
addOnFx += addOnForPair;
}
return addOnFx;
}
public static double AddOnCredit(Portfolio portfolio, IAssetFxModel model, double? MPOR = null)
{
var population = portfolio.Instruments.Select(x => x as ISaccrEnabledCredit).Where(x => x != null).GroupBy(x => x.ReferenceName);
var baseCcy = model.FundingModel.FxMatrix.BaseCurrency;
var addOnByName = new Dictionary<string, double>();
var classByName = new Dictionary<string, SaCcrAssetClass>();
foreach (var entityGroup in population)
{
var name = entityGroup.Key;
var addOnForName = 0.0;
var ccyGroups = entityGroup.GroupBy(e => (e as IInstrument).Currency);
foreach (var ccyGroup in ccyGroups)
{
var fCccy = ccyGroup.Key.Ccy;
var fxToBase = baseCcy == null ? 1.0 : model.FundingModel.GetFxRate(model.BuildDate, $"{fCccy}/{baseCcy.Ccy}");
var effNotional = ccyGroup.Sum(t => t.SupervisoryDelta(model) * t.TradeNotional * fxToBase * t.SupervisoryDuration(model.BuildDate) * t.MaturityFactor(model.BuildDate, MPOR));
var ratingGroup = ccyGroup.Select(e => e.ReferenceRating).Distinct();
if (ratingGroup.Count() > 1)
throw new Exception($"{ratingGroup.Count()} distict ratings found for entity {name}");
var aClass = RatingToClass(ratingGroup.Single());
addOnForName += effNotional * SupervisoryFactors[aClass];
classByName[name] = aClass;
}
addOnByName[name] = addOnForName;
}
var addOnCreditA = 0.0;
var addOnCreditB = 0.0;
foreach (var kv in addOnByName)
{
var aClass = classByName[kv.Key];
var correlation = Correlations[aClass];
var addOn = addOnByName[kv.Key];
addOnCreditA += correlation * addOn;
addOnCreditB += (1 - correlation * correlation) * addOn * addOn;
}
var addOnCredit = Sqrt(addOnCreditA * addOnCreditA + addOnCreditB);
return addOnCredit;
}
private static SaCcrAssetClass RatingToClass(string rating)
{
if (rating == "IG")
return SaCcrAssetClass.CreditIndexIG;
if (rating == "SG")
return SaCcrAssetClass.CreditIndexSG;
var trialName = $"CreditSingle{rating.ToUpper()}";
if (Enum.TryParse<SaCcrAssetClass>(trialName, out var aClass))
return aClass;
else
return SaCcrAssetClass.CreditSingleCCC;
}
public static double AddOnCommodity(Portfolio portfolio, IAssetFxModel model, double? MPOR = null)
{
var population = portfolio.Instruments.Select(x => x as ISaCcrEnabledCommodity).Where(x => x != null).GroupBy(x => x.AssetClass);
var baseCcy = model.FundingModel.FxMatrix.BaseCurrency;
var addOnByClass = new Dictionary<SaCcrAssetClass, Dictionary<string,double>>();
foreach (var classGroup in population)
{
var aClass = classGroup.Key;
addOnByClass[aClass] = new Dictionary<string, double>();
var byType = classGroup.GroupBy(c => c.CommodityType);
foreach (var typeGroup in byType)
{
var addOnForType = 0.0;
var ccyGroups = typeGroup.GroupBy(e => (e as IInstrument).Currency);
foreach (var ccyGroup in ccyGroups)
{
var fCccy = ccyGroup.Key.Ccy;
var fxToBase = baseCcy == null ? 1.0 : model.FundingModel.GetFxRate(model.BuildDate, $"{fCccy}/{baseCcy.Ccy}");
var effNotional = ccyGroup.Sum(t => t.SupervisoryDelta(model) * t.TradeNotional(model) * fxToBase * t.MaturityFactor(model.BuildDate, MPOR));
addOnForType += effNotional * SupervisoryFactors[aClass];
}
addOnByClass[aClass][typeGroup.Key] = addOnForType;
}
}
var addOnCommodity = 0.0;
foreach (var cl in addOnByClass)
{
var addOnCommoA = 0.0;
var addOnCommoB = 0.0;
foreach (var kv in cl.Value)
{
var aClass = cl.Key;
var correlation = Correlations[aClass];
var addOn = kv.Value;
addOnCommoA += correlation * addOn;
addOnCommoB += (1 - correlation * correlation) * addOn * addOn;
}
addOnCommodity += Sqrt(addOnCommoA * addOnCommoA + addOnCommoB);
}
return addOnCommodity;
}
public static double AddOnEquity(Portfolio portfolio, IAssetFxModel model, double? MPOR = null)
{
var population = portfolio.Instruments.Select(x => x as ISaccrEnabledEquity).Where(x => x != null).GroupBy(x => x.ReferenceName);
var baseCcy = model.FundingModel.FxMatrix.BaseCurrency;
var addOnByName = new Dictionary<string, double>();
var classByName = new Dictionary<string, SaCcrAssetClass>();
foreach (var entityGroup in population)
{
var name = entityGroup.Key;
var addOnForName = 0.0;
var ccyGroups = entityGroup.GroupBy(e => (e as IInstrument).Currency);
foreach (var ccyGroup in ccyGroups)
{
var fCccy = ccyGroup.Key.Ccy;
var fxToBase = model.FundingModel.GetFxRate(model.BuildDate, $"{baseCcy.Ccy}/{fCccy}");
var effNotional = ccyGroup.Sum(t => t.SupervisoryDelta(model) * t.TradeNotional * fxToBase * t.MaturityFactor(model.BuildDate, MPOR));
var ratingGroup = ccyGroup.Select(e => e.IsIndex).Distinct();
if (ratingGroup.Count() != 1)
throw new Exception($"Inconsistent index/single stock distict ratings found for entity {name}");
var aClass = ratingGroup.Single() ? SaCcrAssetClass.EquityIndex : SaCcrAssetClass.EquitySingle;
addOnForName += effNotional * SupervisoryFactors[aClass];
classByName[name] = aClass;
}
addOnByName[name] = addOnForName;
}
var addOnEquityA = 0.0;
var addOnEquityB = 0.0;
foreach (var kv in addOnByName)
{
var aClass = classByName[kv.Key];
var correlation = Correlations[aClass];
var addOn = addOnByName[kv.Key];
addOnEquityA += correlation * addOn;
addOnEquityB += (1 - correlation * correlation) * addOn * addOn;
}
var addOnEquity = Sqrt(addOnEquityA * addOnEquityA + addOnEquityB);
return addOnEquity;
}
}
public class SaCcrCollateralSpec
{
public double Collateral { get; set; }
public Currency CollateralCrurrency { get; set; }
/// <summary>
/// Variation margin (i.e. daily margining) is applicable
/// </summary>
public bool HasVm { get; set; }
/// <summary>
/// Minimum Transfer Amount
/// </summary>
public double MTA { get; set; }
public double Threshold { get; set; }
/// <summary>
/// Net independent collateral amount
/// </summary>
public double NICA { get; set; }
/// <summary>
/// Margin Period of Risk, in business days
/// </summary>
public double? MPOR { get; set; }
public double Rc(Portfolio portfolio, IAssetFxModel model, double? pv = null) => HasVm ?
Max(0, (pv ?? portfolio.PV(model).SumOfAllRows) - Collateral) :
Max(0, Max((pv ?? portfolio.PV(model).SumOfAllRows) - Collateral, MTA + Threshold - NICA));
public void SetMPOR(int frequencyInBusinessDays) => MPOR = 10 + frequencyInBusinessDays - 1;
}
}
| |
// 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.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
using System.IO;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal static class AnalyzerHelper
{
private const string CSharpCompilerAnalyzerTypeName = "Microsoft.CodeAnalysis.Diagnostics.CSharp.CSharpCompilerDiagnosticAnalyzer";
private const string VisualBasicCompilerAnalyzerTypeName = "Microsoft.CodeAnalysis.Diagnostics.VisualBasic.VisualBasicCompilerDiagnosticAnalyzer";
// These are the error codes of the compiler warnings.
// Keep the ids the same so that de-duplication against compiler errors
// works in the error list (after a build).
internal const string WRN_AnalyzerCannotBeCreatedIdCS = "CS8032";
internal const string WRN_AnalyzerCannotBeCreatedIdVB = "BC42376";
internal const string WRN_NoAnalyzerInAssemblyIdCS = "CS8033";
internal const string WRN_NoAnalyzerInAssemblyIdVB = "BC42377";
internal const string WRN_UnableToLoadAnalyzerIdCS = "CS8034";
internal const string WRN_UnableToLoadAnalyzerIdVB = "BC42378";
// Shared with Compiler
internal const string AnalyzerExceptionDiagnosticId = "AD0001";
internal const string AnalyzerDriverExceptionDiagnosticId = "AD0002";
// IDE only errors
internal const string WRN_AnalyzerCannotBeCreatedId = "AD1000";
internal const string WRN_NoAnalyzerInAssemblyId = "AD1001";
internal const string WRN_UnableToLoadAnalyzerId = "AD1002";
private const string AnalyzerExceptionDiagnosticCategory = "Intellisense";
public static bool IsWorkspaceDiagnosticAnalyzer(this DiagnosticAnalyzer analyzer)
{
return analyzer is DocumentDiagnosticAnalyzer || analyzer is ProjectDiagnosticAnalyzer;
}
public static bool IsBuiltInAnalyzer(this DiagnosticAnalyzer analyzer)
{
return analyzer is IBuiltInAnalyzer || analyzer.IsWorkspaceDiagnosticAnalyzer() || analyzer.IsCompilerAnalyzer();
}
public static bool ShouldRunForFullProject(this DiagnosticAnalyzerService service, DiagnosticAnalyzer analyzer, Project project)
{
var builtInAnalyzer = analyzer as IBuiltInAnalyzer;
if (builtInAnalyzer != null)
{
return !builtInAnalyzer.OpenFileOnly(project.Solution.Workspace);
}
if (analyzer.IsWorkspaceDiagnosticAnalyzer())
{
return true;
}
// most of analyzers, number of descriptor is quite small, so this should be cheap.
return service.GetDiagnosticDescriptors(analyzer).Any(d => d.GetEffectiveSeverity(project.CompilationOptions) != ReportDiagnostic.Hidden);
}
public static ReportDiagnostic GetEffectiveSeverity(this DiagnosticDescriptor descriptor, CompilationOptions options)
{
return options == null
? descriptor.DefaultSeverity.MapSeverityToReport()
: descriptor.GetEffectiveSeverity(options);
}
public static ReportDiagnostic MapSeverityToReport(this DiagnosticSeverity severity)
{
switch (severity)
{
case DiagnosticSeverity.Hidden:
return ReportDiagnostic.Hidden;
case DiagnosticSeverity.Info:
return ReportDiagnostic.Info;
case DiagnosticSeverity.Warning:
return ReportDiagnostic.Warn;
case DiagnosticSeverity.Error:
return ReportDiagnostic.Error;
default:
throw ExceptionUtilities.Unreachable;
}
}
public static bool IsCompilerAnalyzer(this DiagnosticAnalyzer analyzer)
{
// TODO: find better way.
var typeString = analyzer.GetType().ToString();
if (typeString == CSharpCompilerAnalyzerTypeName)
{
return true;
}
if (typeString == VisualBasicCompilerAnalyzerTypeName)
{
return true;
}
return false;
}
public static ValueTuple<string, VersionStamp> GetAnalyzerIdAndVersion(this DiagnosticAnalyzer analyzer)
{
// Get the unique ID for given diagnostic analyzer.
// note that we also put version stamp so that we can detect changed analyzer.
var typeInfo = analyzer.GetType().GetTypeInfo();
return ValueTuple.Create(analyzer.GetAnalyzerId(), GetAnalyzerVersion(CorLightup.Desktop.GetAssemblyLocation(typeInfo.Assembly)));
}
public static string GetAnalyzerAssemblyName(this DiagnosticAnalyzer analyzer)
{
var typeInfo = analyzer.GetType().GetTypeInfo();
return typeInfo.Assembly.GetName().Name;
}
public static OptionSet GetOptionSet(this AnalyzerOptions analyzerOptions)
{
return (analyzerOptions as WorkspaceAnalyzerOptions)?.Workspace.Options;
}
internal static void OnAnalyzerException_NoTelemetryLogging(
Exception ex,
DiagnosticAnalyzer analyzer,
Diagnostic diagnostic,
AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource,
ProjectId projectIdOpt)
{
if (diagnostic != null)
{
hostDiagnosticUpdateSource?.ReportAnalyzerDiagnostic(analyzer, diagnostic, hostDiagnosticUpdateSource?.Workspace, projectIdOpt);
}
if (IsBuiltInAnalyzer(analyzer))
{
FatalError.ReportWithoutCrashUnlessCanceled(ex);
}
}
internal static void OnAnalyzerExceptionForSupportedDiagnostics(DiagnosticAnalyzer analyzer, Exception exception, AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
{
if (exception is OperationCanceledException)
{
return;
}
var diagnostic = CreateAnalyzerExceptionDiagnostic(analyzer, exception);
OnAnalyzerException_NoTelemetryLogging(exception, analyzer, diagnostic, hostDiagnosticUpdateSource, projectIdOpt: null);
}
/// <summary>
/// Create a diagnostic for exception thrown by the given analyzer.
/// </summary>
/// <remarks>
/// Keep this method in sync with "AnalyzerExecutor.CreateAnalyzerExceptionDiagnostic".
/// </remarks>
internal static Diagnostic CreateAnalyzerExceptionDiagnostic(DiagnosticAnalyzer analyzer, Exception e)
{
var analyzerName = analyzer.ToString();
// TODO: It is not ideal to create a new descriptor per analyzer exception diagnostic instance.
// However, until we add a LongMessage field to the Diagnostic, we are forced to park the instance specific description onto the Descriptor's Description field.
// This requires us to create a new DiagnosticDescriptor instance per diagnostic instance.
var descriptor = new DiagnosticDescriptor(AnalyzerExceptionDiagnosticId,
title: FeaturesResources.User_Diagnostic_Analyzer_Failure,
messageFormat: FeaturesResources.Analyzer_0_threw_an_exception_of_type_1_with_message_2,
description: string.Format(FeaturesResources.Analyzer_0_threw_the_following_exception_colon_1, analyzerName, e.CreateDiagnosticDescription()),
category: AnalyzerExceptionDiagnosticCategory,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
customTags: WellKnownDiagnosticTags.AnalyzerException);
return Diagnostic.Create(descriptor, Location.None, analyzerName, e.GetType(), e.Message);
}
private static VersionStamp GetAnalyzerVersion(string path)
{
if (path == null || !File.Exists(path))
{
return VersionStamp.Default;
}
return VersionStamp.Create(File.GetLastWriteTimeUtc(path));
}
public static DiagnosticData CreateAnalyzerLoadFailureDiagnostic(string fullPath, AnalyzerLoadFailureEventArgs e)
{
return CreateAnalyzerLoadFailureDiagnostic(null, null, null, fullPath, e);
}
public static DiagnosticData CreateAnalyzerLoadFailureDiagnostic(
Workspace workspace, ProjectId projectId, string language, string fullPath, AnalyzerLoadFailureEventArgs e)
{
string id, message, messageFormat, description;
if (!TryGetErrorMessage(language, fullPath, e, out id, out message, out messageFormat, out description))
{
return null;
}
return new DiagnosticData(
id,
FeaturesResources.Roslyn_HostError,
message,
messageFormat,
severity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: description,
warningLevel: 0,
workspace: workspace,
projectId: projectId);
}
private static bool TryGetErrorMessage(
string language, string fullPath, AnalyzerLoadFailureEventArgs e,
out string id, out string message, out string messageFormat, out string description)
{
switch (e.ErrorCode)
{
case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer:
id = Choose(language, WRN_UnableToLoadAnalyzerId, WRN_UnableToLoadAnalyzerIdCS, WRN_UnableToLoadAnalyzerIdVB);
messageFormat = FeaturesResources.Unable_to_load_Analyzer_assembly_0_colon_1;
message = string.Format(FeaturesResources.Unable_to_load_Analyzer_assembly_0_colon_1, fullPath, e.Message);
description = e.Exception.CreateDiagnosticDescription();
break;
case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer:
id = Choose(language, WRN_AnalyzerCannotBeCreatedId, WRN_AnalyzerCannotBeCreatedIdCS, WRN_AnalyzerCannotBeCreatedIdVB);
messageFormat = FeaturesResources.An_instance_of_analyzer_0_cannot_be_created_from_1_colon_2;
message = string.Format(FeaturesResources.An_instance_of_analyzer_0_cannot_be_created_from_1_colon_2, e.TypeName, fullPath, e.Message);
description = e.Exception.CreateDiagnosticDescription();
break;
case AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers:
id = Choose(language, WRN_NoAnalyzerInAssemblyId, WRN_NoAnalyzerInAssemblyIdCS, WRN_NoAnalyzerInAssemblyIdVB);
messageFormat = FeaturesResources.The_assembly_0_does_not_contain_any_analyzers;
message = string.Format(FeaturesResources.The_assembly_0_does_not_contain_any_analyzers, fullPath);
description = e.Exception.CreateDiagnosticDescription();
break;
case AnalyzerLoadFailureEventArgs.FailureErrorCode.None:
default:
id = string.Empty;
message = string.Empty;
messageFormat = string.Empty;
description = string.Empty;
return false;
}
return true;
}
private static string Choose(string language, string noLanguageMessage, string csharpMessage, string vbMessage)
{
if (language == null)
{
return noLanguageMessage;
}
return language == LanguageNames.CSharp ? csharpMessage : vbMessage;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// SignedInfo.cs
//
// 21 [....] 2000
//
namespace System.Security.Cryptography.Xml
{
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Xml;
using System.Globalization;
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class SignedInfo : ICollection {
private string m_id;
private string m_canonicalizationMethod;
private string m_signatureMethod;
private string m_signatureLength;
private ArrayList m_references;
private XmlElement m_cachedXml = null;
private SignedXml m_signedXml = null;
private Transform m_canonicalizationMethodTransform = null;
internal SignedXml SignedXml {
get { return m_signedXml; }
set { m_signedXml = value; }
}
public SignedInfo() {
m_references = new ArrayList();
}
public IEnumerator GetEnumerator() {
throw new NotSupportedException();
}
public void CopyTo(Array array, int index) {
throw new NotSupportedException();
}
public Int32 Count {
get { throw new NotSupportedException(); }
}
public Boolean IsReadOnly {
get { throw new NotSupportedException(); }
}
public Boolean IsSynchronized {
get { throw new NotSupportedException(); }
}
public object SyncRoot {
get { throw new NotSupportedException(); }
}
//
// public properties
//
public string Id {
get { return m_id; }
set {
m_id = value;
m_cachedXml = null;
}
}
public string CanonicalizationMethod {
get {
// Default the canonicalization method to C14N
if (m_canonicalizationMethod == null)
return SignedXml.XmlDsigC14NTransformUrl;
return m_canonicalizationMethod;
}
set {
m_canonicalizationMethod = value;
m_cachedXml = null;
}
}
[ComVisible(false)]
public Transform CanonicalizationMethodObject {
get {
if (m_canonicalizationMethodTransform == null) {
m_canonicalizationMethodTransform = CryptoConfig.CreateFromName(this.CanonicalizationMethod) as Transform;
if (m_canonicalizationMethodTransform == null)
throw new CryptographicException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_CreateTransformFailed"), this.CanonicalizationMethod));
m_canonicalizationMethodTransform.SignedXml = this.SignedXml;
m_canonicalizationMethodTransform.Reference = null;
}
return m_canonicalizationMethodTransform;
}
}
public string SignatureMethod {
get { return m_signatureMethod; }
set {
m_signatureMethod = value;
m_cachedXml = null;
}
}
public string SignatureLength {
get { return m_signatureLength; }
set {
m_signatureLength = value;
m_cachedXml = null;
}
}
public ArrayList References {
get { return m_references; }
}
internal bool CacheValid {
get {
if (m_cachedXml == null) return false;
// now check all the references
foreach (Reference reference in References) {
if (!reference.CacheValid) return false;
}
return true;
}
}
//
// public methods
//
public XmlElement GetXml() {
if (CacheValid) return m_cachedXml;
XmlDocument document = new XmlDocument();
document.PreserveWhitespace = true;
return GetXml(document);
}
internal XmlElement GetXml (XmlDocument document) {
// Create the root element
XmlElement signedInfoElement = document.CreateElement("SignedInfo", SignedXml.XmlDsigNamespaceUrl);
if (!String.IsNullOrEmpty(m_id))
signedInfoElement.SetAttribute("Id", m_id);
// Add the canonicalization method, defaults to SignedXml.XmlDsigNamespaceUrl
XmlElement canonicalizationMethodElement = this.CanonicalizationMethodObject.GetXml(document, "CanonicalizationMethod");
signedInfoElement.AppendChild(canonicalizationMethodElement);
// Add the signature method
if (String.IsNullOrEmpty(m_signatureMethod))
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureMethodRequired"));
XmlElement signatureMethodElement = document.CreateElement("SignatureMethod", SignedXml.XmlDsigNamespaceUrl);
signatureMethodElement.SetAttribute("Algorithm", m_signatureMethod);
// Add HMACOutputLength tag if we have one
if (m_signatureLength != null) {
XmlElement hmacLengthElement = document.CreateElement(null, "HMACOutputLength", SignedXml.XmlDsigNamespaceUrl);
XmlText outputLength = document.CreateTextNode(m_signatureLength);
hmacLengthElement.AppendChild(outputLength);
signatureMethodElement.AppendChild(hmacLengthElement);
}
signedInfoElement.AppendChild(signatureMethodElement);
// Add the references
if (m_references.Count == 0)
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_ReferenceElementRequired"));
for (int i = 0; i < m_references.Count; ++i) {
Reference reference = (Reference)m_references[i];
signedInfoElement.AppendChild(reference.GetXml(document));
}
return signedInfoElement;
}
public void LoadXml(XmlElement value) {
if (value == null)
throw new ArgumentNullException("value");
// SignedInfo
XmlElement signedInfoElement = value;
if (!signedInfoElement.LocalName.Equals("SignedInfo"))
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo");
XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);
nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
// Id attribute -- optional
m_id = Utils.GetAttribute(signedInfoElement, "Id", SignedXml.XmlDsigNamespaceUrl);
// CanonicalizationMethod -- must be present
XmlElement canonicalizationMethodElement = signedInfoElement.SelectSingleNode("ds:CanonicalizationMethod", nsm) as XmlElement;
if (canonicalizationMethodElement == null)
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"),"SignedInfo/CanonicalizationMethod");
m_canonicalizationMethod = Utils.GetAttribute(canonicalizationMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
m_canonicalizationMethodTransform = null;
if (canonicalizationMethodElement.ChildNodes.Count > 0)
this.CanonicalizationMethodObject.LoadInnerXml(canonicalizationMethodElement.ChildNodes);
// SignatureMethod -- must be present
XmlElement signatureMethodElement = signedInfoElement.SelectSingleNode("ds:SignatureMethod", nsm) as XmlElement;
if (signatureMethodElement == null)
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"),"SignedInfo/SignatureMethod");
m_signatureMethod = Utils.GetAttribute(signatureMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
// Now get the output length if we are using a MAC algorithm
XmlElement signatureLengthElement = signatureMethodElement.SelectSingleNode("ds:HMACOutputLength", nsm) as XmlElement;
if (signatureLengthElement != null)
m_signatureLength = signatureLengthElement.InnerXml;
// flush out any reference that was there
m_references.Clear();
XmlNodeList referenceNodes = signedInfoElement.SelectNodes("ds:Reference", nsm);
if (referenceNodes != null) {
foreach(XmlNode node in referenceNodes) {
XmlElement referenceElement = node as XmlElement;
Reference reference = new Reference();
AddReference(reference);
reference.LoadXml(referenceElement);
}
}
// Save away the cached value
m_cachedXml = signedInfoElement;
}
public void AddReference (Reference reference) {
if (reference == null)
throw new ArgumentNullException("reference");
reference.SignedXml = this.SignedXml;
m_references.Add(reference);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="GraphStageLogicSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using Akka.Actor;
using Akka.Pattern;
using Akka.Streams.Dsl;
using Akka.Streams.Dsl.Internal;
using Akka.Streams.Stage;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.Streams.Tests.Implementation.Fusing;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
namespace Akka.Streams.Tests.Implementation
{
public class GraphStageLogicSpec : GraphInterpreterSpecKit
{
private class Emit1234 : GraphStage<FlowShape<int, int>>
{
#region internal classes
private class Emit1234Logic : GraphStageLogic
{
private readonly Emit1234 _emit;
public Emit1234Logic(Emit1234 emit) : base(emit.Shape)
{
_emit = emit;
SetHandler(emit._in, EagerTerminateInput);
SetHandler(emit._out, EagerTerminateOutput);
}
public override void PreStart()
{
Emit(_emit._out, 1, () => Emit(_emit._out, 2));
Emit(_emit._out, 3, () => Emit(_emit._out, 4));
}
}
#endregion
private readonly Inlet<int> _in = new Inlet<int>("in");
private readonly Outlet<int> _out = new Outlet<int>("out");
public Emit1234()
{
Shape = new FlowShape<int, int>(_in, _out);
}
public override FlowShape<int, int> Shape { get; }
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Emit1234Logic(this);
}
private class Emit5678 : GraphStage<FlowShape<int, int>>
{
#region internal classes
private class Emit5678Logic : GraphStageLogic
{
public Emit5678Logic(Emit5678 emit) : base(emit.Shape)
{
SetHandler(emit._in, onPush: () => Push(emit._out, Grab(emit._in)), onUpstreamFinish: () =>
{
Emit(emit._out, 5, () => Emit(emit._out, 6));
Emit(emit._out, 7, () => Emit(emit._out, 8));
CompleteStage();
});
SetHandler(emit._out, onPull: () => Pull(emit._in));
}
}
#endregion
private readonly Inlet<int> _in = new Inlet<int>("in");
private readonly Outlet<int> _out = new Outlet<int>("out");
public Emit5678()
{
Shape = new FlowShape<int, int>(_in, _out);
}
public override FlowShape<int, int> Shape { get; }
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Emit5678Logic(this);
}
private class PassThrough : GraphStage<FlowShape<int, int>>
{
#region internal classes
private class PassThroughLogic : GraphStageLogic
{
public PassThroughLogic(PassThrough emit) : base(emit.Shape)
{
SetHandler(emit.In, onPush: () => Push(emit.Out, Grab(emit.In)),
onUpstreamFinish: () => Complete(emit.Out));
SetHandler(emit.Out, onPull: () => Pull(emit.In));
}
}
#endregion
public Inlet<int> In { get; }= new Inlet<int>("in");
public Outlet<int> Out { get; } = new Outlet<int>("out");
public PassThrough()
{
Shape = new FlowShape<int, int>(In, Out);
}
public override FlowShape<int, int> Shape { get; }
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new PassThroughLogic(this);
}
private class EmitEmptyIterable : GraphStage<SourceShape<int>>
{
#region internal classes
private class EmitEmptyIterableLogic : GraphStageLogic
{
public EmitEmptyIterableLogic(EmitEmptyIterable emit) : base(emit.Shape)
{
SetHandler(emit._out, () => EmitMultiple(emit._out, Enumerable.Empty<int>(), () => Emit(emit._out, 42, CompleteStage)));
}
}
#endregion
private readonly Outlet<int> _out = new Outlet<int>("out");
public EmitEmptyIterable()
{
Shape = new SourceShape<int>(_out);
}
public override SourceShape<int> Shape { get; }
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes)
=> new EmitEmptyIterableLogic(this);
}
private class ReadNEmitN : GraphStage<FlowShape<int, int>>
{
private readonly int _n;
#region internal classes
private class ReadNEmitNLogic : GraphStageLogic
{
private readonly ReadNEmitN _emit;
public ReadNEmitNLogic(ReadNEmitN emit) : base(emit.Shape)
{
_emit = emit;
SetHandler(emit.Shape.Inlet, EagerTerminateInput);
SetHandler(emit.Shape.Outlet, EagerTerminateOutput);
}
public override void PreStart()
{
ReadMany(_emit.Shape.Inlet, _emit._n,
e => EmitMultiple(_emit.Shape.Outlet, e.GetEnumerator(), CompleteStage), _ => { });
}
}
#endregion
public ReadNEmitN(int n)
{
_n = n;
}
public override FlowShape<int, int> Shape { get; } = new FlowShape<int, int>(new Inlet<int>("readN.in"),
new Outlet<int>("readN.out"));
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new ReadNEmitNLogic(this);
}
private class ReadNEmitRestOnComplete : GraphStage<FlowShape<int, int>>
{
private readonly int _n;
#region internal classes
private class ReadNEmitRestOnCompleteLogic : GraphStageLogic
{
private readonly ReadNEmitRestOnComplete _emit;
public ReadNEmitRestOnCompleteLogic(ReadNEmitRestOnComplete emit) : base(emit.Shape)
{
_emit = emit;
SetHandler(emit.Shape.Inlet, EagerTerminateInput);
SetHandler(emit.Shape.Outlet, EagerTerminateOutput);
}
public override void PreStart()
{
ReadMany(_emit.Shape.Inlet, _emit._n,
_=> FailStage(new IllegalStateException("Shouldn't happen!")),
e=> EmitMultiple(_emit.Shape.Outlet, e.GetEnumerator(), CompleteStage));
}
}
#endregion
public ReadNEmitRestOnComplete(int n)
{
_n = n;
}
public override FlowShape<int, int> Shape { get; } = new FlowShape<int, int>(new Inlet<int>("readN.in"),
new Outlet<int>("readN.out"));
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes)
=> new ReadNEmitRestOnCompleteLogic(this);
}
private ActorMaterializer Materializer { get; }
public GraphStageLogicSpec(ITestOutputHelper output) : base(output)
{
Materializer = ActorMaterializer.Create(Sys);
}
[Fact]
public void A_GraphStageLogic_must_read_N_and_emit_N_before_completing()
{
this.AssertAllStagesStopped(() =>
{
Source.From(Enumerable.Range(1, 10))
.Via(new ReadNEmitN(2))
.RunWith(this.SinkProbe<int>(), Materializer)
.Request(10)
.ExpectNext(1, 2)
.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_GraphStageLogic_must_read_N_should_not_emit_if_upstream_completes_before_N_is_sent()
{
this.AssertAllStagesStopped(() =>
{
Source.From(Enumerable.Range(1, 5))
.Via(new ReadNEmitN(6))
.RunWith(this.SinkProbe<int>(), Materializer)
.Request(10)
.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_GraphStageLogic_must_read_N_should_not_emit_if_upstream_fails_before_N_is_sent()
{
this.AssertAllStagesStopped(() =>
{
var error = new ArgumentException("Don't argue like that!");
Source.From(Enumerable.Range(1, 5))
.Select(x =>
{
if (x > 3)
throw error;
return x;
})
.Via(new ReadNEmitN(6))
.RunWith(this.SinkProbe<int>(), Materializer)
.Request(10)
.ExpectError().Should().Be(error);
}, Materializer);
}
[Fact]
public void A_GraphStageLogic_must_read_N_should_provide_elements_read_if_OnComplete_happens_before_N_elements_have_been_seen()
{
this.AssertAllStagesStopped(() =>
{
Source.From(Enumerable.Range(1, 5))
.Via(new ReadNEmitRestOnComplete(6))
.RunWith(this.SinkProbe<int>(), Materializer)
.Request(10)
.ExpectNext(1, 2, 3, 4, 5)
.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_GraphStageLogic_must_emit_all_things_before_completing()
{
this.AssertAllStagesStopped(() =>
{
Source.Empty<int>()
.Via(new Emit1234().Named("testStage"))
.RunWith(this.SinkProbe<int>(), Materializer)
.Request(5)
.ExpectNext(1, 2, 3, 4)
.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_GraphStageLogic_must_emit_all_things_before_completing_with_two_fused_stages()
{
this.AssertAllStagesStopped(() =>
{
var flow = Flow.Create<int>().Via(new Emit1234()).Via(new Emit5678());
var g = Streams.Implementation.Fusing.Fusing.Aggressive(flow);
Source.Empty<int>()
.Via(g)
.RunWith(this.SinkProbe<int>(), Materializer)
.Request(9)
.ExpectNext(1, 2, 3, 4, 5, 6, 7, 8)
.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_GraphStageLogic_must_emit_all_things_before_completing_with_three_fused_stages()
{
this.AssertAllStagesStopped(() =>
{
var flow = Flow.Create<int>().Via(new Emit1234()).Via(new PassThrough()).Via(new Emit5678());
var g = Streams.Implementation.Fusing.Fusing.Aggressive(flow);
Source.Empty<int>()
.Via(g)
.RunWith(this.SinkProbe<int>(), Materializer)
.Request(9)
.ExpectNext(1, 2, 3, 4, 5, 6, 7, 8)
.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_GraphStageLogic_must_emit_properly_after_empty_iterable()
{
this.AssertAllStagesStopped(() =>
{
Source.FromGraph(new EmitEmptyIterable())
.RunWith(Sink.Seq<int>(), Materializer)
.Result.Should()
.HaveCount(1)
.And.OnlyContain(x => x == 42);
}, Materializer);
}
[Fact]
public void A_GraphStageLogic_must_infoke_livecycle_hooks_in_the_right_order()
{
this.AssertAllStagesStopped(() =>
{
var g = new LifecycleStage(TestActor);
Source.Single(1).Via(g).RunWith(Sink.Ignore<int>(), Materializer);
ExpectMsg("preStart");
ExpectMsg("pulled");
ExpectMsg("postStop");
}, Materializer);
}
private class LifecycleStage : GraphStage<FlowShape<int, int>>
{
#region internal class
private class LivecycleLogic : GraphStageLogic
{
private readonly IActorRef _testActor;
public LivecycleLogic(LifecycleStage stage, IActorRef testActor) : base(stage.Shape)
{
_testActor = testActor;
SetHandler(stage._in, EagerTerminateInput);
SetHandler(stage._out, () =>
{
CompleteStage();
testActor.Tell("pulled");
});
}
public override void PreStart()
{
_testActor.Tell("preStart");
}
public override void PostStop()
{
_testActor.Tell("postStop");
}
}
#endregion
private readonly Inlet<int> _in = new Inlet<int>("in");
private readonly Outlet<int> _out = new Outlet<int>("out");
private readonly IActorRef _testActor;
public LifecycleStage(IActorRef testActor)
{
_testActor = testActor;
Shape = new FlowShape<int, int>(_in, _out);
}
public override FlowShape<int, int> Shape { get; }
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes)
=> new LivecycleLogic(this, _testActor);
}
[Fact]
public void A_GraphStageLogic_must_not_double_terminate_a_single_stage()
{
WithBaseBuilderSetup(
new GraphStage<FlowShape<int, int>>[] {new DoubleTerminateStage(TestActor), new PassThrough()},
interpreter =>
{
interpreter.Complete(0);
interpreter.Cancel(1);
interpreter.Execute(2);
ExpectMsg("postStop2");
ExpectNoMsg(0);
interpreter.IsCompleted.Should().BeFalse();
interpreter.IsSuspended.Should().BeFalse();
interpreter.IsStageCompleted(interpreter.Logics[0]).Should().BeTrue();
interpreter.IsStageCompleted(interpreter.Logics[1]).Should().BeFalse();
});
}
private class DoubleTerminateStage : GraphStage<FlowShape<int, int>>
{
#region internal class
private class DoubleTerminateLogic : GraphStageLogic
{
private readonly IActorRef _testActor;
public DoubleTerminateLogic(DoubleTerminateStage stage, IActorRef testActor) : base(stage.Shape)
{
_testActor = testActor;
SetHandler(stage.In, EagerTerminateInput);
SetHandler(stage.Out, EagerTerminateOutput);
}
public override void PostStop()
{
_testActor.Tell("postStop2");
}
}
#endregion
private readonly IActorRef _testActor;
public DoubleTerminateStage(IActorRef testActor)
{
_testActor = testActor;
Shape = new FlowShape<int, int>(In, Out);
}
public override FlowShape<int, int> Shape { get; }
public Inlet<int> In { get; } = new Inlet<int>("in");
public Outlet<int> Out { get; } = new Outlet<int>("out");
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes)
=> new DoubleTerminateLogic(this, _testActor);
}
}
}
| |
// 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;
namespace System.Xml.Serialization
{
/// <include file='doc\XmlElementAttributes.uex' path='docs/doc[@for="XmlElementAttributes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlElementAttributes : IList
{
private List<XmlElementAttribute> _list = new List<XmlElementAttribute>();
/// <include file='doc\XmlElementAttributes.uex' path='docs/doc[@for="XmlElementAttributes.this"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlElementAttribute this[int index]
{
get { return _list[index]; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_list[index] = value;
}
}
/// <include file='doc\XmlElementAttributes.uex' path='docs/doc[@for="XmlElementAttributes.Add"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Add(XmlElementAttribute value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
int index = _list.Count;
_list.Add(value);
return index;
}
/// <include file='doc\XmlElementAttributes.uex' path='docs/doc[@for="XmlElementAttributes.Insert"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Insert(int index, XmlElementAttribute value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_list.Insert(index, value);
}
/// <include file='doc\XmlElementAttributes.uex' path='docs/doc[@for="XmlElementAttributes.IndexOf"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int IndexOf(XmlElementAttribute value)
{
return _list.IndexOf(value);
}
/// <include file='doc\XmlElementAttributes.uex' path='docs/doc[@for="XmlElementAttributes.Contains"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool Contains(XmlElementAttribute value)
{
return _list.Contains(value);
}
/// <include file='doc\XmlElementAttributes.uex' path='docs/doc[@for="XmlElementAttributes.Remove"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Remove(XmlElementAttribute value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (!_list.Remove(value))
{
throw new ArgumentException(SR.Arg_RemoveArgNotFound);
}
}
/// <include file='doc\XmlElementAttributes.uex' path='docs/doc[@for="XmlElementAttributes.CopyTo"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void CopyTo(XmlElementAttribute[] array, int index)
{
_list.CopyTo(array, index);
}
private IList List
{
get { return _list; }
}
public int Count
{
get
{
return _list == null ? 0 : _list.Count;
}
}
public void Clear()
{
_list.Clear();
}
public void RemoveAt(int index)
{
_list.RemoveAt(index);
}
bool IList.IsReadOnly
{
get { return List.IsReadOnly; }
}
bool IList.IsFixedSize
{
get { return List.IsFixedSize; }
}
bool ICollection.IsSynchronized
{
get { return List.IsSynchronized; }
}
Object ICollection.SyncRoot
{
get { return List.SyncRoot; }
}
void ICollection.CopyTo(Array array, int index)
{
List.CopyTo(array, index);
}
Object IList.this[int index]
{
get
{
return List[index];
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
List[index] = value;
}
}
bool IList.Contains(Object value)
{
return List.Contains(value);
}
int IList.Add(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
return List.Add(value);
}
void IList.Remove(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
var attribute = value as XmlElementAttribute;
if (attribute == null)
{
throw new ArgumentException(SR.Arg_RemoveArgNotFound);
}
Remove(attribute);
}
int IList.IndexOf(Object value)
{
return List.IndexOf(value);
}
void IList.Insert(int index, Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
List.Insert(index, value);
}
public IEnumerator GetEnumerator()
{
return List.GetEnumerator();
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="WinFormsUtils.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms.Layout {
using System;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms.Internal;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Windows.Forms.ComponentModel;
using System.Collections.Generic;
// Utilities used by layout code. If you use these outside of the layout
// namespace, you should probably move them to WindowsFormsUtils.
internal class LayoutUtils {
public static readonly Size MaxSize = new Size(Int32.MaxValue, Int32.MaxValue);
public static readonly Size InvalidSize = new Size(Int32.MinValue, Int32.MinValue);
public static readonly Rectangle MaxRectangle = new Rectangle(0, 0, Int32.MaxValue, Int32.MaxValue);
public const ContentAlignment AnyTop = ContentAlignment.TopLeft | ContentAlignment.TopCenter | ContentAlignment.TopRight;
public const ContentAlignment AnyBottom = ContentAlignment.BottomLeft | ContentAlignment.BottomCenter | ContentAlignment.BottomRight;
public const ContentAlignment AnyLeft = ContentAlignment.TopLeft | ContentAlignment.MiddleLeft | ContentAlignment.BottomLeft;
public const ContentAlignment AnyRight = ContentAlignment.TopRight | ContentAlignment.MiddleRight | ContentAlignment.BottomRight;
public const ContentAlignment AnyCenter = ContentAlignment.TopCenter | ContentAlignment.MiddleCenter | ContentAlignment.BottomCenter;
public const ContentAlignment AnyMiddle = ContentAlignment.MiddleLeft | ContentAlignment.MiddleCenter | ContentAlignment.MiddleRight;
public const AnchorStyles HorizontalAnchorStyles = AnchorStyles.Left | AnchorStyles.Right;
public const AnchorStyles VerticalAnchorStyles = AnchorStyles.Top | AnchorStyles.Bottom;
private static readonly AnchorStyles[] dockingToAnchor = new AnchorStyles[] {
/* None */ AnchorStyles.Top | AnchorStyles.Left,
/* Top */ AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right,
/* Bottom */ AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right,
/* Left */ AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom,
/* Right */ AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom,
/* Fill */ AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left
};
// A good, short test string for measuring control height.
public readonly static string TestString = "j^";
// Returns the size of the largest string in the given collection. Non-string objects are converted
// with ToString(). Uses OldMeasureString, not GDI+. Does not support multiline.
public static Size OldGetLargestStringSizeInCollection(Font font, ICollection objects) {
Size largestSize = Size.Empty;
if (objects != null) {
foreach(object obj in objects) {
Size textSize = TextRenderer.MeasureText(obj.ToString(), font, new Size(Int16.MaxValue, Int16.MaxValue), TextFormatFlags.SingleLine);
largestSize.Width = Math.Max(largestSize.Width, textSize.Width);
largestSize.Height = Math.Max(largestSize.Height, textSize.Height);
}
}
return largestSize;
}
/*
* We can cut ContentAlignment from a max index of 1024 (12b) down to 11 (4b) through
* bit twiddling. The int result of this function maps to the ContentAlignment as indicated
* by the table below:
*
* Left Center Right
* Top 0000 0x0 0001 0x1 0010 0x2
* Middle 0100 0x4 0101 0x5 0110 0x6
* Bottom 1000 0x8 1001 0x9 1010 0xA
*
* (The high 2 bits determine T/M/B. The low 2 bits determine L/C/R.)
*/
public static int ContentAlignmentToIndex(ContentAlignment alignment) {
/*
* Here is what content alignment looks like coming in:
*
* Left Center Right
* Top 0x001 0x002 0x004
* Middle 0x010 0x020 0x040
* Bottom 0x100 0x200 0x400
*
* (L/C/R determined bit 1,2,4. T/M/B determined by 4 bit shift.)
*/
int topBits = xContentAlignmentToIndex(((int)alignment) & 0x0F);
int middleBits = xContentAlignmentToIndex(((int)alignment >> 4) & 0x0F);
int bottomBits = xContentAlignmentToIndex(((int)alignment >> 8) & 0x0F);
Debug.Assert((topBits != 0 && (middleBits == 0 && bottomBits == 0))
|| (middleBits != 0 && (topBits == 0 && bottomBits == 0))
|| (bottomBits != 0 && (topBits == 0 && middleBits == 0)),
"One (and only one) of topBits, middleBits, or bottomBits should be non-zero.");
int result = (middleBits != 0 ? 0x04 : 0) | (bottomBits != 0 ? 0x08 : 0) | topBits | middleBits | bottomBits;
// zero isn't used, so we can subtract 1 and start with index 0.
result --;
Debug.Assert(result >= 0x00 && result <=0x0A, "ContentAlignmentToIndex result out of range.");
Debug.Assert(result != 0x00 || alignment == ContentAlignment.TopLeft, "Error detected in ContentAlignmentToIndex.");
Debug.Assert(result != 0x01 || alignment == ContentAlignment.TopCenter, "Error detected in ContentAlignmentToIndex.");
Debug.Assert(result != 0x02 || alignment == ContentAlignment.TopRight, "Error detected in ContentAlignmentToIndex.");
Debug.Assert(result != 0x03, "Error detected in ContentAlignmentToIndex.");
Debug.Assert(result != 0x04 || alignment == ContentAlignment.MiddleLeft, "Error detected in ContentAlignmentToIndex.");
Debug.Assert(result != 0x05 || alignment == ContentAlignment.MiddleCenter, "Error detected in ContentAlignmentToIndex.");
Debug.Assert(result != 0x06 || alignment == ContentAlignment.MiddleRight, "Error detected in ContentAlignmentToIndex.");
Debug.Assert(result != 0x07, "Error detected in ContentAlignmentToIndex.");
Debug.Assert(result != 0x08 || alignment == ContentAlignment.BottomLeft, "Error detected in ContentAlignmentToIndex.");
Debug.Assert(result != 0x09 || alignment == ContentAlignment.BottomCenter, "Error detected in ContentAlignmentToIndex.");
Debug.Assert(result != 0x0A || alignment == ContentAlignment.BottomRight, "Error detected in ContentAlignmentToIndex.");
return result;
}
// Converts 0x00, 0x01, 0x02, 0x04 (3b flag) to 0, 1, 2, 3 (2b index)
private static byte xContentAlignmentToIndex(int threeBitFlag) {
Debug.Assert(threeBitFlag >= 0x00 && threeBitFlag <= 0x04 && threeBitFlag != 0x03, "threeBitFlag out of range.");
byte result = threeBitFlag == 0x04 ? (byte) 3 : (byte) threeBitFlag;
Debug.Assert((result & 0x03) == result, "Result out of range.");
return result;
}
public static Size ConvertZeroToUnbounded(Size size) {
if(size.Width == 0) size.Width = Int32.MaxValue;
if(size.Height == 0) size.Height = Int32.MaxValue;
return size;
}
// Clamps negative values in Padding struct to zero.
public static Padding ClampNegativePaddingToZero(Padding padding) {
// Careful: Setting the LRTB properties causes Padding.All to be -1 even if LRTB all agree.
if(padding.All < 0) {
padding.Left = Math.Max(0, padding.Left);
padding.Top = Math.Max(0, padding.Top);
padding.Right = Math.Max(0, padding.Right);
padding.Bottom = Math.Max(0, padding.Bottom);
}
return padding;
}
/*
* Maps an anchor to its opposite. Does not support combinations. None returns none.
*
* Top = 0x01
* Bottom = 0x02
* Left = 0x04
* Right = 0x08
*/
// Returns the positive opposite of the given anchor (e.g., L -> R, LT -> RB, LTR -> LBR, etc.). None return none.
private static AnchorStyles GetOppositeAnchor(AnchorStyles anchor) {
AnchorStyles result = AnchorStyles.None;
if (anchor == AnchorStyles.None){
return result;
}
// iterate through T,B,L,R
// bitwise or B,T,R,L as appropriate
for (int i = 1; i <= (int)AnchorStyles.Right; i=i <<1) {
switch (anchor & (AnchorStyles)i) {
case AnchorStyles.None:
break;
case AnchorStyles.Left:
result |= AnchorStyles.Right;
break;
case AnchorStyles.Top:
result |= AnchorStyles.Bottom;
break;
case AnchorStyles.Right:
result |= AnchorStyles.Left;
break;
case AnchorStyles.Bottom:
result |= AnchorStyles.Top;
break;
default:
break;
}
}
return result;
}
public static TextImageRelation GetOppositeTextImageRelation(TextImageRelation relation) {
return (TextImageRelation) GetOppositeAnchor((AnchorStyles)relation);
}
public static Size UnionSizes(Size a, Size b) {
return new Size(
Math.Max(a.Width, b.Width),
Math.Max(a.Height, b.Height));
}
public static Size IntersectSizes(Size a, Size b) {
return new Size(
Math.Min(a.Width, b.Width),
Math.Min(a.Height, b.Height));
}
public static bool IsIntersectHorizontally(Rectangle rect1, Rectangle rect2) {
if (!rect1.IntersectsWith(rect2)) {
return false;
}
if (rect1.X <= rect2.X && rect1.X + rect1.Width >= rect2.X + rect2.Width) {
//rect 1 contains rect 2 horizontally
return true;
}
if (rect2.X <= rect1.X && rect2.X + rect2.Width >= rect1.X + rect1.Width) {
//rect 2 contains rect 1 horizontally
return true;
}
return false;
}
public static bool IsIntersectVertically(Rectangle rect1, Rectangle rect2) {
if (!rect1.IntersectsWith(rect2)) {
return false;
}
if (rect1.Y <= rect2.Y && rect1.Y + rect1.Width >= rect2.Y + rect2.Width) {
//rect 1 contains rect 2 vertically
return true;
}
if (rect2.Y <= rect1.Y && rect2.Y + rect2.Width >= rect1.Y + rect1.Width) {
//rect 2 contains rect 1 vertically
return true;
}
return false;
}
//returns anchorStyles, transforms from DockStyle if necessary
internal static AnchorStyles GetUnifiedAnchor(IArrangedElement element) {
DockStyle dockStyle = DefaultLayout.GetDock(element);
if (dockStyle != DockStyle.None) {
return dockingToAnchor[(int)dockStyle];
}
return DefaultLayout.GetAnchor(element);
}
public static Rectangle AlignAndStretch(Size fitThis, Rectangle withinThis, AnchorStyles anchorStyles) {
return Align(Stretch(fitThis, withinThis.Size, anchorStyles), withinThis, anchorStyles);
}
public static Rectangle Align(Size alignThis, Rectangle withinThis, AnchorStyles anchorStyles) {
return VAlign(alignThis, HAlign(alignThis, withinThis, anchorStyles), anchorStyles);
}
public static Rectangle Align(Size alignThis, Rectangle withinThis, ContentAlignment align) {
return VAlign(alignThis, HAlign(alignThis, withinThis, align), align);
}
public static Rectangle HAlign(Size alignThis, Rectangle withinThis, AnchorStyles anchorStyles) {
if ((anchorStyles & AnchorStyles.Right) != 0) {
withinThis.X += withinThis.Width - alignThis.Width;
}
else if (anchorStyles == AnchorStyles.None || (anchorStyles & HorizontalAnchorStyles) == 0) {
withinThis.X += (withinThis.Width - alignThis.Width) / 2;
}
withinThis.Width = alignThis.Width;
return withinThis;
}
private static Rectangle HAlign(Size alignThis, Rectangle withinThis, ContentAlignment align) {
if ((align & AnyRight) != 0) {
withinThis.X += withinThis.Width - alignThis.Width;
}
else if ((align & AnyCenter) != 0) {
withinThis.X += (withinThis.Width - alignThis.Width) / 2;
}
withinThis.Width = alignThis.Width;
return withinThis;
}
public static Rectangle VAlign(Size alignThis, Rectangle withinThis, AnchorStyles anchorStyles) {
if ((anchorStyles & AnchorStyles.Bottom) != 0) {
withinThis.Y += withinThis.Height - alignThis.Height;
}
else if (anchorStyles == AnchorStyles.None || (anchorStyles & VerticalAnchorStyles) == 0) {
withinThis.Y += (withinThis.Height - alignThis.Height) / 2;
}
withinThis.Height = alignThis.Height;
return withinThis;
}
public static Rectangle VAlign(Size alignThis, Rectangle withinThis, ContentAlignment align) {
if ((align & AnyBottom) != 0) {
withinThis.Y += withinThis.Height - alignThis.Height;
}
else if ((align & AnyMiddle) != 0) {
withinThis.Y += (withinThis.Height - alignThis.Height) / 2;
}
withinThis.Height = alignThis.Height;
return withinThis;
}
public static Size Stretch(Size stretchThis, Size withinThis, AnchorStyles anchorStyles) {
Size stretchedSize = new Size(
(anchorStyles & HorizontalAnchorStyles) == HorizontalAnchorStyles ? withinThis.Width : stretchThis.Width,
(anchorStyles & VerticalAnchorStyles) == VerticalAnchorStyles ? withinThis.Height : stretchThis.Height
);
if (stretchedSize.Width > withinThis.Width) {
stretchedSize.Width = withinThis.Width;
}
if (stretchedSize.Height > withinThis.Height) {
stretchedSize.Height = withinThis.Height;
}
return stretchedSize;
}
public static Rectangle InflateRect(Rectangle rect, Padding padding) {
rect.X -= padding.Left;
rect.Y -= padding.Top;
rect.Width += padding.Horizontal;
rect.Height += padding.Vertical;
return rect;
}
public static Rectangle DeflateRect(Rectangle rect, Padding padding) {
rect.X += padding.Left;
rect.Y += padding.Top;
rect.Width -= padding.Horizontal;
rect.Height -= padding.Vertical;
return rect;
}
public static Size AddAlignedRegion(Size textSize, Size imageSize, TextImageRelation relation) {
return AddAlignedRegionCore(textSize, imageSize, IsVerticalRelation(relation));
}
public static Size AddAlignedRegionCore(Size currentSize, Size contentSize, bool vertical) {
if(vertical) {
currentSize.Width = Math.Max(currentSize.Width, contentSize.Width);
currentSize.Height += contentSize.Height;
} else {
currentSize.Width += contentSize.Width;
currentSize.Height = Math.Max(currentSize.Height, contentSize.Height);
}
return currentSize;
}
public static Padding FlipPadding(Padding padding) {
// If Padding.All != -1, then TLRB are all the same and there is no work to be done.
if(padding.All != -1) {
return padding;
}
// Padding is a stuct (passed by value, no need to make a copy)
int temp;
temp = padding.Top;
padding.Top = padding.Left;
padding.Left = temp;
temp = padding.Bottom;
padding.Bottom = padding.Right;
padding.Right = temp;
return padding;
}
public static Point FlipPoint(Point point) {
// Point is a struct (passed by value, no need to make a copy)
int temp = point.X;
point.X = point.Y;
point.Y = temp;
return point;
}
public static Rectangle FlipRectangle(Rectangle rect) {
// Rectangle is a stuct (passed by value, no need to make a copy)
rect.Location = FlipPoint(rect.Location);
rect.Size = FlipSize(rect.Size);
return rect;
}
public static Rectangle FlipRectangleIf(bool condition, Rectangle rect) {
return condition ? FlipRectangle(rect) : rect;
}
public static Size FlipSize(Size size) {
// Size is a struct (passed by value, no need to make a copy)
int temp = size.Width;
size.Width = size.Height;
size.Height = temp;
return size;
}
public static Size FlipSizeIf(bool condition, Size size) {
return condition ? FlipSize(size) : size;
}
public static bool IsHorizontalAlignment(ContentAlignment align) {
return !IsVerticalAlignment(align);
}
// True if text & image should be lined up horizontally. False if vertical or overlay.
public static bool IsHorizontalRelation(TextImageRelation relation) {
return (relation & (TextImageRelation.TextBeforeImage | TextImageRelation.ImageBeforeText)) != 0;
}
public static bool IsVerticalAlignment(ContentAlignment align) {
Debug.Assert(align != ContentAlignment.MiddleCenter, "Result is ambiguous with an alignment of MiddleCenter.");
return (align & (ContentAlignment.TopCenter | ContentAlignment.BottomCenter)) != 0;
}
// True if text & image should be lined up vertically. False if horizontal or overlay.
public static bool IsVerticalRelation(TextImageRelation relation) {
return (relation & (TextImageRelation.TextAboveImage | TextImageRelation.ImageAboveText)) != 0;
}
public static bool IsZeroWidthOrHeight(Rectangle rectangle) {
return (rectangle.Width == 0 || rectangle.Height == 0);
}
public static bool IsZeroWidthOrHeight(Size size) {
return (size.Width == 0 || size.Height == 0);
}
public static bool AreWidthAndHeightLarger(Size size1, Size size2){
return ((size1.Width >= size2.Width) && (size1.Height >= size2.Height));
}
public static void SplitRegion(Rectangle bounds, Size specifiedContent, AnchorStyles region1Align, out Rectangle region1, out Rectangle region2) {
region1 = region2 = bounds;
switch(region1Align) {
case AnchorStyles.Left:
region1.Width = specifiedContent.Width;
region2.X += specifiedContent.Width;
region2.Width -= specifiedContent.Width;
break;
case AnchorStyles.Right:
region1.X += bounds.Width - specifiedContent.Width;
region1.Width = specifiedContent.Width;
region2.Width -= specifiedContent.Width;
break;
case AnchorStyles.Top:
region1.Height = specifiedContent.Height;
region2.Y += specifiedContent.Height;
region2.Height -= specifiedContent.Height;
break;
case AnchorStyles.Bottom:
region1.Y += bounds.Height - specifiedContent.Height;
region1.Height = specifiedContent.Height;
region2.Height -= specifiedContent.Height;
break;
default:
Debug.Fail("Unsupported value for region1Align.");
break;
}
Debug.Assert(Rectangle.Union(region1, region2) == bounds,
"Regions do not add up to bounds.");
}
// Expands adjacent regions to bounds. region1Align indicates which way the adjacency occurs.
public static void ExpandRegionsToFillBounds(Rectangle bounds, AnchorStyles region1Align, ref Rectangle region1, ref Rectangle region2) {
switch(region1Align) {
case AnchorStyles.Left:
Debug.Assert(region1.Right == region2.Left, "Adjacency error.");
region1 = SubstituteSpecifiedBounds(bounds, region1, AnchorStyles.Right);
region2 = SubstituteSpecifiedBounds(bounds, region2, AnchorStyles.Left);
break;
case AnchorStyles.Right:
Debug.Assert(region2.Right == region1.Left, "Adjacency error.");
region1 = SubstituteSpecifiedBounds(bounds, region1, AnchorStyles.Left);
region2 = SubstituteSpecifiedBounds(bounds, region2, AnchorStyles.Right);
break;
case AnchorStyles.Top:
Debug.Assert(region1.Bottom == region2.Top, "Adjacency error.");
region1 = SubstituteSpecifiedBounds(bounds, region1, AnchorStyles.Bottom);
region2 = SubstituteSpecifiedBounds(bounds, region2, AnchorStyles.Top);
break;
case AnchorStyles.Bottom:
Debug.Assert(region2.Bottom == region1.Top, "Adjacency error.");
region1 = SubstituteSpecifiedBounds(bounds, region1, AnchorStyles.Top);
region2 = SubstituteSpecifiedBounds(bounds, region2, AnchorStyles.Bottom);
break;
default:
Debug.Fail("Unsupported value for region1Align.");
break;
}
Debug.Assert(Rectangle.Union(region1, region2) == bounds, "region1 and region2 do not add up to bounds.");
}
public static Size SubAlignedRegion(Size currentSize, Size contentSize, TextImageRelation relation) {
return SubAlignedRegionCore(currentSize, contentSize, IsVerticalRelation(relation));
}
public static Size SubAlignedRegionCore(Size currentSize, Size contentSize, bool vertical) {
if(vertical) {
currentSize.Height -= contentSize.Height;
} else {
currentSize.Width -= contentSize.Width;
}
return currentSize;
}
private static Rectangle SubstituteSpecifiedBounds(Rectangle originalBounds, Rectangle substitutionBounds, AnchorStyles specified) {
int left = (specified & AnchorStyles.Left) != 0 ? substitutionBounds.Left : originalBounds.Left;
int top = (specified & AnchorStyles.Top) != 0 ? substitutionBounds.Top : originalBounds.Top;
int right = (specified & AnchorStyles.Right) != 0 ? substitutionBounds.Right : originalBounds.Right;
int bottom = (specified & AnchorStyles.Bottom) != 0 ? substitutionBounds.Bottom : originalBounds.Bottom;
return Rectangle.FromLTRB(left, top, right, bottom);
}
// given a rectangle, flip to the other side of (withinBounds)
//
// Never call this if you derive from ScrollableControl
public static Rectangle RTLTranslate(Rectangle bounds, Rectangle withinBounds) {
bounds.X = withinBounds.Width - bounds.Right;
return bounds;
}
/// MeasureTextCache
/// Cache mechanism added for VSWhidbey 500516
/// 3000 character strings take 9 seconds to load the form
public sealed class MeasureTextCache {
private Size unconstrainedPreferredSize = LayoutUtils.InvalidSize;
private const int MaxCacheSize = 6; // the number of preferred sizes to store
private int nextCacheEntry = -1; // the next place in the ring buffer to store a preferred size
private PreferredSizeCache[] sizeCacheList; // MRU of size MaxCacheSize
/// InvalidateCache
/// Clears out the cached values, should be called whenever Text, Font or a TextFormatFlag has changed
public void InvalidateCache() {
unconstrainedPreferredSize = LayoutUtils.InvalidSize;
sizeCacheList = null;
}
/// GetTextSize
/// Given constraints, format flags a font and text, determine the size of the string
/// employs an MRU of the last several constraints passed in via a ring-buffer of size MaxCacheSize.
/// Assumes Text and TextFormatFlags are the same, if either were to change, a call to
/// InvalidateCache should be made
public Size GetTextSize(string text, Font font, Size proposedConstraints, TextFormatFlags flags) {
if (!TextRequiresWordBreak(text, font, proposedConstraints, flags)) {
// Text fits within proposed width
// IF we're here, this means we've got text that can fit into the proposedConstraints
// without wrapping. We've determined this because our
// as a side effect of calling TextRequiresWordBreak,
// unconstrainedPreferredSize is set.
return unconstrainedPreferredSize;
}
else {
// Text does NOT fit within proposed width - requires WordBreak
// IF we're here, this means that the wrapping width is smaller
// than our max width. For example: we measure the text with infinite
// bounding box and we determine the width to fit all the characters
// to be 200 px wide. We would come here only for proposed widths less
// than 200 px.
// Create our ring buffer if we dont have one
if (sizeCacheList == null) {
sizeCacheList = new PreferredSizeCache[MaxCacheSize];
}
// check the existing constraints from previous calls
foreach (PreferredSizeCache sizeCache in sizeCacheList) {
if (sizeCache.ConstrainingSize == proposedConstraints) {
return sizeCache.PreferredSize;
}
else if ((sizeCache.ConstrainingSize.Width == proposedConstraints.Width)
&& (sizeCache.PreferredSize.Height <= proposedConstraints.Height)) {
// Caching a common case where the width matches perfectly, and the stored preferred height
// is smaller or equal to the constraining size.
// prefSize = GetPreferredSize(w,Int32.MaxValue);
// prefSize = GetPreferredSize(w,prefSize.Height);
return sizeCache.PreferredSize;
}
//
}
// if we've gotten here, it means we dont have a cache entry, therefore
// we should add a new one in the next available slot.
Size prefSize = TextRenderer.MeasureText(text, font, proposedConstraints, flags);
nextCacheEntry = (nextCacheEntry+1)%MaxCacheSize;
sizeCacheList[nextCacheEntry] = new PreferredSizeCache(proposedConstraints, prefSize);
return prefSize;
}
}
/// GetUnconstrainedSize
/// Gets the unconstrained (Int32.MaxValue, Int32.MaxValue) size for a piece of text
private Size GetUnconstrainedSize(string text, Font font, TextFormatFlags flags) {
if (unconstrainedPreferredSize == LayoutUtils.InvalidSize) {
// we also investigated setting the SingleLine flag, however this did not yield as much benefit as the word break
// and had possibility of causing internationalization issues.
flags = (flags & ~TextFormatFlags.WordBreak); // rip out the wordbreak flag
unconstrainedPreferredSize = TextRenderer.MeasureText(text, font, LayoutUtils.MaxSize, flags);
}
return unconstrainedPreferredSize;
}
/// TextRequiresWordBreak
/// If you give the text all the space in the world it wants, then there should be no reason
/// for it to break on a word. So we find out what the unconstrained size is (Int32.MaxValue, Int32.MaxValue)
/// for a string - eg. 35, 13. If the size passed in has a larger width than 35, then we know that
/// the WordBreak flag is not necessary.
public bool TextRequiresWordBreak(string text, Font font, Size size, TextFormatFlags flags) {
// if the unconstrained size of the string is larger than the proposed width
// we need the word break flag, otherwise we dont, its a perf hit to use it.
return GetUnconstrainedSize(text, font, flags).Width > size.Width;
}
private struct PreferredSizeCache {
public PreferredSizeCache(Size constrainingSize, Size preferredSize) {
this.ConstrainingSize = constrainingSize;
this.PreferredSize = preferredSize;
}
public Size ConstrainingSize;
public Size PreferredSize;
}
}
}
// Frequently when you need to do a PreformLayout, you also need to invalidate the
// PreferredSizeCache (you are laying out because you know that the action has changed
// the PreferredSize of the control and/or its container). LayoutTransaction wraps both
// of these operations into one, plus adds a check for null to make our code more
// concise.
//
// Usage1: (When we are not calling to other code which may cause a layout:)
//
// LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Bounds);
//
// Usage2: (When we need to wrap code which may cause additional layouts:)
//
// using(new LayoutTransaction(ParentInternal, this, PropertyNames.Bounds)) {
// OnBoundsChanged();
// }
//
// The second usage spins off 12b for garbage collection, but I did some profiling and
// it didn't seem significant (we were spinning off more from LayoutEventArgs.)
internal sealed class LayoutTransaction : IDisposable {
Control _controlToLayout;
bool _resumeLayout;
#if DEBUG
int _layoutSuspendCount;
#endif
public LayoutTransaction(Control controlToLayout, IArrangedElement controlCausingLayout, string property) :
this(controlToLayout, controlCausingLayout, property, true) {
}
public LayoutTransaction(Control controlToLayout, IArrangedElement controlCausingLayout, string property, bool resumeLayout) {
CommonProperties.xClearPreferredSizeCache(controlCausingLayout);
_controlToLayout = controlToLayout;
_resumeLayout = resumeLayout;
if(_controlToLayout != null) {
#if DEBUG
_layoutSuspendCount = _controlToLayout.LayoutSuspendCount;
#endif
_controlToLayout.SuspendLayout();
CommonProperties.xClearPreferredSizeCache(_controlToLayout);
// Same effect as calling performLayout on Dispose but then we would have to keep
// controlCausingLayout and property around as state.
if (resumeLayout) {
_controlToLayout.PerformLayout(new LayoutEventArgs(controlCausingLayout, property));
}
}
}
public void Dispose() {
if(_controlToLayout != null) {
_controlToLayout.ResumeLayout(_resumeLayout);
#if DEBUG
Debug.Assert(_controlToLayout.LayoutSuspendCount == _layoutSuspendCount, "Suspend/Resume layout mismatch!");
#endif
}
}
// This overload should be used when a property has changed that affects preferred size,
// but you only want to layout if a certain condition exists (say you want to layout your
// parent because your preferred size has changed).
public static IDisposable CreateTransactionIf(bool condition, Control controlToLayout, IArrangedElement elementCausingLayout, string property) {
if (condition) {
return new LayoutTransaction(controlToLayout, elementCausingLayout, property);
}
else {
CommonProperties.xClearPreferredSizeCache(elementCausingLayout);
return new NullLayoutTransaction();
}
}
public static void DoLayout(IArrangedElement elementToLayout, IArrangedElement elementCausingLayout, string property) {
if (elementCausingLayout != null) {
CommonProperties.xClearPreferredSizeCache(elementCausingLayout);
if(elementToLayout != null) {
CommonProperties.xClearPreferredSizeCache(elementToLayout);
elementToLayout.PerformLayout(elementCausingLayout, property);
}
}
Debug.Assert(elementCausingLayout != null, "LayoutTransaction.DoLayout - elementCausingLayout is null, no layout performed - did you mix up your parameters?");
}
// This overload should be used when a property has changed that affects preferred size,
// but you only want to layout if a certain condition exists (say you want to layout your
// parent because your preferred size has changed).
public static void DoLayoutIf(bool condition, IArrangedElement elementToLayout, IArrangedElement elementCausingLayout, string property) {
if (!condition) {
if (elementCausingLayout != null) {
CommonProperties.xClearPreferredSizeCache(elementCausingLayout);
}
}
else {
LayoutTransaction.DoLayout(elementToLayout, elementCausingLayout, property);
}
}
}
internal struct NullLayoutTransaction : IDisposable {
public void Dispose() {
}
}
}
| |
// 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 FloorSingle()
{
var test = new SimpleUnaryOpTest__FloorSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__FloorSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Single> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__FloorSingle testClass)
{
var result = Avx.Floor(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__FloorSingle testClass)
{
fixed (Vector256<Single>* pFld1 = &_fld1)
{
var result = Avx.Floor(
Avx.LoadVector256((Single*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Vector256<Single> _clsVar1;
private Vector256<Single> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__FloorSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
}
public SimpleUnaryOpTest__FloorSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.Floor(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.Floor(
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.Floor(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.Floor), new Type[] { typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.Floor), new Type[] { typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.Floor), new Type[] { typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.Floor(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Single>* pClsVar1 = &_clsVar1)
{
var result = Avx.Floor(
Avx.LoadVector256((Single*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var result = Avx.Floor(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr));
var result = Avx.Floor(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr));
var result = Avx.Floor(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__FloorSingle();
var result = Avx.Floor(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__FloorSingle();
fixed (Vector256<Single>* pFld1 = &test._fld1)
{
var result = Avx.Floor(
Avx.LoadVector256((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.Floor(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Single>* pFld1 = &_fld1)
{
var result = Avx.Floor(
Avx.LoadVector256((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.Floor(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.Floor(
Avx.LoadVector256((Single*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Single> op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Floor(firstOp[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(MathF.Floor(firstOp[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Floor)}<Single>(Vector256<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
#if NET_2_0
#region License
/*
* Copyright 2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Transactions;
using Spring.Data.Support;
using Spring.Objects.Factory;
using Spring.Transaction;
using Spring.Transaction.Support;
namespace Spring.Data.Core
{
/// <summary>
/// TransactionManager that uses TransactionScope provided by System.Transactions.
/// </summary>
/// <author>Mark Pollack (.NET)</author>
public class TxScopeTransactionManager : AbstractPlatformTransactionManager, IInitializingObject
{
private readonly ITransactionScopeAdapter txAdapter;
/// <summary>
/// Initializes a new instance of the <see cref="TxScopeTransactionManager"/> class.
/// </summary>
public TxScopeTransactionManager()
{
// noop
}
/// <summary>
/// Initializes a new instance of the <see cref="TxScopeTransactionManager"/> class.
/// </summary>
/// <remarks>This is indented only for unit testing purposes and should not be
/// called by production application code.</remarks>
/// <param name="txAdapter">The tx adapter.</param>
public TxScopeTransactionManager(ITransactionScopeAdapter txAdapter)
{
this.txAdapter = txAdapter;
}
#region IInitializingObject Members
/// <summary>
/// No-op initialization
/// </summary>
public void AfterPropertiesSet()
{
// placeholder for more advanced configurations.
}
#endregion
protected override object DoGetTransaction()
{
PromotableTxScopeTransactionObject txObject = new PromotableTxScopeTransactionObject();
if (txAdapter != null)
{
txObject.TxScopeAdapter = txAdapter;
}
return txObject;
}
protected override bool IsExistingTransaction(object transaction)
{
PromotableTxScopeTransactionObject txObject =
(PromotableTxScopeTransactionObject)transaction;
return txObject.TxScopeAdapter.IsExistingTransaction;
}
protected override void DoBegin(object transaction, Spring.Transaction.ITransactionDefinition definition)
{
PromotableTxScopeTransactionObject txObject =
(PromotableTxScopeTransactionObject)transaction;
try
{
DoTxScopeBegin(txObject, definition);
}
catch (Exception e)
{
throw new CannotCreateTransactionException("Transaction Scope failure on begin", e);
}
}
protected override object DoSuspend(object transaction)
{
// Passing the current TxScopeAdapter as the 'suspended resource', even though it is not used just to avoid passing null
// TxScopeTransactionManager is not binding any resources to the local thread, instead delegating to
// System.Transactions to handle thread local resources.
PromotableTxScopeTransactionObject txMgrStateObject = (PromotableTxScopeTransactionObject) transaction;
return txMgrStateObject.TxScopeAdapter;
}
protected override void DoResume(object transaction, object suspendedResources)
{
}
protected override void DoCommit(DefaultTransactionStatus status)
{
PromotableTxScopeTransactionObject txObject =
(PromotableTxScopeTransactionObject)status.Transaction;
try
{
txObject.TxScopeAdapter.Complete();
txObject.TxScopeAdapter.Dispose();
}
catch (TransactionAbortedException ex)
{
throw new UnexpectedRollbackException("Transaction unexpectedly rolled back (maybe due to a timeout)", ex);
}
catch (TransactionInDoubtException ex)
{
throw new HeuristicCompletionException(TransactionOutcomeState.Unknown, ex);
}
catch (Exception ex)
{
throw new TransactionSystemException("Failure on Transaction Scope Commit", ex);
}
}
protected override void DoRollback(DefaultTransactionStatus status)
{
PromotableTxScopeTransactionObject txObject =
(PromotableTxScopeTransactionObject)status.Transaction;
try
{
txObject.TxScopeAdapter.Dispose();
}
catch (Exception e)
{
throw new Spring.Transaction.TransactionSystemException("Failure on Transaction Scope rollback.", e);
}
}
protected override void DoSetRollbackOnly(DefaultTransactionStatus status)
{
if (status.Debug)
{
log.Debug("Setting transaction rollback-only");
}
try
{
System.Transactions.Transaction.Current.Rollback();
} catch (Exception ex)
{
throw new TransactionSystemException("Failure on System.Transactions.Transaction.Current.Rollback", ex);
}
}
protected override bool ShouldCommitOnGlobalRollbackOnly
{
get { return true; }
}
private void DoTxScopeBegin(PromotableTxScopeTransactionObject txObject,
Spring.Transaction.ITransactionDefinition definition)
{
TransactionScopeOption txScopeOption = CreateTransactionScopeOptions(definition);
TransactionOptions txOptions = CreateTransactionOptions(definition);
txObject.TxScopeAdapter.CreateTransactionScope(txScopeOption, txOptions, definition.EnterpriseServicesInteropOption);
}
private static TransactionOptions CreateTransactionOptions(ITransactionDefinition definition)
{
TransactionOptions txOptions = new TransactionOptions();
switch (definition.TransactionIsolationLevel )
{
case System.Data.IsolationLevel.Chaos:
txOptions.IsolationLevel = IsolationLevel.Chaos;
break;
case System.Data.IsolationLevel.ReadCommitted:
txOptions.IsolationLevel = IsolationLevel.ReadCommitted;
break;
case System.Data.IsolationLevel.ReadUncommitted:
txOptions.IsolationLevel = IsolationLevel.ReadUncommitted;
break;
case System.Data.IsolationLevel.RepeatableRead:
txOptions.IsolationLevel = IsolationLevel.RepeatableRead;
break;
case System.Data.IsolationLevel.Serializable:
txOptions.IsolationLevel = IsolationLevel.Serializable;
break;
case System.Data.IsolationLevel.Snapshot:
txOptions.IsolationLevel = IsolationLevel.Snapshot;
break;
case System.Data.IsolationLevel.Unspecified:
txOptions.IsolationLevel = IsolationLevel.Unspecified;
break;
}
if (definition.TransactionTimeout != DefaultTransactionDefinition.TIMEOUT_DEFAULT)
{
txOptions.Timeout = new TimeSpan(0, 0, definition.TransactionTimeout);
}
return txOptions;
}
private static TransactionScopeOption CreateTransactionScopeOptions(ITransactionDefinition definition)
{
TransactionScopeOption txScopeOption;
if (definition.PropagationBehavior == TransactionPropagation.Required)
{
txScopeOption = TransactionScopeOption.Required;
}
else if (definition.PropagationBehavior == TransactionPropagation.RequiresNew)
{
txScopeOption = TransactionScopeOption.RequiresNew;
}
else if (definition.PropagationBehavior == TransactionPropagation.NotSupported)
{
txScopeOption = TransactionScopeOption.Suppress;
}
else
{
throw new Spring.Transaction.TransactionSystemException("Transaction Propagation Behavior" +
definition.PropagationBehavior +
" not supported by TransactionScope. Use Required or RequiredNew");
}
return txScopeOption;
}
/// <summary>
/// The transaction resource object that encapsulates the state and functionality
/// contained in TransactionScope and Transaction.Current via the ITransactionScopeAdapter
/// property.
/// </summary>
public class PromotableTxScopeTransactionObject : ISmartTransactionObject
{
private ITransactionScopeAdapter txScopeAdapter;
/// <summary>
/// Initializes a new instance of the <see cref="PromotableTxScopeTransactionObject"/> class.
/// Will create an instance of <see cref="DefaultTransactionScopeAdapter"/>.
/// </summary>
public PromotableTxScopeTransactionObject()
{
txScopeAdapter = new DefaultTransactionScopeAdapter();
}
/// <summary>
/// Gets or sets the transaction scope adapter.
/// </summary>
/// <value>The transaction scope adapter.</value>
public ITransactionScopeAdapter TxScopeAdapter
{
get { return txScopeAdapter; }
set { txScopeAdapter = value; }
}
/// <summary>
/// Return whether the transaction is internally marked as rollback-only.
/// </summary>
/// <value></value>
/// <returns>True of the transaction is marked as rollback-only.</returns>
public bool RollbackOnly
{
get {
return txScopeAdapter.RollbackOnly;
}
}
}
}
}
#endif
| |
using System;
using BizHawk.Common.NumberExtensions;
namespace BizHawk.Emulation.Common.Components.MC6800
{
public partial class MC6800
{
// this contains the vectors of instrcution operations
// NOTE: This list is NOT confirmed accurate for each individual cycle
private void NOP_()
{
PopulateCURINSTR(IDLE);
IRQS = 1;
}
private void ILLEGAL()
{
//throw new Exception("Encountered illegal instruction");
PopulateCURINSTR(IDLE);
IRQS = 1;
}
private void REG_OP(ushort oper, ushort src)
{
PopulateCURINSTR(oper, src);
IRQS = 1;
}
private void REG_OP_16(ushort oper, ushort src)
{
PopulateCURINSTR(IDLE,
IDLE,
oper, src);
IRQS = 3;
}
private void DIRECT_MEM(ushort oper)
{
PopulateCURINSTR(RD_INC, ALU, PC,
SET_ADDR, ADDR, DP, ALU,
RD, ALU, ADDR,
oper, ALU,
WR, ADDR, ALU);
IRQS = 5;
}
private void DIRECT_ST_4(ushort dest)
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, SET_ADDR, ADDR, DP, ALU,
IDLE,
WR, ADDR, dest);
IRQS = 3;
}
private void DIRECT_MEM_4(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, SET_ADDR, ADDR, DP, ALU,
IDLE,
RD_INC_OP, ALU, ADDR, oper, dest, ALU);
IRQS = 3;
}
private void EXT_MEM(ushort oper)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC, ALU2, PC,
SET_ADDR, ADDR, ALU, ALU2,
RD, ALU, ADDR,
oper, ALU,
WR, ADDR, ALU);
IRQS = 6;
}
private void EXT_REG(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
RD, ALU, ADDR,
oper, dest, ALU);
IRQS = 4;
}
private void EXT_ST(ushort dest)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
IDLE,
WR, ADDR, dest);
IRQS = 4;
}
private void REG_OP_IMD(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, oper, dest, ALU);
IRQS = 1;
}
private void DIR_CMP_16(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, SET_ADDR, ADDR, DP, ALU,
RD_INC, ALU, ADDR,
RD, ALU2, ADDR,
SET_ADDR, ADDR, ALU, ALU2,
oper, dest, ADDR);
IRQS = 5;
}
private void IMD_CMP_16(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
oper, dest, ADDR);
IRQS = 3;
}
private void REG_OP_LD_16(ushort dest)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, LD_16, dest, ALU, ALU2);
IRQS = 2;
}
private void DIR_OP_LD_16(ushort dest)
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, SET_ADDR, ADDR, DP, ALU,
IDLE,
RD_INC, ALU, ADDR,
RD_INC_OP, ALU2, ADDR, LD_16, dest, ALU, ALU2);
IRQS = 4;
}
private void DIR_OP_ST_16(ushort src)
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, SET_ADDR, ADDR, DP, ALU,
IDLE,
WR_HI_INC, ADDR, src,
WR_DEC_LO, ADDR, src);
IRQS = 4;
}
private void EXT_OP_LD_16(ushort dest)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
RD_INC, ALU, ADDR,
RD_INC_OP, ALU2, ADDR, LD_16, dest, ALU, ALU2);
IRQS = 4;
}
private void EXT_OP_ST_16(ushort src)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC, ALU2, PC,
SET_ADDR, ADDR, ALU, ALU2,
WR_HI_INC, ADDR, src,
WR_DEC_LO, ADDR, src);
IRQS = 5;
}
private void EXT_CMP_16(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
RD_INC, ALU, ADDR,
RD, ALU2, ADDR,
SET_ADDR, ADDR, ALU, ALU2,
oper, dest, ADDR);
IRQS = 6;
}
private void JMP_EXT_()
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC, ALU2, PC,
SET_ADDR, PC, ALU, ALU2);
IRQS = 3;
}
private void JSR_EXT()
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC, ALU2, PC,
SET_ADDR, ADDR, ALU, ALU2,
TR, ALU, PC,
IDLE,
TR, PC, ADDR,
WR_DEC_LO, SP, ALU,
WR_DEC_HI, SP, ALU);
IRQS = 8;
}
private void BR_(bool cond)
{
if (cond)
{
PopulateCURINSTR(RD_INC, ALU, PC,
ADD8BR, PC, ALU);
IRQS = 2;
}
else
{
PopulateCURINSTR(RD_INC, ALU, PC,
IDLE);
IRQS = 2;
}
}
private void BSR_()
{
PopulateCURINSTR(RD_INC, ALU, PC,
TR, ADDR, PC,
ADD8BR, PC, ALU,
IDLE,
IDLE,
WR_DEC_LO, SP, ADDR,
WR_DEC_HI, SP, ADDR);
IRQS = 7;
}
private void RTS()
{
PopulateCURINSTR(INC16, SP,
RD_INC, ALU, SP,
RD, ALU2, SP,
SET_ADDR, PC, ALU, ALU2);
IRQS = 4;
}
private void RTI()
{
PopulateCURINSTR(INC16, SP,
RD_INC, CC, SP,
RD_INC, B, SP,
RD_INC, A, SP,
RD_INC, ALU, SP,
RD_INC_OP, ALU2, SP, SET_ADDR, X, ALU, ALU2,
RD_INC, ALU, SP,
RD, ALU2, SP,
SET_ADDR, PC, ALU, ALU2);
IRQS = 9;
}
private void PSH_(ushort src)
{
PopulateCURINSTR(WR, SP, src,
IDLE,
DEC16, SP);
IRQS = 3;
}
private void PUL_(ushort src)
{
PopulateCURINSTR(INC16, SP,
IDLE,
RD, src, SP);
IRQS = 3;
}
private void SWI1()
{
Regs[ADDR] = 0xFFFA;
PopulateCURINSTR(IDLE,
WR_DEC_LO, SP, PC,
WR_DEC_HI, SP, PC,
WR_DEC_LO, SP, X,
WR_DEC_HI, SP, X,
WR_DEC_LO, SP, A,
WR_DEC_LO, SP, B,
WR_DEC_LO, SP, CC,
SET_I,
RD_INC, ALU, ADDR,
RD_INC_OP, ALU2, ADDR, SET_ADDR, PC, ALU, ALU2);
IRQS = 11;
}
private void WAI_()
{
PopulateCURINSTR(WR_DEC_LO, SP, PC,
WR_DEC_HI, SP, PC,
WR_DEC_LO, SP, X,
WR_DEC_HI, SP, X,
WR_DEC_LO, SP, A,
WR_DEC_LO, SP, B,
WR_DEC_LO, SP, CC,
WAI);
IRQS = 8;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Compute;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute
{
/// <summary>
/// The Compute Management API includes operations for managing the dns
/// servers for your subscription.
/// </summary>
internal partial class DNSServerOperations : IServiceOperations<ComputeManagementClient>, IDNSServerOperations
{
/// <summary>
/// Initializes a new instance of the DNSServerOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DNSServerOperations(ComputeManagementClient client)
{
this._client = client;
}
private ComputeManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient.
/// </summary>
public ComputeManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Add a definition for a DNS server to an existing deployment. VM's
/// in this deployment will be programmed to use this DNS server for
/// all DNS resolutions
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Add DNS Server operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> AddDNSServerAsync(string serviceName, string deploymentName, DNSAddParameters parameters, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "AddDNSServerAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.DnsServer.BeginAddingDNSServerAsync(serviceName, deploymentName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// Add a definition for a DNS server to an existing deployment. VM's
/// in this deployment will be programmed to use this DNS server for
/// all DNS resolutions
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Add DNS Server operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginAddingDNSServerAsync(string serviceName, string deploymentName, DNSAddParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginAddingDNSServerAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/dnsservers";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-09-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement dnsServerElement = new XElement(XName.Get("DnsServer", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(dnsServerElement);
if (parameters.Name != null)
{
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = parameters.Name;
dnsServerElement.Add(nameElement);
}
if (parameters.Address != null)
{
XElement addressElement = new XElement(XName.Get("Address", "http://schemas.microsoft.com/windowsazure"));
addressElement.Value = parameters.Address;
dnsServerElement.Add(addressElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes a definition for an existing DNS server from the deployment
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginDeletingDNSServerAsync(string serviceName, string deploymentName, string dnsServerName, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (dnsServerName == null)
{
throw new ArgumentNullException("dnsServerName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("dnsServerName", dnsServerName);
TracingAdapter.Enter(invocationId, this, "BeginDeletingDNSServerAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/dnsservers/";
url = url + Uri.EscapeDataString(dnsServerName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-09-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Updates a definition for an existing DNS server. Updates to address
/// is the only change allowed. DNS server name cannot be changed
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update DNS Server operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginUpdatingDNSServerAsync(string serviceName, string deploymentName, string dnsServerName, DNSUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (dnsServerName == null)
{
throw new ArgumentNullException("dnsServerName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("dnsServerName", dnsServerName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginUpdatingDNSServerAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/dnsservers/";
url = url + Uri.EscapeDataString(dnsServerName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-09-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement dnsServerElement = new XElement(XName.Get("DnsServer", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(dnsServerElement);
if (parameters.Name != null)
{
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = parameters.Name;
dnsServerElement.Add(nameElement);
}
if (parameters.Address != null)
{
XElement addressElement = new XElement(XName.Get("Address", "http://schemas.microsoft.com/windowsazure"));
addressElement.Value = parameters.Address;
dnsServerElement.Add(addressElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes a definition for an existing DNS server from the deployment
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> DeleteDNSServerAsync(string serviceName, string deploymentName, string dnsServerName, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("dnsServerName", dnsServerName);
TracingAdapter.Enter(invocationId, this, "DeleteDNSServerAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.DnsServer.BeginDeletingDNSServerAsync(serviceName, deploymentName, dnsServerName, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// Updates a definition for an existing DNS server. Updates to address
/// is the only change allowed. DNS server name cannot be changed
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update DNS Server operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> UpdateDNSServerAsync(string serviceName, string deploymentName, string dnsServerName, DNSUpdateParameters parameters, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("dnsServerName", dnsServerName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "UpdateDNSServerAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.DnsServer.BeginUpdatingDNSServerAsync(serviceName, deploymentName, dnsServerName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
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
*/
#endregion
using System;
using System.Collections;
using System.Diagnostics;
using Axiom.Collections;
using Axiom.Core;
using Axiom.Graphics;
namespace Axiom.Graphics
{
/// <summary>
/// A grouping level underneath RenderQueue which groups renderables
/// to be issued at coarsely the same time to the renderer.
/// </summary>
/// <remarks>
/// Each instance of this class itself hold RenderPriorityGroup instances,
/// which are the groupings of renderables by priority for fine control
/// of ordering (not required for most instances).
/// </remarks>
public class RenderQueueGroup
{
#region Fields
/// <summary>
/// Render queue that this queue group belongs to.
/// </summary>
protected RenderQueue parent;
/// <summary>
/// Should passes be split by their lighting stage?
/// </summary>
protected bool splitPassesByLightingType;
protected bool splitNoShadowPasses;
protected bool shadowCastersCannotBeReceivers;
/// <summary>
/// List of priority groups.
/// </summary>
protected HashList priorityGroups = new HashList();
/// <summary>
/// Are shadows enabled for this group?
/// </summary>
protected bool shadowsEnabled;
#endregion Fields
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="parent">Render queue that owns this group.</param>
/// <param name="splitPassesByLightingType">Split passes based on lighting stage?</param>
/// <param name="splitNoShadowPasses"></param>
public RenderQueueGroup(RenderQueue parent, bool splitPassesByLightingType,
bool splitNoShadowPasses, bool shadowCastersCannotBeReceivers)
{
// shadows enabled by default
shadowsEnabled = true;
this.splitPassesByLightingType = splitPassesByLightingType;
this.splitNoShadowPasses = splitNoShadowPasses;
this.shadowCastersCannotBeReceivers = shadowCastersCannotBeReceivers;
this.parent = parent;
}
#endregion
#region Methods
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <param name="priority"></param>
public void AddRenderable(IRenderable item, ushort priority)
{
RenderPriorityGroup group = null;
// see if there is a current queue group for this group id
if(!priorityGroups.ContainsKey(priority))
{
// create a new queue group for this group id
group = new RenderPriorityGroup(splitPassesByLightingType, splitNoShadowPasses,
splitPassesByLightingType);
// add the new group to cached render group
priorityGroups.Add(priority, group);
}
else
{
// retreive the existing queue group
group = (RenderPriorityGroup)priorityGroups.GetByKey(priority);
}
// add the renderable to the appropriate group
group.AddRenderable(item);
}
/// <summary>
/// Clears all the priority groups within this group.
/// </summary>
public void Clear()
{
// loop through each priority group and clear it's items. We don't wanna clear the group
// list because it probably won't change frame by frame.
for(int i = 0; i < priorityGroups.Count; i++)
{
RenderPriorityGroup group = (RenderPriorityGroup)priorityGroups[i];
// clear the RenderPriorityGroup
group.Clear();
}
}
/// <summary>
/// Gets the hashlist entry for the priority group at the specified index.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public RenderPriorityGroup GetPriorityGroup(int index)
{
Debug.Assert(index < priorityGroups.Count, "index < priorityGroups.Count");
return (RenderPriorityGroup)priorityGroups[index];
}
#endregion
#region Properties
/// <summary>
/// Gets the number of priority groups within this queue group.
/// </summary>
public int NumPriorityGroups
{
get
{
return priorityGroups.Count;
}
}
/// <summary>
/// Indicate whether a given queue group will be doing any shadow setup.
/// </summary>
/// <remarks>
/// This method allows you to inform the queue about a queue group, and to
/// indicate whether this group will require shadow processing of any sort.
/// In order to preserve rendering order, Axiom/Ogre has to treat queue groups
/// as very separate elements of the scene, and this can result in it
/// having to duplicate shadow setup for each group. Therefore, if you
/// know that a group which you are using will never need shadows, you
/// should preregister the group using this method in order to improve
/// the performance.
/// </remarks>
public bool ShadowsEnabled
{
get
{
return shadowsEnabled;
}
set
{
shadowsEnabled = value;
}
}
/// <summary>
/// Gets/Sets whether or not the queue will split passes by their lighting type,
/// ie ambient, per-light and decal.
/// </summary>
public bool SplitPassesByLightingType
{
get
{
return splitPassesByLightingType;
}
set
{
splitPassesByLightingType = value;
// set the value for all priority groups as well
for(int i = 0; i < priorityGroups.Count; i++)
{
GetPriorityGroup(i).SplitPassesByLightingType = splitPassesByLightingType;
}
}
}
/// <summary>
/// Gets/Sets whether or not the queue will split passes which have shadow receive
/// turned off (in their parent material), which is needed when certain shadow
/// techniques are used.
/// </summary>
public bool SplitNoShadowPasses
{
get
{
return splitNoShadowPasses;
}
set
{
splitNoShadowPasses = value;
// set the value for all priority groups as well
for(int i = 0; i < priorityGroups.Count; i++)
{
GetPriorityGroup(i).SplitNoShadowPasses = splitNoShadowPasses;
}
}
}
/// <summary>
/// Gets/Sets whether or not the queue will disallow receivers when certain shadow
/// techniques are used.
/// </summary>
public bool ShadowCastersCannotBeReceivers
{
get
{
return shadowCastersCannotBeReceivers;
}
set
{
shadowCastersCannotBeReceivers = value;
// set the value for all priority groups as well
for(int i = 0; i < priorityGroups.Count; i++)
{
GetPriorityGroup(i).ShadowCastersCannotBeReceivers = shadowCastersCannotBeReceivers;
}
}
}
#endregion
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.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>
/// VirtualNetworkGatewayConnectionsOperations operations.
/// </summary>
public partial interface IVirtualNetworkGatewayConnectionsOperations
{
/// <summary>
/// Creates or updates a virtual network gateway connection in the
/// specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network gateway
/// connection 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<VirtualNetworkGatewayConnection>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified virtual network gateway connection by resource
/// group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </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<VirtualNetworkGatewayConnection>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network Gateway connection.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </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 virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the
/// virtual network gateway connection shared key for passed virtual
/// network gateway connection in the specified resource group through
/// Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Set Virtual Network Gateway
/// connection Shared key operation throughNetwork resource provider.
/// </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<ConnectionSharedKey>> SetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Get VirtualNetworkGatewayConnectionSharedKey operation
/// retrieves information about the specified virtual network gateway
/// connection shared key through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection shared key name.
/// </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<ConnectionSharedKey>> GetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The List VirtualNetworkGatewayConnections operation retrieves all
/// the virtual network gateways connections created.
/// </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<VirtualNetworkGatewayConnection>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The VirtualNetworkGatewayConnectionResetSharedKey operation resets
/// the virtual network gateway connection shared key for passed
/// virtual network gateway connection in the specified resource group
/// through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection reset shared key Name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the begin reset virtual network gateway
/// connection shared key operation through network resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <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<ConnectionResetSharedKey>> ResetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a virtual network gateway connection in the
/// specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network gateway
/// connection 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<VirtualNetworkGatewayConnection>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network Gateway connection.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </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 virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the
/// virtual network gateway connection shared key for passed virtual
/// network gateway connection in the specified resource group through
/// Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Set Virtual Network Gateway
/// connection Shared key operation throughNetwork resource provider.
/// </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<ConnectionSharedKey>> BeginSetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The VirtualNetworkGatewayConnectionResetSharedKey operation resets
/// the virtual network gateway connection shared key for passed
/// virtual network gateway connection in the specified resource group
/// through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection reset shared key Name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the begin reset virtual network gateway
/// connection shared key operation through network resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <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<ConnectionResetSharedKey>> BeginResetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The List VirtualNetworkGatewayConnections operation retrieves all
/// the virtual network gateways connections created.
/// </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<VirtualNetworkGatewayConnection>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using FakeItEasy;
using Xunit;
namespace Autofac.Extras.FakeItEasy.Test
{
public class AutoFakeFixture
{
public interface IBar
{
bool Gone { get; }
void Go();
IBar Spawn();
}
public interface IBaz
{
void Go();
}
[Fact]
public void ByDefaultAbstractTypesAreResolvedToTheSameSharedInstance()
{
using (var fake = new AutoFake())
{
var bar1 = fake.Resolve<IBar>();
var bar2 = fake.Resolve<IBar>();
Assert.Same(bar1, bar2);
}
}
[Fact]
public void ByDefaultConcreteTypesAreResolvedToTheSameSharedInstance()
{
using (var fake = new AutoFake())
{
var baz1 = fake.Resolve<Baz>();
var baz2 = fake.Resolve<Baz>();
Assert.Same(baz1, baz2);
}
}
[Fact]
public void ByDefaultFakesAreNotStrict()
{
using (var fake = new AutoFake())
{
var foo = fake.Resolve<Foo>();
// Should not throw.
foo.Go();
}
}
[Fact]
public void ByDefaultFakesDoNotCallBaseMethods()
{
using (var fake = new AutoFake())
{
var bar = fake.Resolve<Bar>();
bar.Go();
Assert.False(bar.Gone);
}
}
[Fact]
public void ByDefaultFakesRespondToCalls()
{
using (var fake = new AutoFake())
{
var bar = fake.Resolve<IBar>();
var result = bar.Spawn();
Assert.NotNull(result);
}
}
[Fact]
public void CanResolveFakesWhichCallsBaseMethods()
{
using (var fake = new AutoFake(callsBaseMethods: true))
{
var bar = fake.Resolve<Bar>();
bar.Go();
Assert.True(bar.Gone);
}
}
[Fact]
public void CanResolveFakesWhichCallsBaseMethodsAndInvokeAbstractMethod()
{
using (var fake = new AutoFake(callsBaseMethods: true))
{
var bar = fake.Resolve<Bar>();
bar.GoAbstractly();
}
}
[Fact]
public void CanResolveFakesWhichInvokeActionsWhenResolved()
{
var resolvedFake = (object)null;
using (var fake = new AutoFake(configureFake: obj => resolvedFake = obj))
{
var bar = fake.Resolve<IBar>();
Assert.Same(bar, resolvedFake);
}
}
[Fact]
public void CanResolveStrictFakes()
{
using (var fake = new AutoFake(strict: true))
{
var foo = fake.Resolve<Foo>();
Assert.Throws<ExpectationException>(() => foo.Go());
}
}
[Fact]
public void ProvidesImplementations()
{
using (var fake = new AutoFake())
{
var baz = fake.Provide<IBaz, Baz>();
Assert.NotNull(baz);
Assert.True(baz is Baz);
}
}
[Fact]
public void ProvidesInstances()
{
using (var fake = new AutoFake())
{
var bar = A.Fake<IBar>();
fake.Provide(bar);
var foo = fake.Resolve<Foo>();
foo.Go();
A.CallTo(() => bar.Go()).MustHaveHappened();
}
}
[Fact]
public void CallsBaseMethodsOverridesStrict()
{
// A characterization test, intended to detect accidental changes in behavior.
// This is an odd situation, since specifying both strict and callsBaseMethods only makes
// sense when there are concrete methods on the fake that we want to be executed, but we
// want to reject the invocation of any methods that are left abstract on the faked type.
using (var fake = new AutoFake(callsBaseMethods: true, strict: true))
{
var bar = fake.Resolve<Bar>();
bar.Go();
Assert.True(bar.Gone);
}
}
[Fact]
public void CallsBaseMethodsOverridesConfigureFake()
{
// A characterization test, intended to detect accidental changes in behavior.
// Since callsBaseMethods applies globally and configureFake can affect individual
// members, having configureFake override callsBaseMethods may be preferred.
using (var fake = new AutoFake(
callsBaseMethods: true,
configureFake: f => A.CallTo(() => ((Bar)f).Go()).DoesNothing()))
{
var bar = fake.Resolve<Bar>();
bar.Go();
Assert.True(bar.Gone);
}
}
[Fact]
public void ConfigureFakeOverridesStrict()
{
using (var fake = new AutoFake(
strict: true,
configureFake: f => A.CallTo(() => ((Bar)f).Go()).DoesNothing()))
{
var bar = fake.Resolve<Bar>();
bar.Go();
}
}
public abstract class Bar : IBar
{
private bool _gone;
public bool Gone
{
get { return this._gone; }
}
public virtual void Go()
{
this._gone = true;
}
public IBar Spawn()
{
throw new NotImplementedException();
}
public abstract void GoAbstractly();
}
public class Baz : IBaz
{
private bool _gone;
public bool Gone
{
get { return this._gone; }
}
public virtual void Go()
{
this._gone = true;
}
}
public class Foo
{
private readonly IBar _bar;
private readonly IBaz _baz;
public Foo(IBar bar, IBaz baz)
{
this._bar = bar;
this._baz = baz;
}
public virtual void Go()
{
this._bar.Go();
this._baz.Go();
}
}
[AttributeUsage(AttributeTargets.Class)]
public class ForTestAttribute : Attribute
{
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
namespace System.Data.SqlClient
{
public sealed partial class SqlConnection : DbConnection
{
private bool _AsyncCommandInProgress;
// SQLStatistics support
internal SqlStatistics _statistics;
private bool _collectstats;
private bool _fireInfoMessageEventOnUserErrors; // False by default
// root task associated with current async invocation
private Tuple<TaskCompletionSource<DbConnectionInternal>, Task> _currentCompletion;
private string _connectionString;
private int _connectRetryCount;
// connection resiliency
private object _reconnectLock = new object();
internal Task _currentReconnectionTask;
private Task _asyncWaitingForReconnection; // current async task waiting for reconnection in non-MARS connections
private Guid _originalConnectionId = Guid.Empty;
private CancellationTokenSource _reconnectionCancellationSource;
internal SessionData _recoverySessionData;
internal bool _supressStateChangeForReconnection;
private int _reconnectCount;
public SqlConnection(string connectionString) : this()
{
ConnectionString = connectionString; // setting connection string first so that ConnectionOption is available
CacheConnectionStringProperties();
}
private SqlConnection(SqlConnection connection)
{ // Clone
GC.SuppressFinalize(this);
CopyFrom(connection);
_connectionString = connection._connectionString;
CacheConnectionStringProperties();
}
// This method will be called once connection string is set or changed.
private void CacheConnectionStringProperties()
{
SqlConnectionString connString = ConnectionOptions as SqlConnectionString;
if (connString != null)
{
_connectRetryCount = connString.ConnectRetryCount;
}
}
//
// PUBLIC PROPERTIES
//
// used to start/stop collection of statistics data and do verify the current state
//
// devnote: start/stop should not performed using a property since it requires execution of code
//
// start statistics
// set the internal flag (_statisticsEnabled) to true.
// Create a new SqlStatistics object if not already there.
// connect the parser to the object.
// if there is no parser at this time we need to connect it after creation.
//
public bool StatisticsEnabled
{
get
{
return (_collectstats);
}
set
{
{
if (value)
{
// start
if (ConnectionState.Open == State)
{
if (null == _statistics)
{
_statistics = new SqlStatistics();
ADP.TimerCurrent(out _statistics._openTimestamp);
}
// set statistics on the parser
// update timestamp;
Debug.Assert(Parser != null, "Where's the parser?");
Parser.Statistics = _statistics;
}
}
else
{
// stop
if (null != _statistics)
{
if (ConnectionState.Open == State)
{
// remove statistics from parser
// update timestamp;
TdsParser parser = Parser;
Debug.Assert(parser != null, "Where's the parser?");
parser.Statistics = null;
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
}
}
_collectstats = value;
}
}
}
internal bool AsyncCommandInProgress
{
get
{
return (_AsyncCommandInProgress);
}
set
{
_AsyncCommandInProgress = value;
}
}
// Does this connection uses Integrated Security?
private bool UsesIntegratedSecurity(SqlConnectionString opt)
{
return opt != null ? opt.IntegratedSecurity : false;
}
// Does this connection uses old style of clear userID or Password in connection string?
private bool UsesClearUserIdOrPassword(SqlConnectionString opt)
{
bool result = false;
if (null != opt)
{
result = (!ADP.IsEmpty(opt.UserID) || !ADP.IsEmpty(opt.Password));
}
return result;
}
internal SqlConnectionString.TypeSystem TypeSystem
{
get
{
return ((SqlConnectionString)ConnectionOptions).TypeSystemVersion;
}
}
internal int ConnectRetryInterval
{
get
{
return ((SqlConnectionString)ConnectionOptions).ConnectRetryInterval;
}
}
override public string ConnectionString
{
get
{
return ConnectionString_Get();
}
set
{
ConnectionString_Set(new SqlConnectionPoolKey(value));
_connectionString = value; // Change _connectionString value only after value is validated
CacheConnectionStringProperties();
}
}
override public int ConnectionTimeout
{
get
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout);
}
}
override public string Database
{
// if the connection is open, we need to ask the inner connection what it's
// current catalog is because it may have gotten changed, otherwise we can
// just return what the connection string had.
get
{
SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
string result;
if (null != innerConnection)
{
result = innerConnection.CurrentDatabase;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog);
}
return result;
}
}
override public string DataSource
{
get
{
SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
string result;
if (null != innerConnection)
{
result = innerConnection.CurrentDataSource;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source);
}
return result;
}
}
public int PacketSize
{
// if the connection is open, we need to ask the inner connection what it's
// current packet size is because it may have gotten changed, otherwise we
// can just return what the connection string had.
get
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
int result;
if (null != innerConnection)
{
result = innerConnection.PacketSize;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size);
}
return result;
}
}
public Guid ClientConnectionId
{
get
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null != innerConnection)
{
return innerConnection.ClientConnectionId;
}
else
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return _originalConnectionId;
}
return Guid.Empty;
}
}
}
override public string ServerVersion
{
get
{
return GetOpenTdsConnection().ServerVersion;
}
}
override public ConnectionState State
{
get
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return ConnectionState.Open;
}
return InnerConnection.State;
}
}
internal SqlStatistics Statistics
{
get
{
return _statistics;
}
}
public string WorkstationId
{
get
{
// If not supplied by the user, the default value is the MachineName
// Note: In Longhorn you'll be able to rename a machine without
// rebooting. Therefore, don't cache this machine name.
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
string result = ((null != constr) ? constr.WorkstationId : string.Empty);
return result;
}
}
// SqlCredential: Pair User Id and password in SecureString which are to be used for SQL authentication
//
// PUBLIC EVENTS
//
public event SqlInfoMessageEventHandler InfoMessage;
public bool FireInfoMessageEventOnUserErrors
{
get
{
return _fireInfoMessageEventOnUserErrors;
}
set
{
_fireInfoMessageEventOnUserErrors = value;
}
}
// Approx. number of times that the internal connection has been reconnected
internal int ReconnectCount
{
get
{
return _reconnectCount;
}
}
internal bool ForceNewConnection { get; set; }
protected override void OnStateChange(StateChangeEventArgs stateChange)
{
if (!_supressStateChangeForReconnection)
{
base.OnStateChange(stateChange);
}
}
//
// PUBLIC METHODS
//
new public SqlTransaction BeginTransaction()
{
// this is just a delegate. The actual method tracks executiontime
return BeginTransaction(IsolationLevel.Unspecified, null);
}
new public SqlTransaction BeginTransaction(IsolationLevel iso)
{
// this is just a delegate. The actual method tracks executiontime
return BeginTransaction(iso, null);
}
public SqlTransaction BeginTransaction(string transactionName)
{
// Use transaction names only on the outermost pair of nested
// BEGIN...COMMIT or BEGIN...ROLLBACK statements. Transaction names
// are ignored for nested BEGIN's. The only way to rollback a nested
// transaction is to have a save point from a SAVE TRANSACTION call.
return BeginTransaction(IsolationLevel.Unspecified, transactionName);
}
[SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")]
override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
DbTransaction transaction = BeginTransaction(isolationLevel);
// InnerConnection doesn't maintain a ref on the outer connection (this) and
// subsequently leaves open the possibility that the outer connection could be GC'ed before the SqlTransaction
// is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable
// until the completion of BeginTransaction with KeepAlive
GC.KeepAlive(this);
return transaction;
}
public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionName)
{
WaitForPendingReconnection();
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
SqlTransaction transaction;
bool isFirstAttempt = true;
do
{
transaction = GetOpenTdsConnection().BeginSqlTransaction(iso, transactionName, isFirstAttempt); // do not reconnect twice
Debug.Assert(isFirstAttempt || !transaction.InternalTransaction.ConnectionHasBeenRestored, "Restored connection on non-first attempt");
isFirstAttempt = false;
} while (transaction.InternalTransaction.ConnectionHasBeenRestored);
// The GetOpenConnection line above doesn't keep a ref on the outer connection (this),
// and it could be collected before the inner connection can hook it to the transaction, resulting in
// a transaction with a null connection property. Use GC.KeepAlive to ensure this doesn't happen.
GC.KeepAlive(this);
return transaction;
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
override public void ChangeDatabase(string database)
{
SqlStatistics statistics = null;
RepairInnerConnection();
try
{
statistics = SqlStatistics.StartTimer(Statistics);
InnerConnection.ChangeDatabase(database);
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
static public void ClearAllPools()
{
SqlConnectionFactory.SingletonInstance.ClearAllPools();
}
static public void ClearPool(SqlConnection connection)
{
ADP.CheckArgumentNull(connection, "connection");
DbConnectionOptions connectionOptions = connection.UserConnectionOptions;
if (null != connectionOptions)
{
SqlConnectionFactory.SingletonInstance.ClearPool(connection);
}
}
private void CloseInnerConnection()
{
// CloseConnection() now handles the lock
// The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and
// the command will no longer be cancelable. It might be desirable to be able to cancel the close opperation, but this is
// outside of the scope of Whidbey RTM. See (SqlCommand::Cancel) for other lock.
InnerConnection.CloseConnection(this, ConnectionFactory);
}
override public void Close()
{
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
CancellationTokenSource cts = _reconnectionCancellationSource;
if (cts != null)
{
cts.Cancel();
}
AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); // we do not need to deal with possible exceptions in reconnection
if (State != ConnectionState.Open)
{// if we cancelled before the connection was opened
OnStateChange(DbConnectionInternal.StateChangeClosed);
}
}
CancelOpenAndWait();
CloseInnerConnection();
GC.SuppressFinalize(this);
if (null != Statistics)
{
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
new public SqlCommand CreateCommand()
{
return new SqlCommand(null, this);
}
private void DisposeMe(bool disposing)
{
if (!disposing)
{
// For non-pooled connections we need to make sure that if the SqlConnection was not closed,
// then we release the GCHandle on the stateObject to allow it to be GCed
// For pooled connections, we will rely on the pool reclaiming the connection
var innerConnection = (InnerConnection as SqlInternalConnectionTds);
if ((innerConnection != null) && (!innerConnection.ConnectionOptions.Pooling))
{
var parser = innerConnection.Parser;
if ((parser != null) && (parser._physicalStateObj != null))
{
parser._physicalStateObj.DecrementPendingCallbacks(release: false);
}
}
}
}
override public void Open()
{
if (StatisticsEnabled)
{
if (null == _statistics)
{
_statistics = new SqlStatistics();
}
else
{
_statistics.ContinueOnNewConnection();
}
}
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
if (!TryOpen(null))
{
throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending);
}
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
internal void RegisterWaitingForReconnect(Task waitingTask)
{
if (((SqlConnectionString)ConnectionOptions).MARS)
{
return;
}
Interlocked.CompareExchange(ref _asyncWaitingForReconnection, waitingTask, null);
if (_asyncWaitingForReconnection != waitingTask)
{ // somebody else managed to register
throw SQL.MARSUnspportedOnConnection();
}
}
private async Task ReconnectAsync(int timeout)
{
try
{
long commandTimeoutExpiration = 0;
if (timeout > 0)
{
commandTimeoutExpiration = ADP.TimerCurrent() + ADP.TimerFromSeconds(timeout);
}
CancellationTokenSource cts = new CancellationTokenSource();
_reconnectionCancellationSource = cts;
CancellationToken ctoken = cts.Token;
int retryCount = _connectRetryCount; // take a snapshot: could be changed by modifying the connection string
for (int attempt = 0; attempt < retryCount; attempt++)
{
if (ctoken.IsCancellationRequested)
{
return;
}
try
{
try
{
ForceNewConnection = true;
await OpenAsync(ctoken).ConfigureAwait(false);
// On success, increment the reconnect count - we don't really care if it rolls over since it is approx.
_reconnectCount = unchecked(_reconnectCount + 1);
#if DEBUG
Debug.Assert(_recoverySessionData._debugReconnectDataApplied, "Reconnect data was not applied !");
#endif
}
finally
{
ForceNewConnection = false;
}
return;
}
catch (SqlException e)
{
if (attempt == retryCount - 1)
{
throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId);
}
if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval))
{
throw SQL.CR_NextAttemptWillExceedQueryTimeout(e, _originalConnectionId);
}
}
await Task.Delay(1000 * ConnectRetryInterval, ctoken).ConfigureAwait(false);
}
}
finally
{
_recoverySessionData = null;
_supressStateChangeForReconnection = false;
}
Debug.Assert(false, "Should not reach this point");
}
internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout)
{
Task runningReconnect = _currentReconnectionTask;
// This loop in the end will return not completed reconnect task or null
while (runningReconnect != null && runningReconnect.IsCompleted)
{
// clean current reconnect task (if it is the same one we checked
Interlocked.CompareExchange<Task>(ref _currentReconnectionTask, null, runningReconnect);
// make sure nobody started new task (if which case we did not clean it)
runningReconnect = _currentReconnectionTask;
}
if (runningReconnect == null)
{
if (_connectRetryCount > 0)
{
SqlInternalConnectionTds tdsConn = GetOpenTdsConnection();
if (tdsConn._sessionRecoveryAcknowledged)
{
TdsParserStateObject stateObj = tdsConn.Parser._physicalStateObj;
if (!stateObj.ValidateSNIConnection())
{
if (tdsConn.Parser._sessionPool != null)
{
if (tdsConn.Parser._sessionPool.ActiveSessionsCount > 0)
{
// >1 MARS session
if (beforeDisconnect != null)
{
beforeDisconnect();
}
OnError(SQL.CR_UnrecoverableClient(ClientConnectionId), true, null);
}
}
SessionData cData = tdsConn.CurrentSessionData;
cData.AssertUnrecoverableStateCountIsCorrect();
if (cData._unrecoverableStatesCount == 0)
{
bool callDisconnect = false;
lock (_reconnectLock)
{
runningReconnect = _currentReconnectionTask; // double check after obtaining the lock
if (runningReconnect == null)
{
if (cData._unrecoverableStatesCount == 0)
{ // could change since the first check, but now is stable since connection is know to be broken
_originalConnectionId = ClientConnectionId;
_recoverySessionData = cData;
if (beforeDisconnect != null)
{
beforeDisconnect();
}
try
{
_supressStateChangeForReconnection = true;
tdsConn.DoomThisConnection();
}
catch (SqlException)
{
}
runningReconnect = Task.Run(() => ReconnectAsync(timeout));
// if current reconnect is not null, somebody already started reconnection task - some kind of race condition
Debug.Assert(_currentReconnectionTask == null, "Duplicate reconnection tasks detected");
_currentReconnectionTask = runningReconnect;
}
}
else
{
callDisconnect = true;
}
}
if (callDisconnect && beforeDisconnect != null)
{
beforeDisconnect();
}
}
else
{
if (beforeDisconnect != null)
{
beforeDisconnect();
}
OnError(SQL.CR_UnrecoverableServer(ClientConnectionId), true, null);
}
} // ValidateSNIConnection
} // sessionRecoverySupported
} // connectRetryCount>0
}
else
{ // runningReconnect = null
if (beforeDisconnect != null)
{
beforeDisconnect();
}
}
return runningReconnect;
}
// this is straightforward, but expensive method to do connection resiliency - it take locks and all prepartions as for TDS request
partial void RepairInnerConnection()
{
WaitForPendingReconnection();
if (_connectRetryCount == 0)
{
return;
}
SqlInternalConnectionTds tdsConn = InnerConnection as SqlInternalConnectionTds;
if (tdsConn != null)
{
tdsConn.ValidateConnectionForExecute(null);
tdsConn.GetSessionAndReconnectIfNeeded((SqlConnection)this);
}
}
private void WaitForPendingReconnection()
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false);
}
}
private void CancelOpenAndWait()
{
// copy from member to avoid changes by background thread
var completion = _currentCompletion;
if (completion != null)
{
completion.Item1.TrySetCanceled();
((IAsyncResult)completion.Item2).AsyncWaitHandle.WaitOne();
}
Debug.Assert(_currentCompletion == null, "After waiting for an async call to complete, there should be no completion source");
}
public override Task OpenAsync(CancellationToken cancellationToken)
{
if (StatisticsEnabled)
{
if (null == _statistics)
{
_statistics = new SqlStatistics();
}
else
{
_statistics.ContinueOnNewConnection();
}
}
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
TaskCompletionSource<DbConnectionInternal> completion = new TaskCompletionSource<DbConnectionInternal>();
TaskCompletionSource<object> result = new TaskCompletionSource<object>();
if (cancellationToken.IsCancellationRequested)
{
result.SetCanceled();
return result.Task;
}
bool completed;
try
{
completed = TryOpen(completion);
}
catch (Exception e)
{
result.SetException(e);
return result.Task;
}
if (completed)
{
result.SetResult(null);
}
else
{
CancellationTokenRegistration registration = new CancellationTokenRegistration();
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(() => completion.TrySetCanceled());
}
OpenAsyncRetry retry = new OpenAsyncRetry(this, completion, result, registration);
_currentCompletion = new Tuple<TaskCompletionSource<DbConnectionInternal>, Task>(completion, result.Task);
completion.Task.ContinueWith(retry.Retry, TaskScheduler.Default);
return result.Task;
}
return result.Task;
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
private class OpenAsyncRetry
{
private SqlConnection _parent;
private TaskCompletionSource<DbConnectionInternal> _retry;
private TaskCompletionSource<object> _result;
private CancellationTokenRegistration _registration;
public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource<DbConnectionInternal> retry, TaskCompletionSource<object> result, CancellationTokenRegistration registration)
{
_parent = parent;
_retry = retry;
_result = result;
_registration = registration;
}
internal void Retry(Task<DbConnectionInternal> retryTask)
{
_registration.Dispose();
try
{
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(_parent.Statistics);
if (retryTask.IsFaulted)
{
Exception e = retryTask.Exception.InnerException;
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(retryTask.Exception.InnerException);
}
else if (retryTask.IsCanceled)
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetCanceled();
}
else
{
bool result;
// protect continuation from races with close and cancel
lock (_parent.InnerConnection)
{
result = _parent.TryOpen(_retry);
}
if (result)
{
_parent._currentCompletion = null;
_result.SetResult(null);
}
else
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(ADP.ExceptionWithStackTrace(ADP.InternalError(ADP.InternalErrorCode.CompletedConnectReturnedPending)));
}
}
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
catch (Exception e)
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(e);
}
}
}
private bool TryOpen(TaskCompletionSource<DbConnectionInternal> retry)
{
if (ForceNewConnection)
{
if (!InnerConnection.TryReplaceConnection(this, ConnectionFactory, retry, UserConnectionOptions))
{
return false;
}
}
else
{
if (!InnerConnection.TryOpenConnection(this, ConnectionFactory, retry, UserConnectionOptions))
{
return false;
}
}
// does not require GC.KeepAlive(this) because of OnStateChange
var tdsInnerConnection = (InnerConnection as SqlInternalConnectionTds);
Debug.Assert(tdsInnerConnection.Parser != null, "Where's the parser?");
if (!tdsInnerConnection.ConnectionOptions.Pooling)
{
// For non-pooled connections, we need to make sure that the finalizer does actually run to avoid leaking SNI handles
GC.ReRegisterForFinalize(this);
}
if (StatisticsEnabled)
{
ADP.TimerCurrent(out _statistics._openTimestamp);
tdsInnerConnection.Parser.Statistics = _statistics;
}
else
{
tdsInnerConnection.Parser.Statistics = null;
_statistics = null; // in case of previous Open/Close/reset_CollectStats sequence
}
return true;
}
//
// INTERNAL PROPERTIES
//
internal bool HasLocalTransaction
{
get
{
return GetOpenTdsConnection().HasLocalTransaction;
}
}
internal bool HasLocalTransactionFromAPI
{
get
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return false; //we will not go into reconnection if we are inside the transaction
}
return GetOpenTdsConnection().HasLocalTransactionFromAPI;
}
}
internal bool IsKatmaiOrNewer
{
get
{
if (_currentReconnectionTask != null)
{ // holds true even if task is completed
return true; // if CR is enabled, connection, if established, will be Katmai+
}
return GetOpenTdsConnection().IsKatmaiOrNewer;
}
}
internal TdsParser Parser
{
get
{
SqlInternalConnectionTds tdsConnection = GetOpenTdsConnection();
return tdsConnection.Parser;
}
}
//
// INTERNAL METHODS
//
internal void ValidateConnectionForExecute(string method, SqlCommand command)
{
Task asyncWaitingForReconnection = _asyncWaitingForReconnection;
if (asyncWaitingForReconnection != null)
{
if (!asyncWaitingForReconnection.IsCompleted)
{
throw SQL.MARSUnspportedOnConnection();
}
else
{
Interlocked.CompareExchange(ref _asyncWaitingForReconnection, null, asyncWaitingForReconnection);
}
}
if (_currentReconnectionTask != null)
{
Task currentReconnectionTask = _currentReconnectionTask;
if (currentReconnectionTask != null && !currentReconnectionTask.IsCompleted)
{
return; // execution will wait for this task later
}
}
SqlInternalConnectionTds innerConnection = GetOpenTdsConnection(method);
innerConnection.ValidateConnectionForExecute(command);
}
// Surround name in brackets and then escape any end bracket to protect against SQL Injection.
// NOTE: if the user escapes it themselves it will not work, but this was the case in V1 as well
// as native OleDb and Odbc.
static internal string FixupDatabaseTransactionName(string name)
{
if (!ADP.IsEmpty(name))
{
return SqlServerEscapeHelper.EscapeIdentifier(name);
}
else
{
return name;
}
}
// If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter
// The close action also supports being run asynchronously
internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction)
{
Debug.Assert(exception != null && exception.Errors.Count != 0, "SqlConnection: OnError called with null or empty exception!");
if (breakConnection && (ConnectionState.Open == State))
{
if (wrapCloseInAction != null)
{
int capturedCloseCount = _closeCount;
Action closeAction = () =>
{
if (capturedCloseCount == _closeCount)
{
Close();
}
};
wrapCloseInAction(closeAction);
}
else
{
Close();
}
}
if (exception.Class >= TdsEnums.MIN_ERROR_CLASS)
{
// It is an error, and should be thrown. Class of TdsEnums.MIN_ERROR_CLASS or above is an error,
// below TdsEnums.MIN_ERROR_CLASS denotes an info message.
throw exception;
}
else
{
// If it is a class < TdsEnums.MIN_ERROR_CLASS, it is a warning collection - so pass to handler
this.OnInfoMessage(new SqlInfoMessageEventArgs(exception));
}
}
//
// PRIVATE METHODS
//
internal SqlInternalConnectionTds GetOpenTdsConnection()
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null == innerConnection)
{
throw ADP.ClosedConnectionError();
}
return innerConnection;
}
internal SqlInternalConnectionTds GetOpenTdsConnection(string method)
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null == innerConnection)
{
throw ADP.OpenConnectionRequired(method, InnerConnection.State);
}
return innerConnection;
}
internal void OnInfoMessage(SqlInfoMessageEventArgs imevent)
{
bool notified;
OnInfoMessage(imevent, out notified);
}
internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified)
{
SqlInfoMessageEventHandler handler = InfoMessage;
if (null != handler)
{
notified = true;
try
{
handler(this, imevent);
}
catch (Exception e)
{
if (!ADP.IsCatchableOrSecurityExceptionType(e))
{
throw;
}
}
}
else
{
notified = false;
}
}
//
// SQL DEBUGGING SUPPORT
//
// this only happens once per connection
// SxS: using named file mapping APIs
internal void RegisterForConnectionCloseNotification<T>(ref Task<T> outterTask, object value, int tag)
{
// Connection exists, schedule removal, will be added to ref collection after calling ValidateAndReconnect
outterTask = outterTask.ContinueWith(task =>
{
RemoveWeakReference(value);
return task;
}, TaskScheduler.Default).Unwrap();
}
public void ResetStatistics()
{
if (null != Statistics)
{
Statistics.Reset();
if (ConnectionState.Open == State)
{
// update timestamp;
ADP.TimerCurrent(out _statistics._openTimestamp);
}
}
}
public IDictionary RetrieveStatistics()
{
if (null != Statistics)
{
UpdateStatistics();
return Statistics.GetHashtable();
}
else
{
return new SqlStatistics().GetHashtable();
}
}
private void UpdateStatistics()
{
if (ConnectionState.Open == State)
{
// update timestamp
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
// delegate the rest of the work to the SqlStatistics class
Statistics.UpdateStatistics();
}
} // SqlConnection
} // System.Data.SqlClient namespace
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Microsoft.DotNet.InternalAbstractions;
using Microsoft.DotNet.Cli.Build.Framework;
using Newtonsoft.Json;
using static Microsoft.DotNet.Cli.Build.Framework.BuildHelpers;
using static Microsoft.DotNet.Cli.Build.FS;
namespace Microsoft.DotNet.Cli.Build
{
public class SharedFrameworkPublisher
{
public static string s_sharedFrameworkName = "Microsoft.NETCore.App";
private string _sharedFrameworkTemplateSourceRoot;
private string _sharedFrameworkNugetVersion;
private string _sharedFrameworkRid;
private string _sharedFrameworkTarget;
private string _sharedFrameworkSourceRoot;
private string _repoRoot;
private string _corehostLockedDirectory;
private string _corehostLatestDirectory;
private Crossgen _crossgenUtil;
private string _corehostPackageSource;
public SharedFrameworkPublisher(
string repoRoot,
string corehostLockedDirectory,
string corehostLatestDirectory,
string corehostPackageSource,
string sharedFrameworkNugetVersion,
string sharedFrameworkRid,
string sharedFrameworkTarget)
{
_repoRoot = repoRoot;
_corehostLockedDirectory = corehostLockedDirectory;
_corehostLatestDirectory = corehostLatestDirectory;
_corehostPackageSource = corehostPackageSource;
string crossgenRID = null;
// If we are dealing with cross-targeting compilation, then specify the
// correct RID for crossgen to use when compiling SharedFramework.
// TODO-ARM-Crossgen: Add ubuntu.14.04-arm and ubuntu.16.04-arm
string portablePlatformRID = null;
if ((sharedFrameworkRid == "win8-arm") || (sharedFrameworkRid == "win10-arm64") || (Utils.IsPortableRID(sharedFrameworkRid, out portablePlatformRID)))
{
crossgenRID = sharedFrameworkRid;
}
_crossgenUtil = new Crossgen(DependencyVersions.CoreCLRVersion, DependencyVersions.JitVersion, crossgenRID);
_sharedFrameworkTemplateSourceRoot = Path.Combine(repoRoot, "src", "sharedframework", "framework");
_sharedFrameworkNugetVersion = sharedFrameworkNugetVersion;
_sharedFrameworkRid = sharedFrameworkRid;
_sharedFrameworkTarget = sharedFrameworkTarget;
_sharedFrameworkSourceRoot = GenerateSharedFrameworkProject(
_sharedFrameworkNugetVersion,
_sharedFrameworkTemplateSourceRoot,
_sharedFrameworkRid,
_sharedFrameworkTarget);
}
public static string GetSharedFrameworkPublishPath(string outputRootDirectory, string sharedFrameworkNugetVersion)
{
return Path.Combine(
outputRootDirectory,
"shared",
s_sharedFrameworkName,
sharedFrameworkNugetVersion);
}
public static string GetNetCoreAppRuntimeLibSymbolsPath(string symbolsRoot, string sharedFrameworkRid, string sharedFrameworkTarget)
{
return Path.Combine(symbolsRoot, s_sharedFrameworkName, "runtimes", sharedFrameworkRid, "lib", sharedFrameworkTarget);
}
public static string GetNetCoreAppRuntimeNativeSymbolsPath(string symbolsRoot, string sharedFrameworkRid)
{
return Path.Combine(symbolsRoot, s_sharedFrameworkName, "runtimes", sharedFrameworkRid, "native");
}
public static string GetNetCoreAppToolsSymbolsPath(string symbolsRoot)
{
return Path.Combine(symbolsRoot, s_sharedFrameworkName, "tools");
}
public void CopyMuxer(string sharedFrameworkPublishRoot)
{
File.Copy(
Path.Combine(_corehostLockedDirectory, HostArtifactNames.DotnetHostBaseName),
Path.Combine(sharedFrameworkPublishRoot, HostArtifactNames.DotnetHostBaseName), true);
}
public void CopyHostFxrToVersionedDirectory(string rootDirectory, string hostFxrVersion)
{
var hostFxrVersionedDirectory = Path.Combine(rootDirectory, "host", "fxr", hostFxrVersion);
FS.Mkdirp(hostFxrVersionedDirectory);
File.Copy(
Path.Combine(_corehostLockedDirectory, HostArtifactNames.DotnetHostFxrBaseName),
Path.Combine(hostFxrVersionedDirectory, HostArtifactNames.DotnetHostFxrBaseName), true);
}
public void PublishSharedFramework(string outputRootDirectory, string commitHash, DotNetCli dotnetCli, string hostFxrVersion)
{
dotnetCli.Restore(
"--verbosity", "verbose",
"--disable-parallel",
"--fallbacksource", _corehostPackageSource)
.WorkingDirectory(_sharedFrameworkSourceRoot)
.Execute()
.EnsureSuccessful();
// We publish to a sub folder of the PublishRoot so tools like heat and zip can generate folder structures easier.
string sharedFrameworkNameAndVersionRoot = GetSharedFrameworkPublishPath(outputRootDirectory, _sharedFrameworkNugetVersion);
if (Directory.Exists(sharedFrameworkNameAndVersionRoot))
{
Utils.DeleteDirectory(sharedFrameworkNameAndVersionRoot);
}
dotnetCli.Publish(
"--output", sharedFrameworkNameAndVersionRoot,
"-r", _sharedFrameworkRid,
_sharedFrameworkSourceRoot)
.Execute()
.EnsureSuccessful();
// Clean up artifacts that dotnet-publish generates which we don't need
PublishMutationUtilties.CleanPublishOutput(
sharedFrameworkNameAndVersionRoot,
"framework",
deleteRuntimeConfigJson: true,
deleteDepsJson: false,
deleteAppHost: true);
// Rename the .deps file
var destinationDeps = Path.Combine(sharedFrameworkNameAndVersionRoot, $"{s_sharedFrameworkName}.deps.json");
File.Move(Path.Combine(sharedFrameworkNameAndVersionRoot, "framework.deps.json"), destinationDeps);
PublishMutationUtilties.ChangeEntryPointLibraryName(destinationDeps, null);
// Generate RID fallback graph
GenerateRuntimeGraph(dotnetCli, destinationDeps);
CopyHostArtifactsToSharedFramework(sharedFrameworkNameAndVersionRoot, hostFxrVersion);
_crossgenUtil.CrossgenDirectory(sharedFrameworkNameAndVersionRoot, sharedFrameworkNameAndVersionRoot);
// Generate .version file for sharedfx
var version = _sharedFrameworkNugetVersion;
var content = $@"{commitHash}{Environment.NewLine}{version}{Environment.NewLine}";
File.WriteAllText(Path.Combine(sharedFrameworkNameAndVersionRoot, ".version"), content);
// Populate symbols publish folder
string sharedFrameworkNameAndVersionWithSymbolsRoot = $"{outputRootDirectory}.symbols";
if (Directory.Exists(sharedFrameworkNameAndVersionWithSymbolsRoot))
{
Utils.DeleteDirectory(sharedFrameworkNameAndVersionWithSymbolsRoot);
}
Directory.CreateDirectory(sharedFrameworkNameAndVersionWithSymbolsRoot);
// Copy symbols to publish folder
List<string> pdbFiles = new List<string>();
string symbolsRoot = Path.Combine(_repoRoot, "pkg", "bin", "symbols");
string libPdbPath = GetNetCoreAppRuntimeLibSymbolsPath(symbolsRoot, _sharedFrameworkRid, _sharedFrameworkTarget);
string nativePdbPath = GetNetCoreAppRuntimeNativeSymbolsPath(symbolsRoot, _sharedFrameworkRid);
string toolsPdbPath = GetNetCoreAppToolsSymbolsPath(symbolsRoot);
if (Directory.Exists(libPdbPath))
{
pdbFiles.AddRange(Directory.GetFiles(libPdbPath));
}
if(Directory.Exists(nativePdbPath))
{
pdbFiles.AddRange(Directory.GetFiles(nativePdbPath));
}
if (Directory.Exists(toolsPdbPath))
{
pdbFiles.AddRange(Directory.GetFiles(toolsPdbPath));
}
foreach (string pdbFile in pdbFiles)
{
string destinationPath = Path.Combine(sharedFrameworkNameAndVersionWithSymbolsRoot, Path.GetFileName(pdbFile));
if (!File.Exists(destinationPath))
{
File.Copy(pdbFile, destinationPath);
}
}
return;
}
private void GenerateRuntimeGraph(DotNetCli dotnetCli, string destinationDeps)
{
string runtimeGraphGeneratorRuntime = null;
switch (RuntimeEnvironment.OperatingSystemPlatform)
{
case Platform.Windows:
runtimeGraphGeneratorRuntime = "win";
break;
case Platform.Linux:
runtimeGraphGeneratorRuntime = "linux";
break;
case Platform.Darwin:
runtimeGraphGeneratorRuntime = "osx";
break;
}
if (!string.IsNullOrEmpty(runtimeGraphGeneratorRuntime))
{
var runtimeGraphGeneratorName = "RuntimeGraphGenerator";
var runtimeGraphGeneratorProject = Path.Combine(Dirs.RepoRoot, "setuptools", "independent", runtimeGraphGeneratorName);
var runtimeGraphGeneratorOutput = Path.Combine(Dirs.Output, "setuptools", "independent", runtimeGraphGeneratorName);
dotnetCli.Publish(
"--output", runtimeGraphGeneratorOutput,
runtimeGraphGeneratorProject).Execute().EnsureSuccessful();
var runtimeGraphGeneratorExe = Path.Combine(runtimeGraphGeneratorOutput, $"{runtimeGraphGeneratorName}{Constants.ExeSuffix}");
Cmd(runtimeGraphGeneratorExe, "--project", _sharedFrameworkSourceRoot, "--deps", destinationDeps, runtimeGraphGeneratorRuntime)
.Execute()
.EnsureSuccessful();
}
else
{
throw new Exception($"Could not determine rid graph generation runtime for platform {RuntimeEnvironment.OperatingSystemPlatform}");
}
}
private void CopyHostArtifactsToSharedFramework(string sharedFrameworkNameAndVersionRoot, string hostFxrVersion)
{
File.Copy(
Path.Combine(_corehostLockedDirectory, HostArtifactNames.DotnetHostBaseName),
Path.Combine(sharedFrameworkNameAndVersionRoot, HostArtifactNames.DotnetHostBaseName), true);
File.Copy(
Path.Combine(_corehostLockedDirectory, HostArtifactNames.DotnetHostFxrBaseName),
Path.Combine(sharedFrameworkNameAndVersionRoot, HostArtifactNames.DotnetHostFxrBaseName), true);
// Hostpolicy should be the latest and not the locked version as it is supposed to evolve for
// the framework and has a tight coupling with coreclr's API in the framework.
File.Copy(
Path.Combine(_corehostLatestDirectory, HostArtifactNames.HostPolicyBaseName),
Path.Combine(sharedFrameworkNameAndVersionRoot, HostArtifactNames.HostPolicyBaseName), true);
}
private string GenerateSharedFrameworkProject(
string sharedFrameworkNugetVersion,
string sharedFrameworkTemplatePath,
string rid,
string targetFramework)
{
string sharedFrameworkProjectPath = Path.Combine(Dirs.Intermediate, "sharedFramework", "framework");
Utils.DeleteDirectory(sharedFrameworkProjectPath);
CopyRecursive(sharedFrameworkTemplatePath, sharedFrameworkProjectPath, true);
string templateFile = Path.Combine(sharedFrameworkProjectPath, "project.json.template");
JObject sharedFrameworkProject = JsonUtils.ReadProject(templateFile);
sharedFrameworkProject["dependencies"]["Microsoft.NETCore.App"] = sharedFrameworkNugetVersion;
((JObject)sharedFrameworkProject["runtimes"]).RemoveAll();
sharedFrameworkProject["runtimes"][rid] = new JObject();
((JObject)sharedFrameworkProject["frameworks"]).RemoveAll();
sharedFrameworkProject["frameworks"][targetFramework] = new JObject();
string projectJsonPath = Path.Combine(sharedFrameworkProjectPath, "project.json");
JsonUtils.WriteProject(sharedFrameworkProject, projectJsonPath);
Rm(templateFile);
return sharedFrameworkProjectPath;
}
}
}
| |
//
// PrimarySource.cs
//
// Author:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Hyena.Jobs;
using Hyena.Data;
using Hyena.Query;
using Hyena.Data.Sqlite;
using Hyena.Collections;
using Banshee.Base;
using Banshee.Preferences;
using Banshee.ServiceStack;
using Banshee.Configuration;
using Banshee.Sources;
using Banshee.Playlist;
using Banshee.SmartPlaylist;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Query;
namespace Banshee.Sources
{
public class TrackEventArgs : EventArgs
{
private DateTime when;
public DateTime When {
get { return when; }
}
private QueryField [] changed_fields;
public QueryField [] ChangedFields {
get { return changed_fields; }
}
public TrackEventArgs ()
{
when = DateTime.Now;
}
public TrackEventArgs (params QueryField [] fields) : this ()
{
changed_fields = fields;
}
}
public delegate bool TrackEqualHandler (DatabaseTrackInfo a, TrackInfo b);
public delegate object TrackExternalObjectHandler (DatabaseTrackInfo a);
public delegate string TrackArtworkIdHandler (DatabaseTrackInfo a);
public abstract class PrimarySource : DatabaseSource, IDisposable
{
#region Functions that let us override some behavior of our DatabaseTrackInfos
public TrackEqualHandler TrackEqualHandler { get; protected set; }
public TrackInfo.IsPlayingHandler TrackIsPlayingHandler { get; protected set; }
public TrackExternalObjectHandler TrackExternalObjectHandler { get; protected set; }
public TrackArtworkIdHandler TrackArtworkIdHandler { get; protected set; }
#endregion
protected ErrorSource error_source;
protected bool error_source_visible = false;
protected string remove_range_sql = @"
INSERT INTO CoreRemovedTracks (DateRemovedStamp, TrackID, Uri) SELECT ?, TrackID, Uri FROM CoreTracks WHERE TrackID IN (SELECT {0});
DELETE FROM CoreTracks WHERE TrackID IN (SELECT {0})";
protected HyenaSqliteCommand remove_list_command = new HyenaSqliteCommand (@"
INSERT INTO CoreRemovedTracks (DateRemovedStamp, TrackID, Uri) SELECT ?, TrackID, Uri FROM CoreTracks WHERE TrackID IN (SELECT ItemID FROM CoreCache WHERE ModelID = ?);
DELETE FROM CoreTracks WHERE TrackID IN (SELECT ItemID FROM CoreCache WHERE ModelID = ?)
");
protected HyenaSqliteCommand prune_artists_albums_command = new HyenaSqliteCommand (@"
DELETE FROM CoreArtists WHERE ArtistID NOT IN (SELECT ArtistID FROM CoreTracks);
DELETE FROM CoreAlbums WHERE AlbumID NOT IN (SELECT AlbumID FROM CoreTracks)
");
protected HyenaSqliteCommand purge_tracks_command = new HyenaSqliteCommand (@"
DELETE FROM CoreTracks WHERE PrimarySourceId = ?
");
private SchemaEntry<bool> expanded_schema;
public SchemaEntry<bool> ExpandedSchema {
get { return expanded_schema; }
}
private int dbid;
public int DbId {
get {
if (dbid > 0) {
return dbid;
}
dbid = ServiceManager.DbConnection.Query<int> ("SELECT PrimarySourceID FROM CorePrimarySources WHERE StringID = ?", UniqueId);
if (dbid == 0) {
dbid = ServiceManager.DbConnection.Execute ("INSERT INTO CorePrimarySources (StringID) VALUES (?)", UniqueId);
} else {
SavedCount = ServiceManager.DbConnection.Query<int> ("SELECT CachedCount FROM CorePrimarySources WHERE PrimarySourceID = ?", dbid);
}
if (dbid == 0) {
throw new ApplicationException ("dbid could not be resolved, this should never happen");
}
return dbid;
}
}
private bool supports_playlists = true;
public virtual bool SupportsPlaylists {
get { return supports_playlists; }
protected set { supports_playlists = value; }
}
public virtual bool PlaylistsReadOnly {
get { return false; }
}
public ErrorSource ErrorSource {
get {
if (error_source == null) {
error_source = new ErrorSource (Catalog.GetString ("Errors"));
ErrorSource.Updated += OnErrorSourceUpdated;
OnErrorSourceUpdated (null, null);
}
return error_source;
}
}
private bool is_local = false;
public bool IsLocal {
get { return is_local; }
protected set { is_local = value; }
}
private static SourceSortType[] sort_types = new SourceSortType[] {
SortNameAscending,
SortSizeAscending,
SortSizeDescending
};
public override SourceSortType[] ChildSortTypes {
get { return sort_types; }
}
public override SourceSortType DefaultChildSort {
get { return SortNameAscending; }
}
public delegate void TrackEventHandler (Source sender, TrackEventArgs args);
public event TrackEventHandler TracksAdded;
public event TrackEventHandler TracksChanged;
public event TrackEventHandler TracksDeleted;
private static Dictionary<int, PrimarySource> primary_sources = new Dictionary<int, PrimarySource> ();
public static PrimarySource GetById (int id)
{
return (primary_sources.ContainsKey (id)) ? primary_sources[id] : null;
}
public virtual string BaseDirectory {
get { return null; }
protected set { base_dir_with_sep = null; }
}
private string base_dir_with_sep;
public string BaseDirectoryWithSeparator {
get { return base_dir_with_sep ?? (base_dir_with_sep = BaseDirectory + System.IO.Path.DirectorySeparatorChar); }
}
protected PrimarySource (string generic_name, string name, string id, int order) : base (generic_name, name, id, order)
{
Properties.SetString ("SortChildrenActionLabel", Catalog.GetString ("Sort Playlists By"));
PrimarySourceInitialize ();
}
protected PrimarySource () : base ()
{
}
// Translators: this is a noun, referring to the harddisk
private string storage_name = Catalog.GetString ("Drive");
public string StorageName {
get { return storage_name; }
protected set { storage_name = value; }
}
public override bool? AutoExpand {
get { return ExpandedSchema.Get (); }
}
public override bool Expanded {
get { return ExpandedSchema.Get (); }
set {
ExpandedSchema.Set (value);
base.Expanded = value;
}
}
public PathPattern PathPattern { get; private set; }
protected void SetFileNamePattern (PathPattern pattern)
{
PathPattern = pattern;
var file_system = PreferencesPage.Add (new Section ("file-system", Catalog.GetString ("File Organization"), 5));
file_system.Add (new SchemaPreference<string> (pattern.FolderSchema, Catalog.GetString ("Folder hie_rarchy")));
file_system.Add (new SchemaPreference<string> (pattern.FileSchema, Catalog.GetString ("File _name")));
}
public virtual void Dispose ()
{
if (Application.ShuttingDown)
return;
DatabaseTrackInfo track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo;
if (track != null && track.PrimarySourceId == this.DbId) {
ServiceManager.PlayerEngine.Close ();
}
ClearChildSources ();
ServiceManager.SourceManager.RemoveSource (this);
}
protected override void Initialize ()
{
base.Initialize ();
PrimarySourceInitialize ();
}
private void PrimarySourceInitialize ()
{
// Scope the tracks to this primary source
DatabaseTrackModel.AddCondition (String.Format ("CoreTracks.PrimarySourceID = {0}", DbId));
primary_sources[DbId] = this;
// Load our playlists and smart playlists
foreach (PlaylistSource pl in PlaylistSource.LoadAll (this)) {
AddChildSource (pl);
}
int sp_count = 0;
foreach (SmartPlaylistSource pl in SmartPlaylistSource.LoadAll (this)) {
AddChildSource (pl);
sp_count++;
}
// Create default smart playlists if we haven't done it ever before, and if the
// user has zero smart playlists.
if (!HaveCreatedSmartPlaylists) {
if (sp_count == 0) {
foreach (SmartPlaylistDefinition def in DefaultSmartPlaylists) {
SmartPlaylistSource pl = def.ToSmartPlaylistSource (this);
pl.Save ();
AddChildSource (pl);
pl.RefreshAndReload ();
sp_count++;
}
}
// Only save it if we already had some smart playlists, or we actually created some (eg not
// if we didn't have any and the list of default ones is empty atm).
if (sp_count > 0)
HaveCreatedSmartPlaylists = true;
}
expanded_schema = new SchemaEntry<bool> (
String.Format ("sources.{0}", ParentConfigurationId), "expanded", true, "Is source expanded", "Is source expanded"
);
}
private bool HaveCreatedSmartPlaylists {
get { return DatabaseConfigurationClient.Client.Get<bool> ("HaveCreatedSmartPlaylists", UniqueId, false); }
set { DatabaseConfigurationClient.Client.Set<bool> ("HaveCreatedSmartPlaylists", UniqueId, value); }
}
public override void Save ()
{
ServiceManager.DbConnection.Execute (
"UPDATE CorePrimarySources SET CachedCount = ? WHERE PrimarySourceID = ?",
Count, DbId
);
}
public virtual void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job)
{
Log.WarningFormat ("CopyTrackTo not implemented for source {0}", this);
}
internal void NotifyTracksAdded ()
{
OnTracksAdded ();
}
internal void NotifyTracksChanged (params QueryField [] fields)
{
OnTracksChanged (fields);
}
// TODO replace this public method with a 'transaction'-like system
public void NotifyTracksChanged ()
{
OnTracksChanged ();
}
public void NotifyTracksDeleted ()
{
OnTracksDeleted ();
}
protected void OnErrorSourceUpdated (object o, EventArgs args)
{
lock (error_source) {
if (error_source.Count > 0 && !error_source_visible) {
error_source_visible = true;
AddChildSource (error_source);
} else if (error_source.Count <= 0 && error_source_visible) {
error_source_visible = false;
RemoveChildSource (error_source);
}
}
}
public virtual IEnumerable<SmartPlaylistDefinition> DefaultSmartPlaylists {
get { yield break; }
}
public virtual IEnumerable<SmartPlaylistDefinition> NonDefaultSmartPlaylists {
get { yield break; }
}
public IEnumerable<SmartPlaylistDefinition> PredefinedSmartPlaylists {
get {
foreach (SmartPlaylistDefinition def in DefaultSmartPlaylists)
yield return def;
foreach (SmartPlaylistDefinition def in NonDefaultSmartPlaylists)
yield return def;
}
}
public override bool CanSearch {
get { return true; }
}
protected override void OnTracksAdded ()
{
ThreadAssist.SpawnFromMain (delegate {
Reload ();
TrackEventHandler handler = TracksAdded;
if (handler != null) {
handler (this, new TrackEventArgs ());
}
});
}
protected override void OnTracksChanged (params QueryField [] fields)
{
ThreadAssist.SpawnFromMain (delegate {
if (NeedsReloadWhenFieldsChanged (fields)) {
Reload ();
} else {
InvalidateCaches ();
}
System.Threading.Thread.Sleep (150);
TrackEventHandler handler = TracksChanged;
if (handler != null) {
handler (this, new TrackEventArgs (fields));
}
});
}
protected override void OnTracksDeleted ()
{
ThreadAssist.SpawnFromMain (delegate {
PruneArtistsAlbums ();
Reload ();
TrackEventHandler handler = TracksDeleted;
if (handler != null) {
handler (this, new TrackEventArgs ());
}
});
}
protected override void OnTracksRemoved ()
{
OnTracksDeleted ();
}
protected virtual void PurgeTracks ()
{
ServiceManager.DbConnection.Execute (purge_tracks_command, DbId);
}
protected override void RemoveTrackRange (DatabaseTrackListModel model, RangeCollection.Range range)
{
ServiceManager.DbConnection.Execute (
String.Format (remove_range_sql, model.TrackIdsSql),
DateTime.Now,
model.CacheId, range.Start, range.End - range.Start + 1,
model.CacheId, range.Start, range.End - range.Start + 1
);
}
public void DeleteSelectedTracksFromChild (DatabaseSource source)
{
if (source.Parent != this)
return;
DeleteSelectedTracks (source.TrackModel as DatabaseTrackListModel);
}
public void DeleteAllTracks (AbstractPlaylistSource source)
{
if (source.PrimarySource != this) {
Log.WarningFormat ("Cannot delete all tracks from {0} via primary source {1}", source, this);
return;
}
if (source.Count < 1)
return;
ThreadAssist.SpawnFromMain (delegate {
CachedList<DatabaseTrackInfo> list = CachedList<DatabaseTrackInfo>.CreateFromModel (source.DatabaseTrackModel);
DeleteTrackList (list);
});
}
protected override void DeleteSelectedTracks (DatabaseTrackListModel model)
{
if (model == null || model.Count < 1) {
return;
}
ThreadAssist.SpawnFromMain (delegate {
CachedList<DatabaseTrackInfo> list = CachedList<DatabaseTrackInfo>.CreateFromModelSelection (model);
DeleteTrackList (list);
});
}
protected virtual void DeleteTrackList (CachedList<DatabaseTrackInfo> list)
{
is_deleting = true;
DeleteTrackJob.Total += (int) list.Count;
List<DatabaseTrackInfo> skip_deletion = null;
// Remove from file system
foreach (DatabaseTrackInfo track in list) {
if (track == null) {
DeleteTrackJob.Completed++;
continue;
}
try {
DeleteTrackJob.Status = String.Format ("{0} - {1}", track.ArtistName, track.TrackTitle);
if (!DeleteTrack (track)) {
if (skip_deletion == null) {
skip_deletion = new List<DatabaseTrackInfo> ();
}
skip_deletion.Add (track);
}
} catch (Exception e) {
Log.Exception (e);
ErrorSource.AddMessage (e.Message, track.Uri.ToString ());
}
DeleteTrackJob.Completed++;
if (DeleteTrackJob.Completed % 10 == 0 && !DeleteTrackJob.IsFinished) {
OnTracksDeleted ();
}
}
is_deleting = false;
if (DeleteTrackJob.Total == DeleteTrackJob.Completed) {
delete_track_job.Finish ();
delete_track_job = null;
}
if (skip_deletion != null) {
list.Remove (skip_deletion);
skip_deletion.Clear ();
skip_deletion = null;
}
// Remove from database
if (list.Count > 0) {
ServiceManager.DbConnection.Execute (remove_list_command, DateTime.Now, list.CacheId, list.CacheId);
}
ThreadAssist.ProxyToMain (delegate {
OnTracksDeleted ();
OnUserNotifyUpdated ();
OnUpdated ();
});
}
protected virtual bool DeleteTrack (DatabaseTrackInfo track)
{
if (!track.Uri.IsLocalPath)
throw new Exception ("Cannot delete a non-local resource: " + track.Uri.Scheme);
try {
Banshee.IO.Utilities.DeleteFileTrimmingParentDirectories (track.Uri);
} catch (System.IO.FileNotFoundException) {
} catch (System.IO.DirectoryNotFoundException) {
}
return true;
}
public override bool AcceptsInputFromSource (Source source)
{
return base.AcceptsInputFromSource (source) && source.Parent != this
&& (source.Parent is PrimarySource || source is PrimarySource)
&& !(source.Parent is Banshee.Library.LibrarySource);
}
public override bool AddSelectedTracks (Source source)
{
if (!AcceptsInputFromSource (source))
return false;
DatabaseTrackListModel model = (source as ITrackModelSource).TrackModel as DatabaseTrackListModel;
// Store a snapshot of the current selection
CachedList<DatabaseTrackInfo> cached_list = CachedList<DatabaseTrackInfo>.CreateFromModelSelection (model);
if (ThreadAssist.InMainThread) {
System.Threading.ThreadPool.QueueUserWorkItem (AddTrackList, cached_list);
} else {
AddTrackList (cached_list);
}
return true;
}
public override bool AddAllTracks (Source source)
{
if (!AcceptsInputFromSource (source) || source.Count == 0) {
return false;
}
DatabaseTrackListModel model = (source as ITrackModelSource).TrackModel as DatabaseTrackListModel;
CachedList<DatabaseTrackInfo> cached_list = CachedList<DatabaseTrackInfo>.CreateFromModel (model);
if (ThreadAssist.InMainThread) {
System.Threading.ThreadPool.QueueUserWorkItem (AddTrackList, cached_list);
} else {
AddTrackList (cached_list);
}
return true;
}
private static HyenaSqliteCommand get_track_id_cmd = new HyenaSqliteCommand ("SELECT TrackID FROM CoreTracks WHERE PrimarySourceId = ? AND Uri = ? LIMIT 1");
public int GetTrackIdForUri (string uri)
{
return ServiceManager.DbConnection.Query<int> (get_track_id_cmd, DbId, new SafeUri (uri).AbsoluteUri);
}
private bool is_adding;
public bool IsAdding {
get { return is_adding; }
}
private bool is_deleting;
public bool IsDeleting {
get { return is_deleting; }
}
protected virtual void AddTrackAndIncrementCount (DatabaseTrackInfo track)
{
AddTrackJob.Status = String.Format ("{0} - {1}", track.ArtistName, track.TrackTitle);
AddTrack (track);
IncrementAddedTracks ();
}
protected virtual void AddTrackList (object cached_list)
{
CachedList<DatabaseTrackInfo> list = cached_list as CachedList<DatabaseTrackInfo>;
is_adding = true;
AddTrackJob.Total += (int) list.Count;
foreach (DatabaseTrackInfo track in list) {
if (AddTrackJob.IsCancelRequested) {
AddTrackJob.Finish ();
IncrementAddedTracks ();
break;
}
if (track == null) {
IncrementAddedTracks ();
continue;
}
try {
AddTrackJob.Status = String.Format ("{0} - {1}", track.ArtistName, track.TrackTitle);
AddTrackAndIncrementCount (track);
} catch (Exception e) {
IncrementAddedTracks ();
Log.Exception (e);
ErrorSource.AddMessage (e.Message, track.Uri.ToString ());
}
}
is_adding = false;
}
protected void IncrementAddedTracks ()
{
bool finished = false, notify = false;
lock (this) {
add_track_job.Completed++;
if (add_track_job.IsFinished) {
finished = true;
add_track_job = null;
} else {
if (add_track_job.Completed % 10 == 0)
notify = true;
}
}
if (finished) {
is_adding = false;
}
if (notify || finished) {
OnTracksAdded ();
if (finished) {
ThreadAssist.ProxyToMain (OnUserNotifyUpdated);
}
}
}
private bool delay_add_job = true;
protected bool DelayAddJob {
get { return delay_add_job; }
set { delay_add_job = value; }
}
private bool delay_delete_job = true;
protected bool DelayDeleteJob {
get { return delay_delete_job; }
set { delay_delete_job = value; }
}
private BatchUserJob add_track_job;
protected BatchUserJob AddTrackJob {
get {
lock (this) {
if (add_track_job == null) {
add_track_job = new BatchUserJob (String.Format (Catalog.GetString (
"Adding {0} of {1} to {2}"), "{0}", "{1}", Name),
Properties.GetStringList ("Icon.Name"));
add_track_job.SetResources (Resource.Cpu, Resource.Database, Resource.Disk);
add_track_job.PriorityHints = PriorityHints.SpeedSensitive | PriorityHints.DataLossIfStopped;
add_track_job.DelayShow = DelayAddJob;
add_track_job.CanCancel = true;
add_track_job.Register ();
}
}
return add_track_job;
}
}
private BatchUserJob delete_track_job;
protected BatchUserJob DeleteTrackJob {
get {
lock (this) {
if (delete_track_job == null) {
delete_track_job = new BatchUserJob (String.Format (Catalog.GetString (
"Deleting {0} of {1} From {2}"), "{0}", "{1}", Name),
Properties.GetStringList ("Icon.Name"));
delete_track_job.SetResources (Resource.Cpu, Resource.Database);
delete_track_job.PriorityHints = PriorityHints.SpeedSensitive | PriorityHints.DataLossIfStopped;
delete_track_job.DelayShow = DelayDeleteJob;
delete_track_job.Register ();
}
}
return delete_track_job;
}
}
protected override void PruneArtistsAlbums ()
{
ServiceManager.DbConnection.Execute (prune_artists_albums_command);
base.PruneArtistsAlbums ();
DatabaseAlbumInfo.Reset ();
DatabaseArtistInfo.Reset ();
}
}
}
| |
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.UIElements;
using System.Reflection;
using System.Linq;
namespace UnityEditor.VFX.UI
{
class ResizableElementFactory : UxmlFactory<ResizableElement>
{}
class ElementResizer : Manipulator
{
public readonly ResizableElement.Resizer direction;
public readonly VisualElement resizedElement;
public ElementResizer(VisualElement resizedElement, ResizableElement.Resizer direction)
{
this.direction = direction;
this.resizedElement = resizedElement;
}
protected override void RegisterCallbacksOnTarget()
{
target.RegisterCallback<MouseDownEvent>(OnMouseDown);
target.RegisterCallback<MouseUpEvent>(OnMouseUp);
}
protected override void UnregisterCallbacksFromTarget()
{
target.UnregisterCallback<MouseDownEvent>(OnMouseDown);
target.UnregisterCallback<MouseUpEvent>(OnMouseUp);
}
Vector2 m_StartMouse;
Vector2 m_StartSize;
Vector2 m_MinSize;
Vector2 m_MaxSize;
Vector2 m_StartPosition;
bool m_DragStarted = false;
void OnMouseDown(MouseDownEvent e)
{
if (e.button == 0 && e.clickCount == 1)
{
VisualElement resizedTarget = resizedElement.parent;
if (resizedTarget != null)
{
VisualElement resizedBase = resizedTarget.parent;
if (resizedBase != null)
{
target.RegisterCallback<MouseMoveEvent>(OnMouseMove);
e.StopPropagation();
target.CaptureMouse();
m_StartMouse = resizedBase.WorldToLocal(e.mousePosition);
m_StartSize = new Vector2(resizedTarget.resolvedStyle.width, resizedTarget.resolvedStyle.height);
m_StartPosition = new Vector2(resizedTarget.resolvedStyle.left, resizedTarget.resolvedStyle.top);
bool minWidthDefined = resizedTarget.resolvedStyle.minWidth != StyleKeyword.Auto;
bool maxWidthDefined = resizedTarget.resolvedStyle.maxWidth != StyleKeyword.None;
bool minHeightDefined = resizedTarget.resolvedStyle.minHeight != StyleKeyword.Auto;
bool maxHeightDefined = resizedTarget.resolvedStyle.maxHeight != StyleKeyword.None;
m_MinSize = new Vector2(
minWidthDefined ? resizedTarget.resolvedStyle.minWidth.value : Mathf.NegativeInfinity,
minHeightDefined ? resizedTarget.resolvedStyle.minHeight.value : Mathf.NegativeInfinity);
m_MaxSize = new Vector2(
maxWidthDefined ? resizedTarget.resolvedStyle.maxWidth.value : Mathf.Infinity,
maxHeightDefined ? resizedTarget.resolvedStyle.maxHeight.value : Mathf.Infinity);
m_DragStarted = false;
}
}
}
}
void OnMouseMove(MouseMoveEvent e)
{
VisualElement resizedTarget = resizedElement.parent;
VisualElement resizedBase = resizedTarget.parent;
Vector2 mousePos = resizedBase.WorldToLocal(e.mousePosition);
if (!m_DragStarted)
{
if (resizedTarget is IVFXResizable)
{
(resizedTarget as IVFXResizable).OnStartResize();
}
m_DragStarted = true;
}
if ((direction & ResizableElement.Resizer.Right) != 0)
{
resizedTarget.style.width = Mathf.Min(m_MaxSize.x, Mathf.Max(m_MinSize.x, m_StartSize.x + mousePos.x - m_StartMouse.x));
}
else if ((direction & ResizableElement.Resizer.Left) != 0)
{
float delta = mousePos.x - m_StartMouse.x;
if (m_StartSize.x - delta < m_MinSize.x)
{
delta = -m_MinSize.x + m_StartSize.x;
}
else if (m_StartSize.x - delta > m_MaxSize.x)
{
delta = -m_MaxSize.x + m_StartSize.x;
}
resizedTarget.style.left = delta + m_StartPosition.x;
resizedTarget.style.width = -delta + m_StartSize.x;
}
if ((direction & ResizableElement.Resizer.Bottom) != 0)
{
resizedTarget.style.height = Mathf.Min(m_MaxSize.y, Mathf.Max(m_MinSize.y, m_StartSize.y + mousePos.y - m_StartMouse.y));
}
else if ((direction & ResizableElement.Resizer.Top) != 0)
{
float delta = mousePos.y - m_StartMouse.y;
if (m_StartSize.y - delta < m_MinSize.y)
{
delta = -m_MinSize.y + m_StartSize.y;
}
else if (m_StartSize.y - delta > m_MaxSize.y)
{
delta = -m_MaxSize.y + m_StartSize.y;
}
resizedTarget.style.top = delta + m_StartPosition.y;
resizedTarget.style.height = -delta + m_StartSize.y;
}
e.StopPropagation();
}
void OnMouseUp(MouseUpEvent e)
{
if (e.button == 0)
{
VisualElement resizedTarget = resizedElement.parent;
if (resizedTarget.style.width != m_StartSize.x || resizedTarget.style.height != m_StartSize.y)
{
if (resizedTarget is IVFXResizable)
{
(resizedTarget as IVFXResizable).OnResized();
}
}
target.UnregisterCallback<MouseMoveEvent>(OnMouseMove);
target.ReleaseMouse();
e.StopPropagation();
}
}
}
public class ResizableElement : VisualElement
{
public ResizableElement() : this("uxml/Resizable")
{
pickingMode = PickingMode.Ignore;
}
public ResizableElement(string uiFile)
{
var tpl = Resources.Load<VisualTreeAsset>(uiFile);
var sheet = Resources.Load<StyleSheet>("Resizable");
styleSheets.Add(sheet);
tpl.CloneTree(this);
foreach (Resizer value in System.Enum.GetValues(typeof(Resizer)))
{
VisualElement resizer = this.Q(value.ToString().ToLower() + "-resize");
if (resizer != null)
resizer.AddManipulator(new ElementResizer(this, value));
m_Resizers[value] = resizer;
}
foreach (Resizer vertical in new[] {Resizer.Top, Resizer.Bottom})
foreach (Resizer horizontal in new[] {Resizer.Left, Resizer.Right})
{
VisualElement resizer = this.Q(vertical.ToString().ToLower() + "-" + horizontal.ToString().ToLower() + "-resize");
if (resizer != null)
resizer.AddManipulator(new ElementResizer(this, vertical | horizontal));
m_Resizers[vertical | horizontal] = resizer;
}
}
public enum Resizer
{
Top = 1 << 0,
Bottom = 1 << 1,
Left = 1 << 2,
Right = 1 << 3,
}
Dictionary<Resizer, VisualElement> m_Resizers = new Dictionary<Resizer, VisualElement>();
}
class StickyNodeChangeEvent : EventBase<StickyNodeChangeEvent>
{
public static StickyNodeChangeEvent GetPooled(StickyNote target, Change change)
{
var evt = GetPooled();
evt.target = target;
evt.change = change;
return evt;
}
public enum Change
{
title,
contents,
theme,
textSize
}
public Change change {get; protected set; }
}
class StickyNote : GraphElement, IVFXResizable
{
public enum Theme
{
Classic,
Black,
Orange,
Green,
Blue,
Red,
Purple,
Teal
}
Theme m_Theme = Theme.Classic;
public Theme theme
{
get
{
return m_Theme;
}
set
{
if (m_Theme != value)
{
m_Theme = value;
UpdateThemeClasses();
}
}
}
public enum TextSize
{
Small,
Medium,
Large,
Huge
}
TextSize m_TextSize = TextSize.Medium;
public TextSize textSize
{
get {return m_TextSize; }
set
{
if (m_TextSize != value)
{
m_TextSize = value;
UpdateSizeClasses();
}
}
}
public virtual void OnStartResize()
{
}
public virtual void OnResized()
{
}
Vector2 AllExtraSpace(VisualElement element)
{
return new Vector2(
element.resolvedStyle.marginLeft + element.resolvedStyle.marginRight + element.resolvedStyle.paddingLeft + element.resolvedStyle.paddingRight + element.resolvedStyle.borderRightWidth + element.resolvedStyle.borderLeftWidth,
element.resolvedStyle.marginTop + element.resolvedStyle.marginBottom + element.resolvedStyle.paddingTop + element.resolvedStyle.paddingBottom + element.resolvedStyle.borderBottomWidth + element.resolvedStyle.borderTopWidth
);
}
void OnFitToText(DropdownMenuAction a)
{
FitText(false);
}
public void FitText(bool onlyIfSmaller)
{
Vector2 preferredTitleSize = Vector2.zero;
if (!string.IsNullOrEmpty(m_Title.text))
preferredTitleSize = m_Title.MeasureTextSize(m_Title.text, 0, MeasureMode.Undefined, 0, MeasureMode.Undefined); // This is the size of the string with the current title font and such
preferredTitleSize += AllExtraSpace(m_Title);
preferredTitleSize.x += m_Title.ChangeCoordinatesTo(this, Vector2.zero).x + resolvedStyle.width - m_Title.ChangeCoordinatesTo(this, new Vector2(m_Title.layout.width, 0)).x;
Vector2 preferredContentsSizeOneLine = m_Contents.MeasureTextSize(m_Contents.text, 0, MeasureMode.Undefined, 0, MeasureMode.Undefined);
Vector2 contentExtraSpace = AllExtraSpace(m_Contents);
preferredContentsSizeOneLine += contentExtraSpace;
Vector2 extraSpace = new Vector2(resolvedStyle.width, resolvedStyle.height) - m_Contents.ChangeCoordinatesTo(this, new Vector2(m_Contents.layout.width, m_Contents.layout.height));
extraSpace += m_Title.ChangeCoordinatesTo(this, Vector2.zero);
preferredContentsSizeOneLine += extraSpace;
float width = 0;
float height = 0;
// The content in one line is smaller than the current width.
// Set the width to fit both title and content.
// Set the height to have only one line in the content
if (preferredContentsSizeOneLine.x < Mathf.Max(preferredTitleSize.x, resolvedStyle.width))
{
width = Mathf.Max(preferredContentsSizeOneLine.x, preferredTitleSize.x);
height = preferredContentsSizeOneLine.y + preferredTitleSize.y;
}
else // The width is not enough for the content: keep the width or use the title width if bigger.
{
width = Mathf.Max(preferredTitleSize.x + extraSpace.x, resolvedStyle.width);
float contextWidth = width - extraSpace.x - contentExtraSpace.x;
Vector2 preferredContentsSize = m_Contents.MeasureTextSize(m_Contents.text, contextWidth, MeasureMode.Exactly, 0, MeasureMode.Undefined);
preferredContentsSize += contentExtraSpace;
height = preferredTitleSize.y + preferredContentsSize.y + extraSpace.y;
}
if (!onlyIfSmaller || resolvedStyle.width < width)
style.width = width;
if (!onlyIfSmaller || resolvedStyle.height < height)
style.height = height;
OnResized();
}
void UpdateThemeClasses()
{
foreach (Theme value in System.Enum.GetValues(typeof(Theme)))
{
if (m_Theme != value)
{
RemoveFromClassList("theme-" + value.ToString().ToLower());
}
else
{
AddToClassList("theme-" + value.ToString().ToLower());
}
}
}
void UpdateSizeClasses()
{
foreach (TextSize value in System.Enum.GetValues(typeof(TextSize)))
{
if (m_TextSize != value)
{
RemoveFromClassList("size-" + value.ToString().ToLower());
}
else
{
AddToClassList("size-" + value.ToString().ToLower());
}
}
}
public static readonly Vector2 defaultSize = new Vector2(200, 160);
public StickyNote(Vector2 position) : this("uxml/StickyNote", position)
{
styleSheets.Add(Resources.Load<StyleSheet>("Selectable"));
styleSheets.Add(Resources.Load<StyleSheet>("StickyNote"));
RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
}
public StickyNote(string uiFile, Vector2 position)
{
var tpl = Resources.Load<VisualTreeAsset>(uiFile);
tpl.CloneTree(this);
capabilities = Capabilities.Movable | Capabilities.Deletable | Capabilities.Ascendable | Capabilities.Selectable;
m_Title = this.Q<Label>(name: "title");
if (m_Title != null)
{
m_Title.RegisterCallback<MouseDownEvent>(OnTitleMouseDown);
}
m_TitleField = this.Q<TextField>(name: "title-field");
if (m_TitleField != null)
{
m_TitleField.visible = false;
m_TitleField.Q("unity-text-input").RegisterCallback<BlurEvent>(OnTitleBlur);
m_TitleField.RegisterCallback<ChangeEvent<string>>(OnTitleChange);
}
m_Contents = this.Q<Label>(name: "contents");
if (m_Contents != null)
{
m_ContentsField = m_Contents.Q<TextField>(name: "contents-field");
if (m_ContentsField != null)
{
m_ContentsField.visible = false;
m_ContentsField.multiline = true;
m_ContentsField.Q("unity-text-input").RegisterCallback<BlurEvent>(OnContentsBlur);
}
m_Contents.RegisterCallback<MouseDownEvent>(OnContentsMouseDown);
}
SetPosition(new Rect(position, defaultSize));
AddToClassList("sticky-note");
AddToClassList("selectable");
UpdateThemeClasses();
UpdateSizeClasses();
this.AddManipulator(new ContextualMenuManipulator(BuildContextualMenu));
}
public void BuildContextualMenu(ContextualMenuPopulateEvent evt)
{
if (evt.target is StickyNote)
{
/*foreach (Theme value in System.Enum.GetValues(typeof(Theme)))
{
evt.menu.AppendAction("Theme/" + value.ToString(), OnChangeTheme, e => DropdownMenu.MenuAction.StatusFlags.Normal, value);
}*/
if (theme == Theme.Black)
evt.menu.AppendAction("Light Theme", OnChangeTheme, e => DropdownMenuAction.Status.Normal, Theme.Classic);
else
evt.menu.AppendAction("Dark Theme", OnChangeTheme, e => DropdownMenuAction.Status.Normal, Theme.Black);
foreach (TextSize value in System.Enum.GetValues(typeof(TextSize)))
{
evt.menu.AppendAction(value.ToString() + " Text Size", OnChangeSize, e => DropdownMenuAction.Status.Normal, value);
}
evt.menu.AppendSeparator();
evt.menu.AppendAction("Fit To Text", OnFitToText, e => DropdownMenuAction.Status.Normal);
evt.menu.AppendSeparator();
}
}
void OnTitleChange(EventBase e)
{
title = m_TitleField.value;
}
const string fitTextClass = "fit-text";
public override void SetPosition(Rect rect)
{
style.left = rect.x;
style.top = rect.y;
style.width = rect.width;
style.height = rect.height;
}
public override Rect GetPosition()
{
return new Rect(resolvedStyle.left, resolvedStyle.top, resolvedStyle.width, resolvedStyle.height);
}
public string contents
{
get {return m_Contents.text; }
set
{
if (m_Contents != null)
{
m_Contents.text = value;
}
}
}
public new string title
{
get {return m_Title.text; }
set
{
if (m_Title != null)
{
m_Title.text = value;
if (!string.IsNullOrEmpty(m_Title.text))
{
m_Title.RemoveFromClassList("empty");
}
else
{
m_Title.AddToClassList("empty");
}
//UpdateTitleHeight();
}
}
}
void OnChangeTheme(DropdownMenuAction action)
{
theme = (Theme)action.userData;
NotifyChange(StickyNodeChangeEvent.Change.theme);
}
void OnChangeSize(DropdownMenuAction action)
{
textSize = (TextSize)action.userData;
NotifyChange(StickyNodeChangeEvent.Change.textSize);
panel.InternalValidateLayout();
FitText(true);
}
void OnAttachToPanel(AttachToPanelEvent e)
{
//UpdateTitleHeight();
}
void OnTitleBlur(BlurEvent e)
{
//bool changed = m_Title.text != m_TitleField.value;
title = m_TitleField.value;
m_TitleField.visible = false;
m_Title.UnregisterCallback<GeometryChangedEvent>(OnTitleRelayout);
//Notify change
//if( changed)
{
NotifyChange(StickyNodeChangeEvent.Change.title);
}
}
void OnContentsBlur(BlurEvent e)
{
bool changed = m_Contents.text != m_ContentsField.value;
m_Contents.text = m_ContentsField.value;
m_ContentsField.visible = false;
//Notify change
if (changed)
{
NotifyChange(StickyNodeChangeEvent.Change.contents);
}
}
void OnTitleRelayout(GeometryChangedEvent e)
{
UpdateTitleFieldRect();
}
void UpdateTitleFieldRect()
{
Rect rect = m_Title.layout;
//if( m_Title != m_TitleField.parent)
m_Title.parent.ChangeCoordinatesTo(m_TitleField.parent, rect);
m_TitleField.style.left = rect.xMin /* + m_Title.style.marginLeft*/;
m_TitleField.style.right = rect.yMin + m_Title.resolvedStyle.marginTop;
m_TitleField.style.width = rect.width - m_Title.resolvedStyle.marginLeft - m_Title.resolvedStyle.marginRight;
m_TitleField.style.height = rect.height - m_Title.resolvedStyle.marginTop - m_Title.resolvedStyle.marginBottom;
}
void OnTitleMouseDown(MouseDownEvent e)
{
if (e.clickCount == 2)
{
m_TitleField.RemoveFromClassList("empty");
m_TitleField.value = m_Title.text;
m_TitleField.visible = true;
UpdateTitleFieldRect();
m_Title.RegisterCallback<GeometryChangedEvent>(OnTitleRelayout);
m_TitleField.Q("unity-text-input").Focus();
m_TitleField.SelectAll();
e.StopPropagation();
e.PreventDefault();
}
}
void NotifyChange(StickyNodeChangeEvent.Change change)
{
if (OnChange != null)
{
OnChange(change);
}
}
public System.Action<StickyNodeChangeEvent.Change> OnChange;
void OnContentsMouseDown(MouseDownEvent e)
{
if (e.clickCount == 2)
{
m_ContentsField.value = m_Contents.text;
m_ContentsField.visible = true;
m_ContentsField.Q("unity-text-input").Focus();
e.StopPropagation();
e.PreventDefault();
}
}
Label m_Title;
protected TextField m_TitleField;
Label m_Contents;
protected TextField m_ContentsField;
}
}
| |
/*
* 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 BufferedIndexInput = Lucene.Net.Store.BufferedIndexInput;
using IndexInput = Lucene.Net.Store.IndexInput;
namespace Lucene.Net.Index
{
/// <summary> This abstract class reads skip lists with multiple levels.
///
/// See {@link MultiLevelSkipListWriter} for the information about the encoding
/// of the multi level skip lists.
///
/// Subclasses must implement the abstract method {@link #ReadSkipData(int, IndexInput)}
/// which defines the actual format of the skip data.
/// </summary>
abstract class MultiLevelSkipListReader
{
// the maximum number of skip levels possible for this index
private int maxNumberOfSkipLevels;
// number of levels in this skip list
private int numberOfSkipLevels;
// Expert: defines the number of top skip levels to buffer in memory.
// Reducing this number results in less memory usage, but possibly
// slower performance due to more random I/Os.
// Please notice that the space each level occupies is limited by
// the skipInterval. The top level can not contain more than
// skipLevel entries, the second top level can not contain more
// than skipLevel^2 entries and so forth.
private int numberOfLevelsToBuffer = 1;
private int docCount;
private bool haveSkipped;
private IndexInput[] skipStream; // skipStream for each level
private long[] skipPointer; // the start pointer of each skip level
private int[] skipInterval; // skipInterval of each level
private int[] numSkipped; // number of docs skipped per level
private int[] skipDoc; // doc id of current skip entry per level
private int lastDoc; // doc id of last read skip entry with docId <= target
private long[] childPointer; // child pointer of current skip entry per level
private long lastChildPointer; // childPointer of last read skip entry with docId <= target
private bool inputIsBuffered;
public MultiLevelSkipListReader(IndexInput skipStream, int maxSkipLevels, int skipInterval)
{
this.skipStream = new IndexInput[maxSkipLevels];
this.skipPointer = new long[maxSkipLevels];
this.childPointer = new long[maxSkipLevels];
this.numSkipped = new int[maxSkipLevels];
this.maxNumberOfSkipLevels = maxSkipLevels;
this.skipInterval = new int[maxSkipLevels];
this.skipStream[0] = skipStream;
this.inputIsBuffered = (skipStream is BufferedIndexInput);
this.skipInterval[0] = skipInterval;
for (int i = 1; i < maxSkipLevels; i++)
{
// cache skip intervals
this.skipInterval[i] = this.skipInterval[i - 1] * skipInterval;
}
skipDoc = new int[maxSkipLevels];
}
/// <summary>Returns the id of the doc to which the last call of {@link #SkipTo(int)}
/// has skipped.
/// </summary>
internal virtual int GetDoc()
{
return lastDoc;
}
/// <summary>Skips entries to the first beyond the current whose document number is
/// greater than or equal to <i>target</i>. Returns the current doc count.
/// </summary>
internal virtual int SkipTo(int target)
{
if (!haveSkipped)
{
// first time, load skip levels
LoadSkipLevels();
haveSkipped = true;
}
// walk up the levels until highest level is found that has a skip
// for this target
int level = 0;
while (level < numberOfSkipLevels - 1 && target > skipDoc[level + 1])
{
level++;
}
while (level >= 0)
{
if (target > skipDoc[level])
{
if (!LoadNextSkip(level))
{
continue;
}
}
else
{
// no more skips on this level, go down one level
if (level > 0 && lastChildPointer > skipStream[level - 1].GetFilePointer())
{
SeekChild(level - 1);
}
level--;
}
}
return numSkipped[0] - skipInterval[0] - 1;
}
private bool LoadNextSkip(int level)
{
// we have to skip, the target document is greater than the current
// skip list entry
SetLastSkipData(level);
numSkipped[level] += skipInterval[level];
if (numSkipped[level] > docCount)
{
// this skip list is exhausted
skipDoc[level] = System.Int32.MaxValue;
if (numberOfSkipLevels > level)
numberOfSkipLevels = level;
return false;
}
// read next skip entry
skipDoc[level] += ReadSkipData(level, skipStream[level]);
if (level != 0)
{
// read the child pointer if we are not on the leaf level
childPointer[level] = skipStream[level].ReadVLong() + skipPointer[level - 1];
}
return true;
}
/// <summary>Seeks the skip entry on the given level </summary>
protected internal virtual void SeekChild(int level)
{
skipStream[level].Seek(lastChildPointer);
numSkipped[level] = numSkipped[level + 1] - skipInterval[level + 1];
skipDoc[level] = lastDoc;
if (level > 0)
{
childPointer[level] = skipStream[level].ReadVLong() + skipPointer[level - 1];
}
}
internal virtual void Close()
{
for (int i = 1; i < skipStream.Length; i++)
{
if (skipStream[i] != null)
{
skipStream[i].Close();
}
}
}
/// <summary>initializes the reader </summary>
internal virtual void Init(long skipPointer, int df)
{
this.skipPointer[0] = skipPointer;
this.docCount = df;
Array.Clear(skipDoc, 0, skipDoc.Length);
Array.Clear(numSkipped, 0, numSkipped.Length);
Array.Clear(childPointer, 0, childPointer.Length);
haveSkipped = false;
for (int i = 1; i < numberOfSkipLevels; i++)
{
skipStream[i] = null;
}
}
/// <summary>Loads the skip levels </summary>
private void LoadSkipLevels()
{
numberOfSkipLevels = docCount == 0 ? 0 :(int) System.Math.Floor(System.Math.Log(docCount) / System.Math.Log(skipInterval[0]));
if (numberOfSkipLevels > maxNumberOfSkipLevels)
{
numberOfSkipLevels = maxNumberOfSkipLevels;
}
skipStream[0].Seek(skipPointer[0]);
int toBuffer = numberOfLevelsToBuffer;
for (int i = numberOfSkipLevels - 1; i > 0; i--)
{
// the length of the current level
long length = skipStream[0].ReadVLong();
// the start pointer of the current level
skipPointer[i] = skipStream[0].GetFilePointer();
if (toBuffer > 0)
{
// buffer this level
skipStream[i] = new SkipBuffer(skipStream[0], (int) length);
toBuffer--;
}
else
{
// clone this stream, it is already at the start of the current level
skipStream[i] = (IndexInput) skipStream[0].Clone();
if (inputIsBuffered && length < BufferedIndexInput.BUFFER_SIZE)
{
((BufferedIndexInput) skipStream[i]).SetBufferSize((int) length);
}
// move base stream beyond the current level
skipStream[0].Seek(skipStream[0].GetFilePointer() + length);
}
}
// use base stream for the lowest level
skipPointer[0] = skipStream[0].GetFilePointer();
}
/// <summary> Subclasses must implement the actual skip data encoding in this method.
///
/// </summary>
/// <param name="level">the level skip data shall be read from
/// </param>
/// <param name="skipStream">the skip stream to read from
/// </param>
protected internal abstract int ReadSkipData(int level, IndexInput skipStream);
/// <summary>Copies the values of the last read skip entry on this level </summary>
protected internal virtual void SetLastSkipData(int level)
{
lastDoc = skipDoc[level];
lastChildPointer = childPointer[level];
}
/// <summary>used to buffer the top skip levels </summary>
private sealed class SkipBuffer : IndexInput
{
private byte[] data;
private long pointer;
private int pos;
internal SkipBuffer(IndexInput input, int length)
{
data = new byte[length];
pointer = input.GetFilePointer();
input.ReadBytes(data, 0, length);
}
public override void Close()
{
data = null;
}
public override long GetFilePointer()
{
return pointer + pos;
}
public override long Length()
{
return data.Length;
}
public override byte ReadByte()
{
return data[pos++];
}
public override void ReadBytes(byte[] b, int offset, int len)
{
Array.Copy(data, pos, b, offset, len);
pos += len;
}
public override void Seek(long pos)
{
this.pos = (int) (pos - pointer);
}
//override public object Clone() // {{Aroush-2.3.1}} Do we need this?
//{
// return null;
//}
}
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using Glass.Mapper.Configuration;
using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.OnDemandResolver;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.IoC;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Mvc.Configuration;
using Sitecore.Mvc.Data;
using Sitecore.Mvc.Extensions;
using Sitecore.Mvc.Pipelines.Response.GetModel;
using Sitecore.Mvc.Presentation;
namespace Glass.Mapper.Sc.Pipelines.Response
{
/// <summary>
///
/// </summary>
public class GetModel : GetModelProcessor
{
/// <summary>
/// The model type field
/// </summary>
public const string ModelTypeField = "Model Type";
private readonly Type renderingModelType = typeof (IRenderingModel);
/// <summary>
/// The model field
/// </summary>
public const string ModelField = "Model";
/// <summary>
/// Initializes a new instance of the <see cref="GetModel"/> class.
/// </summary>
public GetModel() : this(IoC.SitecoreContextFactory.Default)
{
}
public GetModel(ISitecoreContextFactory sitecoreContextFactory)
{
SitecoreContextFactory = sitecoreContextFactory;
}
protected virtual ISitecoreContextFactory SitecoreContextFactory { get; private set; }
/// <summary>
/// Processes the specified args.
/// </summary>
/// <param name="args">The args.</param>
public override void Process(GetModelArgs args)
{
if (args.Result != null)
{
return;
}
Rendering rendering = args.Rendering;
if (rendering.RenderingType == "Layout")
{
args.Result = GetFromItem(rendering, args);
if (args.Result == null)
{
args.Result = GetFromLayout(rendering, args);
}
}
if (args.Result == null)
{
args.Result = GetFromPropertyValue(rendering, args);
}
if (args.Result == null)
{
args.Result = GetFromField(rendering, args);
}
if (args.Result != null)
{
args.AbortPipeline();
}
}
/// <summary>
/// Gets from field.
/// </summary>
/// <param name="rendering">The rendering.</param>
/// <param name="args">The args.</param>
/// <returns></returns>
protected virtual object GetFromField(Rendering rendering, GetModelArgs args)
{
Item obj = rendering.RenderingItem.ValueOrDefault(i => i.InnerItem);
if (obj == null)
return null;
return rendering.Item == null
? null
: GetObject(obj[ModelField], rendering.Item.Database, rendering);
}
/// <summary>
/// Gets from property value.
/// </summary>
/// <param name="rendering">The rendering.</param>
/// <param name="args">The args.</param>
/// <returns></returns>
protected virtual object GetFromPropertyValue(Rendering rendering, GetModelArgs args)
{
string model = rendering.Properties[ModelField];
if (model.IsWhiteSpaceOrNull())
return null;
else
return GetObject(model, rendering.Item.Database, rendering);
}
/// <summary>
/// Gets from layout.
/// </summary>
/// <param name="rendering">The rendering.</param>
/// <param name="args">The args.</param>
/// <returns></returns>
protected virtual object GetFromLayout(Rendering rendering, GetModelArgs args)
{
string pathOrId = rendering.Properties["LayoutId"];
if (pathOrId.IsWhiteSpaceOrNull())
return null;
string model = MvcSettings.GetRegisteredObject<ItemLocator>().GetItem(pathOrId).ValueOrDefault(i => i["Model"]);
if (model.IsWhiteSpaceOrNull())
return null;
else
return GetObject(model, rendering.Item.Database, rendering);
}
/// <summary>
/// Gets from item.
/// </summary>
/// <param name="rendering">The rendering.</param>
/// <param name="args">The args.</param>
/// <returns></returns>
protected virtual object GetFromItem(Rendering rendering, GetModelArgs args)
{
string model = rendering.Item.ValueOrDefault(i => i["MvcLayoutModel"]);
if (model.IsWhiteSpaceOrNull())
return null;
return GetObject(model, rendering.Item.Database, rendering);
}
/// <summary>
/// Gets the object.
/// </summary>
/// <param name="model">The model.</param>
/// <param name="db">The db.</param>
/// <returns></returns>
/// <exception cref="Glass.Mapper.MapperException">Failed to find context {0}.Formatted(ContextName)</exception>
public virtual object GetObject(string model, Database db, Rendering renderingItem)
{
if (model.IsNullOrEmpty())
return null;
//must be a path to a Model item
if (model.StartsWith("/sitecore"))
{
var target = db.GetItem(model);
if (target == null)
return null;
string newModel = target[ModelTypeField];
return GetObject(newModel, db, renderingItem);
}
//if guid must be that to Model item
Guid targetId;
if (Guid.TryParse(model, out targetId))
{
var target = db.GetItem(new ID(targetId));
if (target == null)
return null;
string newModel = target[ModelTypeField];
return GetObject(newModel, db, renderingItem);
}
var type = Type.GetType(model, false);
if (type == null || renderingModelType.IsAssignableFrom(type))
return null;
ISitecoreContext scContext = SitecoreContextFactory.GetSitecoreContext();
//this is really aggressive
if (!scContext.GlassContext.TypeConfigurations.ContainsKey(type))
{
//if the config is null then it is probably an ondemand mapping so we have to load the ondemand part
IConfigurationLoader loader =
new OnDemandLoader<SitecoreTypeConfiguration>(type);
scContext.GlassContext.Load(loader);
}
if (renderingItem.DataSource.IsNotNullOrEmpty())
{
var item = scContext.Database.GetItem(renderingItem.DataSource);
return scContext.CreateType(type, item, false, false, null);
}
if (renderingItem.RenderingItem.DataSource.HasValue())
{
var item = scContext.Database.GetItem(renderingItem.RenderingItem.DataSource);
return scContext.CreateType(type, item, false, false, null);
}
/**
* Issues #82:
* Check Item before defaulting to the current item.
*/
if (renderingItem.Item != null)
{
return scContext.CreateType(type, renderingItem.Item, false, false, null);
}
return scContext.GetCurrentItem(type);
}
}
}
| |
// 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.Composition;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
[ExportWorkspaceService(typeof(ISolutionCrawlerRegistrationService), ServiceLayer.Host), Shared]
internal partial class SolutionCrawlerRegistrationService : ISolutionCrawlerRegistrationService
{
private const string Default = "*";
private readonly object _gate;
private readonly SolutionCrawlerProgressReporter _progressReporter;
private readonly IAsynchronousOperationListener _listener;
private readonly ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> _analyzerProviders;
private readonly Dictionary<Workspace, WorkCoordinator> _documentWorkCoordinatorMap;
[ImportingConstructor]
public SolutionCrawlerRegistrationService(
[ImportMany] IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders,
[ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners)
{
_gate = new object();
_analyzerProviders = analyzerProviders.GroupBy(kv => kv.Metadata.Name).ToImmutableDictionary(g => g.Key, g => g.ToImmutableArray());
AssertAnalyzerProviders(_analyzerProviders);
_documentWorkCoordinatorMap = new Dictionary<Workspace, WorkCoordinator>(ReferenceEqualityComparer.Instance);
_listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.SolutionCrawler);
_progressReporter = new SolutionCrawlerProgressReporter(_listener);
}
public void Register(Workspace workspace)
{
var correlationId = LogAggregator.GetNextId();
lock (_gate)
{
if (_documentWorkCoordinatorMap.ContainsKey(workspace))
{
// already registered.
return;
}
var coordinator = new WorkCoordinator(
_listener,
GetAnalyzerProviders(workspace),
new Registration(correlationId, workspace, _progressReporter));
_documentWorkCoordinatorMap.Add(workspace, coordinator);
}
SolutionCrawlerLogger.LogRegistration(correlationId, workspace);
}
public void Unregister(Workspace workspace, bool blockingShutdown = false)
{
var coordinator = default(WorkCoordinator);
lock (_gate)
{
if (!_documentWorkCoordinatorMap.TryGetValue(workspace, out coordinator))
{
// already unregistered
return;
}
_documentWorkCoordinatorMap.Remove(workspace);
coordinator.Shutdown(blockingShutdown);
}
SolutionCrawlerLogger.LogUnregistration(coordinator.CorrelationId);
}
public void Reanalyze(Workspace workspace, IIncrementalAnalyzer analyzer, IEnumerable<ProjectId> projectIds, IEnumerable<DocumentId> documentIds, bool highPriority)
{
lock (_gate)
{
var coordinator = default(WorkCoordinator);
if (!_documentWorkCoordinatorMap.TryGetValue(workspace, out coordinator))
{
// this can happen if solution crawler is already unregistered from workspace.
// one of those example will be VS shutting down so roslyn package is disposed but there is a pending
// async operation.
return;
}
// no specific projects or documents provided
if (projectIds == null && documentIds == null)
{
coordinator.Reanalyze(analyzer, workspace.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet(), highPriority);
return;
}
// specific documents provided
if (projectIds == null)
{
coordinator.Reanalyze(analyzer, documentIds.ToSet(), highPriority);
return;
}
var solution = workspace.CurrentSolution;
var set = new HashSet<DocumentId>(documentIds ?? SpecializedCollections.EmptyEnumerable<DocumentId>());
set.UnionWith(projectIds.Select(id => solution.GetProject(id)).SelectMany(p => p.DocumentIds));
coordinator.Reanalyze(analyzer, set, highPriority);
}
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(Workspace workspace, ImmutableArray<IIncrementalAnalyzer> workers)
{
if (_documentWorkCoordinatorMap.ContainsKey(workspace))
{
_documentWorkCoordinatorMap[workspace].WaitUntilCompletion_ForTestingPurposesOnly(workers);
}
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(Workspace workspace)
{
if (_documentWorkCoordinatorMap.ContainsKey(workspace))
{
_documentWorkCoordinatorMap[workspace].WaitUntilCompletion_ForTestingPurposesOnly();
}
}
private IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> GetAnalyzerProviders(Workspace workspace)
{
Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata> lazyProvider;
foreach (var kv in _analyzerProviders)
{
var lazyProviders = kv.Value;
// try get provider for the specific workspace kind
if (TryGetProvider(workspace.Kind, lazyProviders, out lazyProvider))
{
yield return lazyProvider;
continue;
}
// try get default provider
if (TryGetProvider(Default, lazyProviders, out lazyProvider))
{
yield return lazyProvider;
}
}
}
private bool TryGetProvider(
string kind,
ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> lazyProviders,
out Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata> lazyProvider)
{
// set out param
lazyProvider = null;
// try find provider for specific workspace kind
if (kind != Default)
{
foreach (var provider in lazyProviders)
{
if (provider.Metadata.WorkspaceKinds?.Any(wk => wk == kind) == true)
{
lazyProvider = provider;
return true;
}
}
return false;
}
// try find default provider
foreach (var provider in lazyProviders)
{
if (IsDefaultProvider(provider.Metadata))
{
lazyProvider = provider;
return true;
}
return false;
}
return false;
}
[Conditional("DEBUG")]
private static void AssertAnalyzerProviders(
ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> analyzerProviders)
{
#if DEBUG
// make sure there is duplicated provider defined for same workspace.
var set = new HashSet<string>();
foreach (var kv in analyzerProviders)
{
foreach (var lazyProvider in kv.Value)
{
if (IsDefaultProvider(lazyProvider.Metadata))
{
Contract.Requires(set.Add(Default));
continue;
}
foreach (var kind in lazyProvider.Metadata.WorkspaceKinds)
{
Contract.Requires(set.Add(kind));
}
}
set.Clear();
}
#endif
}
private static bool IsDefaultProvider(IncrementalAnalyzerProviderMetadata providerMetadata)
{
return providerMetadata.WorkspaceKinds == null || providerMetadata.WorkspaceKinds.Length == 0;
}
private class Registration
{
public readonly int CorrelationId;
public readonly Workspace Workspace;
public readonly SolutionCrawlerProgressReporter ProgressReporter;
public Registration(int correlationId, Workspace workspace, SolutionCrawlerProgressReporter progressReporter)
{
CorrelationId = correlationId;
Workspace = workspace;
ProgressReporter = progressReporter;
}
public Solution CurrentSolution
{
get { return Workspace.CurrentSolution; }
}
public TService GetService<TService>() where TService : IWorkspaceService
{
return Workspace.Services.GetService<TService>();
}
}
}
}
| |
#if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API
using System;
using System.Collections.Generic;
using PlayFab.Internal;
namespace PlayFab
{
/// <summary>
/// <para />APIs which allow game servers to subscribe to PlayStream events for a specific title
/// <para />This API is server only, and should NEVER be used on clients.
/// </summary>
public static class PlayFabPlayStreamAPI
{
static PlayFabPlayStreamAPI() { }
/// <summary>
/// The event when successfully subcribed to PlayStream.
/// </summary>
public static event Action OnSubscribed;
/// <summary>
/// The event when failed to subcribe events from PlayStream server.
/// </summary>
public static event Action<SubscriptionError> OnFailed;
/// <summary>
/// <para />This is the event when a PlayStream event is received from the server.
/// </summary>
public static event Action<PlayStreamNotification> OnPlayStreamEvent;
#region Connection Status Events
/// <summary>
/// The debug event when reconnected to the PlayStream server.
/// </summary>
public static event Action OnReconnected;
/// <summary>
/// The debug event when received anything from the PlayStream server. This gives the raw message received from the server and should be used for debug purposes.
/// </summary>
public static event Action<string> OnReceived;
/// <summary>
/// The debug event when an error occurs.
/// </summary>
public static event Action<Exception> OnError;
/// <summary>
/// The debug event when disconnected from the PlayStream server.
/// </summary>
public static event Action OnDisconnected;
#endregion
/// <summary>
/// Start the SignalR connection asynchronously and subscribe to PlayStream events if successfully connected.
/// Optionally pass an filter id to only be subscribed to specific types of PlayStream events. Event filters can be configured on GameManager.
/// </summary>
public static void Start(string eventFilterId = null)
{
Action connetionCallback = () =>
{
OnConnectedCallback(eventFilterId);
};
PlayFabHttp.InitializeSignalR(PlayFabSettings.ProductionEnvironmentPlayStreamUrl, "EventStreamsHub", connetionCallback, OnReceivedCallback, OnReconnectedCallback, OnDisconnectedCallback, OnErrorCallback);
}
/// <summary>
/// Sends a disconnect request to the server and stop the SignalR connection.
/// </summary>
public static void Stop()
{
PlayFabHttp.StopSignalR();
}
#region Connection Callbacks
private static void OnConnectedCallback(string filter)
{
PlayFabHttp.SubscribeSignalR("notifyNewMessage", OnPlayStreamNotificationCallback);
PlayFabHttp.SubscribeSignalR("notifySubscriptionError", OnSubscriptionErrorCallback);
PlayFabHttp.SubscribeSignalR("notifySubscriptionSuccess", OnSubscriptionSuccessCallback);
var queueRequest = new
{
TitleId = PlayFabSettings.TitleId,
TitleSecret = PlayFabSettings.DeveloperSecretKey,
BackFill = false,
EventFilter = filter
};
PlayFabHttp.InvokeSignalR("SubscribeToQueue", null, queueRequest);
}
private static void OnPlayStreamNotificationCallback(object[] data)
{
var notif = Json.JsonWrapper.DeserializeObject<PlayStreamNotification>(data[0].ToString());
if (OnPlayStreamEvent != null)
{
OnPlayStreamEvent(notif);
}
}
private static void OnSubscriptionErrorCallback(object[] data)
{
var message = data[0] as string;
if (OnFailed != null)
{
if (message == "Invalid Title Secret Key!")
{
OnFailed(SubscriptionError.InvalidSecretKey);
}
else
{
OnFailed(SubscriptionError.FailWithUnexpected(message));
}
}
}
private static void OnSubscriptionSuccessCallback(object[] data)
{
if (OnSubscribed != null)
{
OnSubscribed();
}
}
private static void OnReconnectedCallback()
{
if (OnReconnected != null)
{
OnReconnected();
}
}
private static void OnReceivedCallback(string msg)
{
if (OnReceived != null)
{
OnReceived(msg);
}
}
private static void OnErrorCallback(Exception ex)
{
var timeoutEx = ex as TimeoutException;
if (timeoutEx != null)
{
if (OnFailed != null)
{
OnFailed(SubscriptionError.ConnectionTimeout);
}
}
else
{
if (OnError != null)
{
OnError(ex);
}
}
}
private static void OnDisconnectedCallback()
{
if (OnDisconnected != null)
{
OnDisconnected();
}
}
#endregion
}
/// <summary>
/// <para />The server message wrapper for PlayStream events.
/// <para />Should be used to deserialize EventObject into its appropriate types by EventName, TntityType, and EventNamespace. Do not modify.
/// </summary>
public sealed class PlayStreamNotification
{
//metadata sent by server
public string EventName;
public string EntityType;
public string EventNamespace;
public string PlayerId;
public string TitleId;
public PlayStreamEvent EventObject;
public PlayerProfile Profile;
public List<object> TriggerResults;
public List<object> SegmentMatchResults;
public class PlayStreamEvent
{
public object EventData;
public object InternalState;
}
public class PlayerProfile
{
public string PlayerId;
public string TitleId;
public object DisplayName;
public string Origination;
public object Created;
public object LastLogin;
public object BannedUntil;
public Dictionary<string, int> Statistics;
public Dictionary<string, int> VirtualCurrencyBalances;
public List<object> AdCampaignAttributions;
public List<object> PushNotificationRegistrations;
public List<LinkedAccount> LinkedAccounts;
public class LinkedAccount
{
public string Platform;
public string PlatformUserId;
}
}
}
/// <summary>
/// The error code of PlayStream subscription result.
/// </summary>
public struct SubscriptionError
{
public ErrorCode Code;
public string Message;
public enum ErrorCode
{
Unexpected = 400,
ConnectionTimeout = 401,
InvalidSecretKey = 402
}
public static SubscriptionError ConnectionTimeout
{
get
{
return new SubscriptionError() { Message = "Connection Timeout", Code = ErrorCode.ConnectionTimeout };
}
}
public static SubscriptionError InvalidSecretKey
{
get
{
return new SubscriptionError() { Message = "Invalid Secret Key", Code = ErrorCode.InvalidSecretKey };
}
}
public static SubscriptionError FailWithUnexpected(string message)
{
return new SubscriptionError() { Message = message, Code = ErrorCode.Unexpected };
}
}
}
#endif
| |
/*
* Copyright 2012-2021 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 <[email protected]>
*/
using System;
using System.Text;
// Note: Code in this file is maintained manually.
namespace Net.Pkcs11Interop.Common
{
/// <summary>
/// Utility class that helps with data type conversions.
/// </summary>
public static partial class ConvertUtils
{
#region Bool <-> Bytes
/// <summary>
/// Converts bool to byte array
/// </summary>
/// <param name='value'>Bool that should be converted</param>
/// <returns>Byte array with bool value</returns>
public static byte[] BoolToBytes(bool value)
{
byte[] bytes = BitConverter.GetBytes(value);
// Cryptoki uses boolean flag with size of 1 byte
int unmanagedSize = 1;
if (unmanagedSize != bytes.Length)
throw new Exception(string.Format("Unmanaged size of bool ({0}) does not match the length of produced byte array ({1})", unmanagedSize, bytes.Length));
return bytes;
}
/// <summary>
/// Converts byte array to bool
/// </summary>
/// <param name='value'>Byte array that should be converted</param>
/// <returns>Bool with value from byte array</returns>
public static bool BytesToBool(byte[] value)
{
// Cryptoki uses boolean flag with size of 1 byte
if ((value == null) || (value.Length != 1))
throw new Exception("Unable to convert bytes to bool");
return BitConverter.ToBoolean(value, 0);
}
#endregion
#region Utf8String <-> Bytes
/// <summary>
/// Converts UTF-8 string to byte array (not null terminated)
/// </summary>
/// <param name='value'>String that should be converted</param>
/// <returns>Byte array with string value</returns>
public static byte[] Utf8StringToBytes(string value)
{
return (value == null) ? null : UTF8Encoding.UTF8.GetBytes(value);
}
/// <summary>
/// Converts UTF-8 string to byte array padded or trimmed to specified length
/// </summary>
/// <param name='value'>String that should be converted</param>
/// <param name='outputLength'>Expected length of byte array</param>
/// <param name='paddingByte'>Padding byte that will be used for padding to expected length</param>
/// <returns>Byte array with string value padded or trimmed to specified length</returns>
public static byte[] Utf8StringToBytes(string value, int outputLength, byte paddingByte)
{
if (outputLength < 1)
throw new ArgumentException("Value has to be positive number", "outputLength");
byte[] output = new byte[outputLength];
for (int i = 0; i < outputLength; i++)
output[i] = paddingByte;
if (value != null)
{
byte[] bytes = ConvertUtils.Utf8StringToBytes(value);
if (bytes.Length > outputLength)
Array.Copy(bytes, 0, output, 0, outputLength);
else
Array.Copy(bytes, 0, output, 0, bytes.Length);
}
return output;
}
/// <summary>
/// Converts byte array (not null terminated) to UTF-8 string
/// </summary>
/// <param name='value'>Byte array that should be converted</param>
/// <returns>String with value from byte array</returns>
public static string BytesToUtf8String(byte[] value)
{
return (value == null) ? null : Encoding.UTF8.GetString(value, 0, value.Length);
}
/// <summary>
/// Converts byte array to UTF-8 string (not null terminated)
/// </summary>
/// <param name='value'>Byte array that should be converted</param>
/// <param name='trimEnd'>Flag indicating whether white space characters should be removed from the end of resulting string</param>
/// <returns>String with value from byte array</returns>
public static string BytesToUtf8String(byte[] value, bool trimEnd)
{
string result = BytesToUtf8String(value);
if ((value != null) && (trimEnd))
result = result.TrimEnd(null);
return result;
}
/// <summary>
/// Converts specified range of byte array to UTF-8 string (not null terminated)
/// </summary>
/// <param name='value'>Byte array that should be processed</param>
/// <param name='index'>Starting index of bytes to decode</param>
/// <param name='count'>Number of bytes to decode</param>
/// <returns>String with value from byte array</returns>
public static string BytesToUtf8String(byte[] value, int index, int count)
{
return (value == null) ? null : UTF8Encoding.UTF8.GetString(value, index, count);
}
#endregion
#region UtcTimeString <-> DateTime
/// <summary>
/// Converts string with UTC time to DateTime
/// </summary>
/// <param name='utcTime'>UTC time that should be converted (formatted as string of length 16 represented in the format YYYYMMDDhhmmssxx).</param>
/// <returns>DateTime if successful, null otherwise.</returns>
public static DateTime? UtcTimeStringToDateTime(string utcTime)
{
DateTime? dateTime = null;
if (!string.IsNullOrEmpty(utcTime))
{
if (utcTime.Length == 16)
{
int year = Int32.Parse(utcTime.Substring(0, 4));
int month = Int32.Parse(utcTime.Substring(4, 2));
int day = Int32.Parse(utcTime.Substring(6, 2));
int hour = Int32.Parse(utcTime.Substring(8, 2));
int minute = Int32.Parse(utcTime.Substring(10, 2));
int second = Int32.Parse(utcTime.Substring(12, 2));
int millisecond = Int32.Parse(utcTime.Substring(14, 2));
dateTime = new DateTime(year, month, day, hour, minute, second, millisecond, DateTimeKind.Utc);
}
}
return dateTime;
}
#endregion
#region String <-> HexString
/// <summary>
/// Converts byte array to hex encoded string
/// </summary>
/// <param name='value'>Byte array that should be converted</param>
/// <returns>String with hex encoded value from byte array</returns>
public static string BytesToHexString(byte[] value)
{
if (value == null)
return null;
return BitConverter.ToString(value).Replace("-", "");
}
/// <summary>
/// Converts hex encoded string to byte array
/// </summary>
/// <param name="value">String that should be converted</param>
/// <returns>Byte array decoded from string</returns>
public static byte[] HexStringToBytes(string value)
{
if (value == null)
return null;
if ((value.Length % 2) != 0)
throw new ArgumentException("Hex encoded string must contain an even number of characters", "value");
byte[] bytes = new byte[value.Length / 2];
for (int i = 0; i < value.Length; i += 2)
bytes[i / 2] = Convert.ToByte(value.Substring(i, 2), 16);
return bytes;
}
#endregion
#region String <-> Base64String
/// <summary>
/// Converts byte array to Base64 encoded string
/// </summary>
/// <param name='value'>Byte array that should be converted</param>
/// <returns>String with Base64 encoded value from byte array</returns>
public static string BytesToBase64String(byte[] value)
{
return Convert.ToBase64String(value);
}
/// <summary>
/// Converts Base64 encoded string to byte array
/// </summary>
/// <param name="value">String that should be converted</param>
/// <returns>Byte array decoded from string</returns>
public static byte[] Base64StringToBytes(string value)
{
return Convert.FromBase64String(value);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Provider;
using Dbg = System.Management.Automation;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The base class for the */content commands.
/// </summary>
public class ContentCommandBase : CoreCommandWithCredentialsBase, IDisposable
{
#region Parameters
/// <summary>
/// Gets or sets the path parameter to the command.
/// </summary>
[Parameter(Position = 0, ParameterSetName = "Path",
Mandatory = true, ValueFromPipelineByPropertyName = true)]
public string[] Path { get; set; }
/// <summary>
/// Gets or sets the literal path parameter to the command.
/// </summary>
[Parameter(ParameterSetName = "LiteralPath",
Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)]
[Alias("PSPath", "LP")]
public string[] LiteralPath
{
get { return Path; }
set
{
base.SuppressWildcardExpansion = true;
Path = value;
}
}
/// <summary>
/// Gets or sets the filter property.
/// </summary>
[Parameter]
public override string Filter
{
get { return base.Filter; }
set { base.Filter = value; }
}
/// <summary>
/// Gets or sets the include property.
/// </summary>
[Parameter]
public override string[] Include
{
get { return base.Include; }
set { base.Include = value; }
}
/// <summary>
/// Gets or sets the exclude property.
/// </summary>
[Parameter]
public override string[] Exclude
{
get { return base.Exclude; }
set { base.Exclude = value; }
}
/// <summary>
/// Gets or sets the force property.
/// </summary>
/// <remarks>
/// Gives the provider guidance on how vigorous it should be about performing
/// the operation. If true, the provider should do everything possible to perform
/// the operation. If false, the provider should attempt the operation but allow
/// even simple errors to terminate the operation.
/// For example, if the user tries to copy a file to a path that already exists and
/// the destination is read-only, if force is true, the provider should copy over
/// the existing read-only file. If force is false, the provider should write an error.
/// </remarks>
[Parameter]
public override SwitchParameter Force
{
get { return base.Force; }
set { base.Force = value; }
}
#endregion Parameters
#region parameter data
#endregion parameter data
#region protected members
/// <summary>
/// An array of content holder objects that contain the path information
/// and content readers/writers for the item represented by the path information.
/// </summary>
internal List<ContentHolder> contentStreams = new List<ContentHolder>();
/// <summary>
/// Wraps the content into a PSObject and adds context information as notes.
/// </summary>
/// <param name="content">
/// The content being written out.
/// </param>
/// <param name="readCount">
/// The number of blocks that have been read so far.
/// </param>
/// <param name="pathInfo">
/// The context the content was retrieved from.
/// </param>
/// <param name="context">
/// The context the command is being run under.
/// </param>
internal void WriteContentObject(object content, long readCount, PathInfo pathInfo, CmdletProviderContext context)
{
Dbg.Diagnostics.Assert(
content != null,
"The caller should verify the content.");
Dbg.Diagnostics.Assert(
pathInfo != null,
"The caller should verify the pathInfo.");
Dbg.Diagnostics.Assert(
context != null,
"The caller should verify the context.");
PSObject result = PSObject.AsPSObject(content);
Dbg.Diagnostics.Assert(
result != null,
"A PSObject should always be constructed.");
// Use the cached notes if the cache exists and the path is still the same
PSNoteProperty note;
if (_currentContentItem != null &&
((_currentContentItem.PathInfo == pathInfo) ||
(
string.Compare(
pathInfo.Path,
_currentContentItem.PathInfo.Path,
StringComparison.OrdinalIgnoreCase) == 0)
)
)
{
result = _currentContentItem.AttachNotes(result);
}
else
{
// Generate a new cache item and cache the notes
_currentContentItem = new ContentPathsCache(pathInfo);
// Construct a provider qualified path as the Path note
string psPath = pathInfo.Path;
note = new PSNoteProperty("PSPath", psPath);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSPath", psPath);
_currentContentItem.PSPath = psPath;
try
{
// Now get the parent path and child name
string parentPath = null;
if (pathInfo.Drive != null)
{
parentPath = SessionState.Path.ParseParent(pathInfo.Path, pathInfo.Drive.Root, context);
}
else
{
parentPath = SessionState.Path.ParseParent(pathInfo.Path, string.Empty, context);
}
note = new PSNoteProperty("PSParentPath", parentPath);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", parentPath);
_currentContentItem.ParentPath = parentPath;
// Get the child name
string childName = SessionState.Path.ParseChildName(pathInfo.Path, context);
note = new PSNoteProperty("PSChildName", childName);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSChildName", childName);
_currentContentItem.ChildName = childName;
}
catch (NotSupportedException)
{
// Ignore. The object just won't have ParentPath or ChildName set.
}
// PSDriveInfo
if (pathInfo.Drive != null)
{
PSDriveInfo drive = pathInfo.Drive;
note = new PSNoteProperty("PSDrive", drive);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSDrive", drive);
_currentContentItem.Drive = drive;
}
// ProviderInfo
ProviderInfo provider = pathInfo.Provider;
note = new PSNoteProperty("PSProvider", provider);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSProvider", provider);
_currentContentItem.Provider = provider;
}
// Add the ReadCount note
note = new PSNoteProperty("ReadCount", readCount);
result.Properties.Add(note, true);
WriteObject(result);
}
/// <summary>
/// A cache of the notes that get added to the content items as they are written
/// to the pipeline.
/// </summary>
private ContentPathsCache _currentContentItem;
/// <summary>
/// A class that stores a cache of the notes that get attached to content items
/// as they get written to the pipeline. An instance of this cache class is
/// only valid for a single path.
/// </summary>
internal class ContentPathsCache
{
/// <summary>
/// Constructs a content cache item.
/// </summary>
/// <param name="pathInfo">
/// The path information for which the cache will be bound.
/// </param>
public ContentPathsCache(PathInfo pathInfo)
{
PathInfo = pathInfo;
}
/// <summary>
/// The path information for the cached item.
/// </summary>
public PathInfo PathInfo { get; }
/// <summary>
/// The cached PSPath of the item.
/// </summary>
public string PSPath { get; set; }
/// <summary>
/// The cached parent path of the item.
/// </summary>
public string ParentPath { get; set; }
/// <summary>
/// The cached drive for the item.
/// </summary>
public PSDriveInfo Drive { get; set; }
/// <summary>
/// The cached provider of the item.
/// </summary>
public ProviderInfo Provider { get; set; }
/// <summary>
/// The cached child name of the item.
/// </summary>
public string ChildName { get; set; }
/// <summary>
/// Attaches the cached notes to the specified PSObject.
/// </summary>
/// <param name="content">
/// The PSObject to attached the cached notes to.
/// </param>
/// <returns>
/// The PSObject that was passed in with the cached notes added.
/// </returns>
public PSObject AttachNotes(PSObject content)
{
// Construct a provider qualified path as the Path note
PSNoteProperty note = new PSNoteProperty("PSPath", PSPath);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSPath", PSPath);
// Now attach the parent path and child name
note = new PSNoteProperty("PSParentPath", ParentPath);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", ParentPath);
// Attach the child name
note = new PSNoteProperty("PSChildName", ChildName);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSChildName", ChildName);
// PSDriveInfo
if (PathInfo.Drive != null)
{
note = new PSNoteProperty("PSDrive", Drive);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSDrive", Drive);
}
// ProviderInfo
note = new PSNoteProperty("PSProvider", Provider);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSProvider", Provider);
return content;
}
}
/// <summary>
/// A struct to hold the path information and the content readers/writers
/// for an item.
/// </summary>
internal struct ContentHolder
{
internal ContentHolder(
PathInfo pathInfo,
IContentReader reader,
IContentWriter writer)
{
if (pathInfo == null)
{
throw PSTraceSource.NewArgumentNullException("pathInfo");
}
PathInfo = pathInfo;
Reader = reader;
Writer = writer;
}
internal PathInfo PathInfo { get; }
internal IContentReader Reader { get; }
internal IContentWriter Writer { get; }
}
/// <summary>
/// Closes the content readers and writers in the content holder array.
/// </summary>
internal void CloseContent(List<ContentHolder> contentHolders, bool disposing)
{
if (contentHolders == null)
{
throw PSTraceSource.NewArgumentNullException("contentHolders");
}
foreach (ContentHolder holder in contentHolders)
{
try
{
if (holder.Writer != null)
{
holder.Writer.Close();
}
}
catch (Exception e) // Catch-all OK. 3rd party callout
{
// Catch all the exceptions caused by closing the writer
// and write out an error.
ProviderInvocationException providerException =
new ProviderInvocationException(
"ProviderContentCloseError",
SessionStateStrings.ProviderContentCloseError,
holder.PathInfo.Provider,
holder.PathInfo.Path,
e);
// Log a provider health event
MshLog.LogProviderHealthEvent(
this.Context,
holder.PathInfo.Provider.Name,
providerException,
Severity.Warning);
if (!disposing)
{
WriteError(
new ErrorRecord(
providerException.ErrorRecord,
providerException));
}
}
try
{
if (holder.Reader != null)
{
holder.Reader.Close();
}
}
catch (Exception e) // Catch-all OK. 3rd party callout
{
// Catch all the exceptions caused by closing the writer
// and write out an error.
ProviderInvocationException providerException =
new ProviderInvocationException(
"ProviderContentCloseError",
SessionStateStrings.ProviderContentCloseError,
holder.PathInfo.Provider,
holder.PathInfo.Path,
e);
// Log a provider health event
MshLog.LogProviderHealthEvent(
this.Context,
holder.PathInfo.Provider.Name,
providerException,
Severity.Warning);
if (!disposing)
{
WriteError(
new ErrorRecord(
providerException.ErrorRecord,
providerException));
}
}
}
}
/// <summary>
/// Overridden by derived classes to support ShouldProcess with
/// the appropriate information.
/// </summary>
/// <param name="path">
/// The path to the item from which the content writer will be
/// retrieved.
/// </param>
/// <returns>
/// True if the action should continue or false otherwise.
/// </returns>
internal virtual bool CallShouldProcess(string path)
{
return true;
}
/// <summary>
/// Gets the IContentReaders for the current path(s)
/// </summary>
/// <returns>
/// An array of IContentReaders for the current path(s)
/// </returns>
internal List<ContentHolder> GetContentReaders(
string[] readerPaths,
CmdletProviderContext currentCommandContext)
{
// Resolve all the paths into PathInfo objects
Collection<PathInfo> pathInfos = ResolvePaths(readerPaths, false, true, currentCommandContext);
// Create the results array
List<ContentHolder> results = new List<ContentHolder>();
foreach (PathInfo pathInfo in pathInfos)
{
// For each path, get the content writer
Collection<IContentReader> readers = null;
try
{
string pathToProcess = WildcardPattern.Escape(pathInfo.Path);
if (currentCommandContext.SuppressWildcardExpansion)
{
pathToProcess = pathInfo.Path;
}
readers =
InvokeProvider.Content.GetReader(pathToProcess, currentCommandContext);
}
catch (PSNotSupportedException notSupported)
{
WriteError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
continue;
}
catch (DriveNotFoundException driveNotFound)
{
WriteError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
continue;
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
continue;
}
catch (ItemNotFoundException pathNotFound)
{
WriteError(
new ErrorRecord(
pathNotFound.ErrorRecord,
pathNotFound));
continue;
}
if (readers != null && readers.Count > 0)
{
if (readers.Count == 1 && readers[0] != null)
{
ContentHolder holder =
new ContentHolder(pathInfo, readers[0], null);
results.Add(holder);
}
}
}
return results;
}
/// <summary>
/// Resolves the specified paths to PathInfo objects.
/// </summary>
/// <param name="pathsToResolve">
/// The paths to be resolved. Each path may contain glob characters.
/// </param>
/// <param name="allowNonexistingPaths">
/// If true, resolves the path even if it doesn't exist.
/// </param>
/// <param name="allowEmptyResult">
/// If true, allows a wildcard that returns no results.
/// </param>
/// <param name="currentCommandContext">
/// The context under which the command is running.
/// </param>
/// <returns>
/// An array of PathInfo objects that are the resolved paths for the
/// <paramref name="pathsToResolve"/> parameter.
/// </returns>
internal Collection<PathInfo> ResolvePaths(
string[] pathsToResolve,
bool allowNonexistingPaths,
bool allowEmptyResult,
CmdletProviderContext currentCommandContext)
{
Collection<PathInfo> results = new Collection<PathInfo>();
foreach (string path in pathsToResolve)
{
bool pathNotFound = false;
bool filtersHidPath = false;
ErrorRecord pathNotFoundErrorRecord = null;
try
{
// First resolve each of the paths
Collection<PathInfo> pathInfos =
SessionState.Path.GetResolvedPSPathFromPSPath(
path,
currentCommandContext);
if (pathInfos.Count == 0)
{
pathNotFound = true;
// If the item simply did not exist,
// we would have got an ItemNotFoundException.
// If we get here, it's because the filters
// excluded the file.
if (!currentCommandContext.SuppressWildcardExpansion)
{
filtersHidPath = true;
}
}
foreach (PathInfo pathInfo in pathInfos)
{
results.Add(pathInfo);
}
}
catch (PSNotSupportedException notSupported)
{
WriteError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
}
catch (DriveNotFoundException driveNotFound)
{
WriteError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
}
catch (ItemNotFoundException pathNotFoundException)
{
pathNotFound = true;
pathNotFoundErrorRecord = new ErrorRecord(pathNotFoundException.ErrorRecord, pathNotFoundException);
}
if (pathNotFound)
{
if (allowNonexistingPaths &&
(!filtersHidPath) &&
(currentCommandContext.SuppressWildcardExpansion ||
(!WildcardPattern.ContainsWildcardCharacters(path))))
{
ProviderInfo provider = null;
PSDriveInfo drive = null;
string unresolvedPath =
SessionState.Path.GetUnresolvedProviderPathFromPSPath(
path,
currentCommandContext,
out provider,
out drive);
PathInfo pathInfo =
new PathInfo(
drive,
provider,
unresolvedPath,
SessionState);
results.Add(pathInfo);
}
else
{
if (pathNotFoundErrorRecord == null)
{
// Detect if the path resolution failed to resolve to a file.
string error = StringUtil.Format(NavigationResources.ItemNotFound, Path);
Exception e = new Exception(error);
pathNotFoundErrorRecord = new ErrorRecord(
e,
"ItemNotFound",
ErrorCategory.ObjectNotFound,
Path);
}
WriteError(pathNotFoundErrorRecord);
}
}
}
return results;
}
#endregion protected members
#region IDisposable
internal void Dispose(bool isDisposing)
{
if (isDisposing)
{
CloseContent(contentStreams, true);
contentStreams = new List<ContentHolder>();
}
}
/// <summary>
/// Dispose method in IDisposable.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Finalizer.
/// </summary>
~ContentCommandBase()
{
Dispose(false);
}
#endregion IDisposable
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="iCall.PeriodicHandlerBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonTimeStamp))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(iCallPeriodicHandlerExpiry))]
public partial class iCallPeriodicHandler : iControlInterface {
public iCallPeriodicHandler() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
public void create(
string [] handlers,
string [] scripts,
long [] intervals
) {
this.Invoke("create", new object [] {
handlers,
scripts,
intervals});
}
public System.IAsyncResult Begincreate(string [] handlers,string [] scripts,long [] intervals, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
handlers,
scripts,
intervals}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_handlers
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
public void delete_all_handlers(
) {
this.Invoke("delete_all_handlers", new object [0]);
}
public System.IAsyncResult Begindelete_all_handlers(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_handlers", new object[0], callback, asyncState);
}
public void Enddelete_all_handlers(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_handler
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
public void delete_handler(
string [] handlers
) {
this.Invoke("delete_handler", new object [] {
handlers});
}
public System.IAsyncResult Begindelete_handler(string [] handlers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_handler", new object[] {
handlers}, callback, asyncState);
}
public void Enddelete_handler(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] handlers
) {
object [] results = this.Invoke("get_description", new object [] {
handlers});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] handlers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
handlers}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_first_occurrence
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonTimeStamp [] get_first_occurrence(
string [] handlers
) {
object [] results = this.Invoke("get_first_occurrence", new object [] {
handlers});
return ((CommonTimeStamp [])(results[0]));
}
public System.IAsyncResult Beginget_first_occurrence(string [] handlers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_first_occurrence", new object[] {
handlers}, callback, asyncState);
}
public CommonTimeStamp [] Endget_first_occurrence(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonTimeStamp [])(results[0]));
}
//-----------------------------------------------------------------------
// get_handler_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public iCallGeneralHandlerState [] get_handler_state(
string [] handlers
) {
object [] results = this.Invoke("get_handler_state", new object [] {
handlers});
return ((iCallGeneralHandlerState [])(results[0]));
}
public System.IAsyncResult Beginget_handler_state(string [] handlers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_handler_state", new object[] {
handlers}, callback, asyncState);
}
public iCallGeneralHandlerState [] Endget_handler_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((iCallGeneralHandlerState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_interval
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_interval(
string [] handlers
) {
object [] results = this.Invoke("get_interval", new object [] {
handlers});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_interval(string [] handlers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_interval", new object[] {
handlers}, callback, asyncState);
}
public long [] Endget_interval(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_last_occurrence
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public iCallPeriodicHandlerExpiry [] get_last_occurrence(
string [] handlers
) {
object [] results = this.Invoke("get_last_occurrence", new object [] {
handlers});
return ((iCallPeriodicHandlerExpiry [])(results[0]));
}
public System.IAsyncResult Beginget_last_occurrence(string [] handlers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_last_occurrence", new object[] {
handlers}, callback, asyncState);
}
public iCallPeriodicHandlerExpiry [] Endget_last_occurrence(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((iCallPeriodicHandlerExpiry [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_script
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_script(
string [] handlers
) {
object [] results = this.Invoke("get_script", new object [] {
handlers});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_script(string [] handlers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_script", new object[] {
handlers}, callback, asyncState);
}
public string [] Endget_script(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
public void set_description(
string [] handlers,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
handlers,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] handlers,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
handlers,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_first_occurrence
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
public void set_first_occurrence(
string [] handlers,
CommonTimeStamp [] occurrences
) {
this.Invoke("set_first_occurrence", new object [] {
handlers,
occurrences});
}
public System.IAsyncResult Beginset_first_occurrence(string [] handlers,CommonTimeStamp [] occurrences, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_first_occurrence", new object[] {
handlers,
occurrences}, callback, asyncState);
}
public void Endset_first_occurrence(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_handler_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
public void set_handler_state(
string [] handlers,
iCallGeneralHandlerState [] states
) {
this.Invoke("set_handler_state", new object [] {
handlers,
states});
}
public System.IAsyncResult Beginset_handler_state(string [] handlers,iCallGeneralHandlerState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_handler_state", new object[] {
handlers,
states}, callback, asyncState);
}
public void Endset_handler_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_interval
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
public void set_interval(
string [] handlers,
long [] intervals
) {
this.Invoke("set_interval", new object [] {
handlers,
intervals});
}
public System.IAsyncResult Beginset_interval(string [] handlers,long [] intervals, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_interval", new object[] {
handlers,
intervals}, callback, asyncState);
}
public void Endset_interval(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_last_occurrence
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
public void set_last_occurrence(
string [] handlers,
iCallPeriodicHandlerExpiry [] occurrences
) {
this.Invoke("set_last_occurrence", new object [] {
handlers,
occurrences});
}
public System.IAsyncResult Beginset_last_occurrence(string [] handlers,iCallPeriodicHandlerExpiry [] occurrences, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_last_occurrence", new object[] {
handlers,
occurrences}, callback, asyncState);
}
public void Endset_last_occurrence(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_script
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PeriodicHandler",
RequestNamespace="urn:iControl:iCall/PeriodicHandler", ResponseNamespace="urn:iControl:iCall/PeriodicHandler")]
public void set_script(
string [] handlers,
string [] scripts
) {
this.Invoke("set_script", new object [] {
handlers,
scripts});
}
public System.IAsyncResult Beginset_script(string [] handlers,string [] scripts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_script", new object[] {
handlers,
scripts}, callback, asyncState);
}
public void Endset_script(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
// ---------------------------------------------------------------------------
// Copyright (C) 2005 Microsoft Corporation All Rights Reserved
// ---------------------------------------------------------------------------
#pragma warning disable 1634, 1691
#define CODE_ANALYSIS
using System.CodeDom;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
namespace System.Workflow.Activities.Rules
{
#region RuleExpressionResult class hierarchy
public abstract class RuleExpressionResult
{
public abstract object Value { get; set; }
}
public class RuleLiteralResult : RuleExpressionResult
{
private object literal;
public RuleLiteralResult(object literal)
{
this.literal = literal;
}
public override object Value
{
get
{
return literal;
}
set
{
throw new InvalidOperationException(Messages.CannotWriteToExpression);
}
}
}
internal class RuleFieldResult : RuleExpressionResult
{
private object targetObject;
private FieldInfo fieldInfo;
public RuleFieldResult(object targetObject, FieldInfo fieldInfo)
{
if (fieldInfo == null)
throw new ArgumentNullException("fieldInfo");
this.targetObject = targetObject;
this.fieldInfo = fieldInfo;
}
public override object Value
{
get
{
#pragma warning disable 56503
if (!fieldInfo.IsStatic && targetObject == null)
{
// Accessing a non-static field from null target.
string message = string.Format(CultureInfo.CurrentCulture, Messages.TargetEvaluatedNullField, fieldInfo.Name);
RuleEvaluationException exception = new RuleEvaluationException(message);
exception.Data[RuleUserDataKeys.ErrorObject] = fieldInfo;
throw exception;
}
return fieldInfo.GetValue(targetObject);
#pragma warning restore 56503
}
set
{
if (!fieldInfo.IsStatic && targetObject == null)
{
// Accessing a non-static field from null target.
string message = string.Format(CultureInfo.CurrentCulture, Messages.TargetEvaluatedNullField, fieldInfo.Name);
RuleEvaluationException exception = new RuleEvaluationException(message);
exception.Data[RuleUserDataKeys.ErrorObject] = fieldInfo;
throw exception;
}
fieldInfo.SetValue(targetObject, value);
}
}
}
internal class RulePropertyResult : RuleExpressionResult
{
private PropertyInfo propertyInfo;
private object targetObject;
private object[] indexerArguments;
public RulePropertyResult(PropertyInfo propertyInfo, object targetObject, object[] indexerArguments)
{
if (propertyInfo == null)
throw new ArgumentNullException("propertyInfo");
this.targetObject = targetObject;
this.propertyInfo = propertyInfo;
this.indexerArguments = indexerArguments;
}
public override object Value
{
get
{
#pragma warning disable 56503
if (!propertyInfo.GetGetMethod(true).IsStatic && targetObject == null)
{
string message = string.Format(CultureInfo.CurrentCulture, Messages.TargetEvaluatedNullProperty, propertyInfo.Name);
RuleEvaluationException exception = new RuleEvaluationException(message);
exception.Data[RuleUserDataKeys.ErrorObject] = propertyInfo;
throw exception;
}
try
{
return propertyInfo.GetValue(targetObject, indexerArguments);
}
catch (TargetInvocationException e)
{
// if there is no inner exception, leave it untouched
if (e.InnerException == null)
throw;
string message = string.Format(CultureInfo.CurrentCulture, Messages.Error_PropertyGet,
RuleDecompiler.DecompileType(propertyInfo.ReflectedType), propertyInfo.Name, e.InnerException.Message);
throw new TargetInvocationException(message, e.InnerException);
}
#pragma warning restore 56503
}
set
{
if (!propertyInfo.GetSetMethod(true).IsStatic && targetObject == null)
{
string message = string.Format(CultureInfo.CurrentCulture, Messages.TargetEvaluatedNullProperty, propertyInfo.Name);
RuleEvaluationException exception = new RuleEvaluationException(message);
exception.Data[RuleUserDataKeys.ErrorObject] = propertyInfo;
throw exception;
}
try
{
propertyInfo.SetValue(targetObject, value, indexerArguments);
}
catch (TargetInvocationException e)
{
// if there is no inner exception, leave it untouched
if (e.InnerException == null)
throw;
string message = string.Format(CultureInfo.CurrentCulture, Messages.Error_PropertySet,
RuleDecompiler.DecompileType(propertyInfo.ReflectedType), propertyInfo.Name, e.InnerException.Message);
throw new TargetInvocationException(message, e.InnerException);
}
}
}
}
internal class RuleArrayElementResult : RuleExpressionResult
{
private Array targetArray;
private long[] indexerArguments;
public RuleArrayElementResult(Array targetArray, long[] indexerArguments)
{
if (targetArray == null)
throw new ArgumentNullException("targetArray");
if (indexerArguments == null)
throw new ArgumentNullException("indexerArguments");
this.targetArray = targetArray;
this.indexerArguments = indexerArguments;
}
public override object Value
{
get
{
return targetArray.GetValue(indexerArguments);
}
set
{
targetArray.SetValue(value, indexerArguments);
}
}
}
#endregion
#region RuleExecution Class
public class RuleExecution
{
private bool halted; // "Halt" was executed?
private Activity activity;
private object thisObject;
private RuleValidation validation;
private ActivityExecutionContext activityExecutionContext;
private RuleLiteralResult thisLiteralResult;
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")]
public RuleExecution(RuleValidation validation, object thisObject)
{
if (validation == null)
throw new ArgumentNullException("validation");
if (thisObject == null)
throw new ArgumentNullException("thisObject");
if (validation.ThisType != thisObject.GetType())
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, Messages.ValidationMismatch,
RuleDecompiler.DecompileType(validation.ThisType),
RuleDecompiler.DecompileType(thisObject.GetType())));
this.validation = validation;
this.activity = thisObject as Activity;
this.thisObject = thisObject;
this.thisLiteralResult = new RuleLiteralResult(thisObject);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")]
public RuleExecution(RuleValidation validation, object thisObject, ActivityExecutionContext activityExecutionContext)
: this(validation, thisObject)
{
this.activityExecutionContext = activityExecutionContext;
}
public object ThisObject
{
get { return thisObject; }
}
public Activity Activity
{
get
{
#pragma warning disable 56503
if (activity == null)
throw new InvalidOperationException(Messages.NoActivity);
return activity;
#pragma warning restore 56503
}
}
public RuleValidation Validation
{
get { return validation; }
set
{
if (value == null)
throw new ArgumentNullException("value");
validation = value;
}
}
public bool Halted
{
get { return halted; }
set { halted = value; }
}
public ActivityExecutionContext ActivityExecutionContext
{
get { return this.activityExecutionContext; }
}
internal RuleLiteralResult ThisLiteralResult
{
get { return this.thisLiteralResult; }
}
}
#endregion
#region RuleState internal class
internal class RuleState : IComparable
{
internal Rule Rule;
private ICollection<int> thenActionsActiveRules;
private ICollection<int> elseActionsActiveRules;
internal RuleState(Rule rule)
{
this.Rule = rule;
}
internal ICollection<int> ThenActionsActiveRules
{
get { return thenActionsActiveRules; }
set { thenActionsActiveRules = value; }
}
internal ICollection<int> ElseActionsActiveRules
{
get { return elseActionsActiveRules; }
set { elseActionsActiveRules = value; }
}
int IComparable.CompareTo(object obj)
{
RuleState other = obj as RuleState;
int compare = other.Rule.Priority.CompareTo(Rule.Priority);
if (compare == 0)
// if the priorities are the same, compare names (in ascending order)
compare = -other.Rule.Name.CompareTo(Rule.Name);
return compare;
}
}
#endregion
#region Tracking Argument
/// <summary>
/// Contains the name and condition result of a rule that has caused one or more actions to execute.
/// </summary>
[Serializable]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class RuleActionTrackingEvent
{
private string ruleName;
private bool conditionResult;
internal RuleActionTrackingEvent(string ruleName, bool conditionResult)
{
this.ruleName = ruleName;
this.conditionResult = conditionResult;
}
/// <summary>
/// The name of the rule that has caused one or more actions to execute.
/// </summary>
public string RuleName
{
get { return ruleName; }
}
/// <summary>
/// The rule's condition result: false means the "else" actions are executed; true means the "then" actions are executed.
/// </summary>
public bool ConditionResult
{
get { return conditionResult; }
}
}
#endregion
internal class Executor
{
#region Rule Set Executor
internal static IList<RuleState> Preprocess(RuleChainingBehavior behavior, ICollection<Rule> rules, RuleValidation validation, Tracer tracer)
{
// start by taking the active rules and make them into a list sorted by priority
List<RuleState> orderedRules = new List<RuleState>(rules.Count);
foreach (Rule r in rules)
{
if (r.Active)
orderedRules.Add(new RuleState(r));
}
orderedRules.Sort();
// Analyze the rules to match side-effects with dependencies.
// Note that the RuleSet needs to have been validated prior to this.
AnalyzeRules(behavior, orderedRules, validation, tracer);
// return the sorted list of rules
return orderedRules;
}
internal static void ExecuteRuleSet(IList<RuleState> orderedRules, RuleExecution ruleExecution, Tracer tracer, string trackingKey)
{
// keep track of rule execution
long[] executionCount = new long[orderedRules.Count];
bool[] satisfied = new bool[orderedRules.Count];
// clear the halted flag
ruleExecution.Halted = false;
ActivityExecutionContext activityExecutionContext = ruleExecution.ActivityExecutionContext;
// loop until we hit the end of the list
int current = 0;
while (current < orderedRules.Count)
{
RuleState currentRuleState = orderedRules[current];
// does this rule need to be evaluated?
if (!satisfied[current])
{
// yes, so evaluate it and determine the list of actions needed
if (tracer != null)
tracer.StartRule(currentRuleState.Rule.Name);
satisfied[current] = true;
bool result = currentRuleState.Rule.Condition.Evaluate(ruleExecution);
if (tracer != null)
tracer.RuleResult(currentRuleState.Rule.Name, result);
if (activityExecutionContext != null && currentRuleState.Rule.Name != null)
activityExecutionContext.TrackData(trackingKey, new RuleActionTrackingEvent(currentRuleState.Rule.Name, result));
ICollection<RuleAction> actions = (result) ?
currentRuleState.Rule.thenActions :
currentRuleState.Rule.elseActions;
ICollection<int> activeRules = result ?
currentRuleState.ThenActionsActiveRules :
currentRuleState.ElseActionsActiveRules;
// are there any actions to be performed?
if ((actions != null) && (actions.Count > 0))
{
++executionCount[current];
string ruleName = currentRuleState.Rule.Name;
if (tracer != null)
tracer.StartActions(ruleName, result);
// evaluate the actions
foreach (RuleAction action in actions)
{
action.Execute(ruleExecution);
// was Halt executed?
if (ruleExecution.Halted)
break;
}
// was Halt executed?
if (ruleExecution.Halted)
break;
// any fields updated?
if (activeRules != null)
{
foreach (int updatedRuleIndex in activeRules)
{
RuleState rs = orderedRules[updatedRuleIndex];
if (satisfied[updatedRuleIndex])
{
// evaluate at least once, or repeatedly if appropriate
if ((executionCount[updatedRuleIndex] == 0) || (rs.Rule.ReevaluationBehavior == RuleReevaluationBehavior.Always))
{
if (tracer != null)
tracer.TraceUpdate(ruleName, rs.Rule.Name);
satisfied[updatedRuleIndex] = false;
if (updatedRuleIndex < current)
current = updatedRuleIndex;
}
}
}
}
continue;
}
}
++current;
}
// no more rules to execute, so we are done
}
class RuleSymbolInfo
{
internal ICollection<string> conditionDependencies;
internal ICollection<string> thenSideEffects;
internal ICollection<string> elseSideEffects;
}
private static void AnalyzeRules(RuleChainingBehavior behavior, List<RuleState> ruleStates, RuleValidation validation, Tracer tracer)
{
int i;
int numRules = ruleStates.Count;
// if no chaining is required, then nothing to do
if (behavior == RuleChainingBehavior.None)
return;
// Analyze all the rules and collect all the dependencies & side-effects
RuleSymbolInfo[] ruleSymbols = new RuleSymbolInfo[numRules];
for (i = 0; i < numRules; ++i)
ruleSymbols[i] = AnalyzeRule(behavior, ruleStates[i].Rule, validation, tracer);
for (i = 0; i < numRules; ++i)
{
RuleState currentRuleState = ruleStates[i];
if (ruleSymbols[i].thenSideEffects != null)
{
currentRuleState.ThenActionsActiveRules = AnalyzeSideEffects(ruleSymbols[i].thenSideEffects, ruleSymbols);
if ((currentRuleState.ThenActionsActiveRules != null) && (tracer != null))
tracer.TraceThenTriggers(currentRuleState.Rule.Name, currentRuleState.ThenActionsActiveRules, ruleStates);
}
if (ruleSymbols[i].elseSideEffects != null)
{
currentRuleState.ElseActionsActiveRules = AnalyzeSideEffects(ruleSymbols[i].elseSideEffects, ruleSymbols);
if ((currentRuleState.ElseActionsActiveRules != null) && (tracer != null))
tracer.TraceElseTriggers(currentRuleState.Rule.Name, currentRuleState.ElseActionsActiveRules, ruleStates);
}
}
}
private static ICollection<int> AnalyzeSideEffects(ICollection<string> sideEffects, RuleSymbolInfo[] ruleSymbols)
{
Dictionary<int, object> affectedRules = new Dictionary<int, object>();
for (int i = 0; i < ruleSymbols.Length; ++i)
{
ICollection<string> dependencies = ruleSymbols[i].conditionDependencies;
if (dependencies == null)
{
continue;
}
foreach (string sideEffect in sideEffects)
{
bool match = false;
if (sideEffect.EndsWith("*", StringComparison.Ordinal))
{
foreach (string dependency in dependencies)
{
if (dependency.EndsWith("*", StringComparison.Ordinal))
{
// Strip the trailing "/*" from the dependency
string stripDependency = dependency.Substring(0, dependency.Length - 2);
// Strip the trailing "*" from the side-effect
string stripSideEffect = sideEffect.Substring(0, sideEffect.Length - 1);
string shortString;
string longString;
if (stripDependency.Length < stripSideEffect.Length)
{
shortString = stripDependency;
longString = stripSideEffect;
}
else
{
shortString = stripSideEffect;
longString = stripDependency;
}
// There's a match if the shorter string is a prefix of the longer string.
if (longString.StartsWith(shortString, StringComparison.Ordinal))
{
match = true;
break;
}
}
else
{
string stripSideEffect = sideEffect.Substring(0, sideEffect.Length - 1);
string stripDependency = dependency;
if (stripDependency.EndsWith("/", StringComparison.Ordinal))
stripDependency = stripDependency.Substring(0, stripDependency.Length - 1);
if (stripDependency.StartsWith(stripSideEffect, StringComparison.Ordinal))
{
match = true;
break;
}
}
}
}
else
{
// The side-effect did not end with a wildcard
foreach (string dependency in dependencies)
{
if (dependency.EndsWith("*", StringComparison.Ordinal))
{
// Strip the trailing "/*"
string stripDependency = dependency.Substring(0, dependency.Length - 2);
string shortString;
string longString;
if (stripDependency.Length < sideEffect.Length)
{
shortString = stripDependency;
longString = sideEffect;
}
else
{
shortString = sideEffect;
longString = stripDependency;
}
// There's a match if the shorter string is a prefix of the longer string.
if (longString.StartsWith(shortString, StringComparison.Ordinal))
{
match = true;
break;
}
}
else
{
// The side-effect must be a prefix of the dependency (or an exact match).
if (dependency.StartsWith(sideEffect, StringComparison.Ordinal))
{
match = true;
break;
}
}
}
}
if (match)
{
affectedRules[i] = null;
break;
}
}
}
return affectedRules.Keys;
}
private static RuleSymbolInfo AnalyzeRule(RuleChainingBehavior behavior, Rule rule, RuleValidation validator, Tracer tracer)
{
RuleSymbolInfo rsi = new RuleSymbolInfo();
if (rule.Condition != null)
{
rsi.conditionDependencies = rule.Condition.GetDependencies(validator);
if ((rsi.conditionDependencies != null) && (tracer != null))
tracer.TraceConditionSymbols(rule.Name, rsi.conditionDependencies);
}
if (rule.thenActions != null)
{
rsi.thenSideEffects = GetActionSideEffects(behavior, rule.thenActions, validator);
if ((rsi.thenSideEffects != null) && (tracer != null))
tracer.TraceThenSymbols(rule.Name, rsi.thenSideEffects);
}
if (rule.elseActions != null)
{
rsi.elseSideEffects = GetActionSideEffects(behavior, rule.elseActions, validator);
if ((rsi.elseSideEffects != null) && (tracer != null))
tracer.TraceElseSymbols(rule.Name, rsi.elseSideEffects);
}
return rsi;
}
private static ICollection<string> GetActionSideEffects(RuleChainingBehavior behavior, IList<RuleAction> actions, RuleValidation validation)
{
// Man, I wish there were a Set<T> class...
Dictionary<string, object> symbols = new Dictionary<string, object>();
foreach (RuleAction action in actions)
{
if ((behavior == RuleChainingBehavior.Full) ||
((behavior == RuleChainingBehavior.UpdateOnly) && (action is RuleUpdateAction)))
{
ICollection<string> sideEffects = action.GetSideEffects(validation);
if (sideEffects != null)
{
foreach (string symbol in sideEffects)
symbols[symbol] = null;
}
}
}
return symbols.Keys;
}
#endregion
#region Condition Executors
internal static bool EvaluateBool(CodeExpression expression, RuleExecution context)
{
object result = RuleExpressionWalker.Evaluate(context, expression).Value;
if (result is bool)
return (bool)result;
Type expectedType = context.Validation.ExpressionInfo(expression).ExpressionType;
if (expectedType == null)
{
// oops ... not a boolean, so error
InvalidOperationException exception = new InvalidOperationException(Messages.ConditionMustBeBoolean);
exception.Data[RuleUserDataKeys.ErrorObject] = expression;
throw exception;
}
return (bool)AdjustType(expectedType, result, typeof(bool));
}
internal static object AdjustType(Type operandType, object operandValue, Type toType)
{
// if no conversion required, we are done
if (operandType == toType)
return operandValue;
object converted;
if (AdjustValueStandard(operandType, operandValue, toType, out converted))
return converted;
// not a standard conversion, see if it's an implicit user defined conversions
ValidationError error;
MethodInfo conversion = RuleValidation.FindImplicitConversion(operandType, toType, out error);
if (conversion == null)
{
if (error != null)
throw new RuleEvaluationException(error.ErrorText);
throw new RuleEvaluationException(
string.Format(CultureInfo.CurrentCulture,
Messages.CastIncompatibleTypes,
RuleDecompiler.DecompileType(operandType),
RuleDecompiler.DecompileType(toType)));
}
// now we have a method, need to do the conversion S -> Sx -> Tx -> T
Type sx = conversion.GetParameters()[0].ParameterType;
Type tx = conversion.ReturnType;
object intermediateResult1;
if (AdjustValueStandard(operandType, operandValue, sx, out intermediateResult1))
{
// we are happy with the first conversion, so call the user's static method
object intermediateResult2 = conversion.Invoke(null, new object[] { intermediateResult1 });
object intermediateResult3;
if (AdjustValueStandard(tx, intermediateResult2, toType, out intermediateResult3))
return intermediateResult3;
}
throw new RuleEvaluationException(
string.Format(CultureInfo.CurrentCulture,
Messages.CastIncompatibleTypes,
RuleDecompiler.DecompileType(operandType),
RuleDecompiler.DecompileType(toType)));
}
internal static object AdjustTypeWithCast(Type operandType, object operandValue, Type toType)
{
// if no conversion required, we are done
if (operandType == toType)
return operandValue;
object converted;
if (AdjustValueStandard(operandType, operandValue, toType, out converted))
return converted;
// handle enumerations (done above?)
// now it's time for implicit and explicit user defined conversions
ValidationError error;
MethodInfo conversion = RuleValidation.FindExplicitConversion(operandType, toType, out error);
if (conversion == null)
{
if (error != null)
throw new RuleEvaluationException(error.ErrorText);
throw new RuleEvaluationException(
string.Format(CultureInfo.CurrentCulture,
Messages.CastIncompatibleTypes,
RuleDecompiler.DecompileType(operandType),
RuleDecompiler.DecompileType(toType)));
}
// now we have a method, need to do the conversion S -> Sx -> Tx -> T
Type sx = conversion.GetParameters()[0].ParameterType;
Type tx = conversion.ReturnType;
object intermediateResult1;
if (AdjustValueStandard(operandType, operandValue, sx, out intermediateResult1))
{
// we are happy with the first conversion, so call the user's static method
object intermediateResult2 = conversion.Invoke(null, new object[] { intermediateResult1 });
object intermediateResult3;
if (AdjustValueStandard(tx, intermediateResult2, toType, out intermediateResult3))
return intermediateResult3;
}
throw new RuleEvaluationException(
string.Format(CultureInfo.CurrentCulture,
Messages.CastIncompatibleTypes,
RuleDecompiler.DecompileType(operandType),
RuleDecompiler.DecompileType(toType)));
}
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static bool AdjustValueStandard(Type operandType, object operandValue, Type toType, out object converted)
{
// assume it's the same for now
converted = operandValue;
// check for null
if (operandValue == null)
{
// are we converting to a value type?
if (toType.IsValueType)
{
// is the conversion to nullable?
if (!ConditionHelper.IsNullableValueType(toType))
{
// value type and null, so no conversion possible
string message = string.Format(CultureInfo.CurrentCulture, Messages.CannotCastNullToValueType, RuleDecompiler.DecompileType(toType));
throw new InvalidCastException(message);
}
// here we have a Nullable<T>
// however, we may need to call the implicit conversion operator if the types are not compatible
converted = Activator.CreateInstance(toType);
ValidationError error;
return RuleValidation.StandardImplicitConversion(operandType, toType, null, out error);
}
// not a value type, so null is valid
return true;
}
// check simple cases
Type currentType = operandValue.GetType();
if (currentType == toType)
return true;
// now the fun begins
// this should handle most class conversions
if (toType.IsAssignableFrom(currentType))
return true;
// handle the numerics (both implicit and explicit), along with nullable
// note that if the value was null, it's already handled, so value cannot be nullable
if ((currentType.IsValueType) && (toType.IsValueType))
{
if (currentType.IsEnum)
{
// strip off the enum representation
currentType = Enum.GetUnderlyingType(currentType);
ArithmeticLiteral literal = ArithmeticLiteral.MakeLiteral(currentType, operandValue);
operandValue = literal.Value;
}
bool resultNullable = ConditionHelper.IsNullableValueType(toType);
Type resultType = (resultNullable) ? Nullable.GetUnderlyingType(toType) : toType;
if (resultType.IsEnum)
{
// Enum.ToObject may throw if currentType is not type SByte,
// Int16, Int32, Int64, Byte, UInt16, UInt32, or UInt64.
// So we adjust currentValue to the underlying type (which may throw if out of range)
Type underlyingType = Enum.GetUnderlyingType(resultType);
object adjusted;
if (AdjustValueStandard(currentType, operandValue, underlyingType, out adjusted))
{
converted = Enum.ToObject(resultType, adjusted);
if (resultNullable)
converted = Activator.CreateInstance(toType, converted);
return true;
}
}
else if ((resultType.IsPrimitive) || (resultType == typeof(decimal)))
{
// resultType must be a primitive to continue (not a struct)
// (enums and generics handled above)
if (currentType == typeof(char))
{
char c = (char)operandValue;
if (resultType == typeof(float))
{
converted = (float)c;
}
else if (resultType == typeof(double))
{
converted = (double)c;
}
else if (resultType == typeof(decimal))
{
converted = (decimal)c;
}
else
{
converted = ((IConvertible)c).ToType(resultType, CultureInfo.CurrentCulture);
}
if (resultNullable)
converted = Activator.CreateInstance(toType, converted);
return true;
}
else if (currentType == typeof(float))
{
float f = (float)operandValue;
if (resultType == typeof(char))
{
converted = (char)f;
}
else
{
converted = ((IConvertible)f).ToType(resultType, CultureInfo.CurrentCulture);
}
if (resultNullable)
converted = Activator.CreateInstance(toType, converted);
return true;
}
else if (currentType == typeof(double))
{
double d = (double)operandValue;
if (resultType == typeof(char))
{
converted = (char)d;
}
else
{
converted = ((IConvertible)d).ToType(resultType, CultureInfo.CurrentCulture);
}
if (resultNullable)
converted = Activator.CreateInstance(toType, converted);
return true;
}
else if (currentType == typeof(decimal))
{
decimal d = (decimal)operandValue;
if (resultType == typeof(char))
{
converted = (char)d;
}
else
{
converted = ((IConvertible)d).ToType(resultType, CultureInfo.CurrentCulture);
}
if (resultNullable)
converted = Activator.CreateInstance(toType, converted);
return true;
}
else
{
IConvertible convert = operandValue as IConvertible;
if (convert != null)
{
try
{
converted = convert.ToType(resultType, CultureInfo.CurrentCulture);
if (resultNullable)
converted = Activator.CreateInstance(toType, converted);
return true;
}
catch (InvalidCastException)
{
// not IConvertable, so can't do it
return false;
}
}
}
}
}
// no luck with standard conversions, so no conversion done
return false;
}
#endregion
}
}
| |
using System;
using static OneOf.Functions;
namespace OneOf
{
public class OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> : IOneOf
{
readonly T0 _value0;
readonly T1 _value1;
readonly T2 _value2;
readonly T3 _value3;
readonly T4 _value4;
readonly T5 _value5;
readonly T6 _value6;
readonly T7 _value7;
readonly T8 _value8;
readonly T9 _value9;
readonly T10 _value10;
readonly T11 _value11;
readonly T12 _value12;
readonly T13 _value13;
readonly T14 _value14;
readonly T15 _value15;
readonly T16 _value16;
readonly int _index;
protected OneOfBase(OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> input)
{
_index = input.Index;
switch (_index)
{
case 0: _value0 = input.AsT0; break;
case 1: _value1 = input.AsT1; break;
case 2: _value2 = input.AsT2; break;
case 3: _value3 = input.AsT3; break;
case 4: _value4 = input.AsT4; break;
case 5: _value5 = input.AsT5; break;
case 6: _value6 = input.AsT6; break;
case 7: _value7 = input.AsT7; break;
case 8: _value8 = input.AsT8; break;
case 9: _value9 = input.AsT9; break;
case 10: _value10 = input.AsT10; break;
case 11: _value11 = input.AsT11; break;
case 12: _value12 = input.AsT12; break;
case 13: _value13 = input.AsT13; break;
case 14: _value14 = input.AsT14; break;
case 15: _value15 = input.AsT15; break;
case 16: _value16 = input.AsT16; break;
default: throw new InvalidOperationException();
}
}
public object Value =>
_index switch
{
0 => _value0,
1 => _value1,
2 => _value2,
3 => _value3,
4 => _value4,
5 => _value5,
6 => _value6,
7 => _value7,
8 => _value8,
9 => _value9,
10 => _value10,
11 => _value11,
12 => _value12,
13 => _value13,
14 => _value14,
15 => _value15,
16 => _value16,
_ => throw new InvalidOperationException()
};
public int Index => _index;
public bool IsT0 => _index == 0;
public bool IsT1 => _index == 1;
public bool IsT2 => _index == 2;
public bool IsT3 => _index == 3;
public bool IsT4 => _index == 4;
public bool IsT5 => _index == 5;
public bool IsT6 => _index == 6;
public bool IsT7 => _index == 7;
public bool IsT8 => _index == 8;
public bool IsT9 => _index == 9;
public bool IsT10 => _index == 10;
public bool IsT11 => _index == 11;
public bool IsT12 => _index == 12;
public bool IsT13 => _index == 13;
public bool IsT14 => _index == 14;
public bool IsT15 => _index == 15;
public bool IsT16 => _index == 16;
public T0 AsT0 =>
_index == 0 ?
_value0 :
throw new InvalidOperationException($"Cannot return as T0 as result is T{_index}");
public T1 AsT1 =>
_index == 1 ?
_value1 :
throw new InvalidOperationException($"Cannot return as T1 as result is T{_index}");
public T2 AsT2 =>
_index == 2 ?
_value2 :
throw new InvalidOperationException($"Cannot return as T2 as result is T{_index}");
public T3 AsT3 =>
_index == 3 ?
_value3 :
throw new InvalidOperationException($"Cannot return as T3 as result is T{_index}");
public T4 AsT4 =>
_index == 4 ?
_value4 :
throw new InvalidOperationException($"Cannot return as T4 as result is T{_index}");
public T5 AsT5 =>
_index == 5 ?
_value5 :
throw new InvalidOperationException($"Cannot return as T5 as result is T{_index}");
public T6 AsT6 =>
_index == 6 ?
_value6 :
throw new InvalidOperationException($"Cannot return as T6 as result is T{_index}");
public T7 AsT7 =>
_index == 7 ?
_value7 :
throw new InvalidOperationException($"Cannot return as T7 as result is T{_index}");
public T8 AsT8 =>
_index == 8 ?
_value8 :
throw new InvalidOperationException($"Cannot return as T8 as result is T{_index}");
public T9 AsT9 =>
_index == 9 ?
_value9 :
throw new InvalidOperationException($"Cannot return as T9 as result is T{_index}");
public T10 AsT10 =>
_index == 10 ?
_value10 :
throw new InvalidOperationException($"Cannot return as T10 as result is T{_index}");
public T11 AsT11 =>
_index == 11 ?
_value11 :
throw new InvalidOperationException($"Cannot return as T11 as result is T{_index}");
public T12 AsT12 =>
_index == 12 ?
_value12 :
throw new InvalidOperationException($"Cannot return as T12 as result is T{_index}");
public T13 AsT13 =>
_index == 13 ?
_value13 :
throw new InvalidOperationException($"Cannot return as T13 as result is T{_index}");
public T14 AsT14 =>
_index == 14 ?
_value14 :
throw new InvalidOperationException($"Cannot return as T14 as result is T{_index}");
public T15 AsT15 =>
_index == 15 ?
_value15 :
throw new InvalidOperationException($"Cannot return as T15 as result is T{_index}");
public T16 AsT16 =>
_index == 16 ?
_value16 :
throw new InvalidOperationException($"Cannot return as T16 as result is T{_index}");
public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2, Action<T3> f3, Action<T4> f4, Action<T5> f5, Action<T6> f6, Action<T7> f7, Action<T8> f8, Action<T9> f9, Action<T10> f10, Action<T11> f11, Action<T12> f12, Action<T13> f13, Action<T14> f14, Action<T15> f15, Action<T16> f16)
{
if (_index == 0 && f0 != null)
{
f0(_value0);
return;
}
if (_index == 1 && f1 != null)
{
f1(_value1);
return;
}
if (_index == 2 && f2 != null)
{
f2(_value2);
return;
}
if (_index == 3 && f3 != null)
{
f3(_value3);
return;
}
if (_index == 4 && f4 != null)
{
f4(_value4);
return;
}
if (_index == 5 && f5 != null)
{
f5(_value5);
return;
}
if (_index == 6 && f6 != null)
{
f6(_value6);
return;
}
if (_index == 7 && f7 != null)
{
f7(_value7);
return;
}
if (_index == 8 && f8 != null)
{
f8(_value8);
return;
}
if (_index == 9 && f9 != null)
{
f9(_value9);
return;
}
if (_index == 10 && f10 != null)
{
f10(_value10);
return;
}
if (_index == 11 && f11 != null)
{
f11(_value11);
return;
}
if (_index == 12 && f12 != null)
{
f12(_value12);
return;
}
if (_index == 13 && f13 != null)
{
f13(_value13);
return;
}
if (_index == 14 && f14 != null)
{
f14(_value14);
return;
}
if (_index == 15 && f15 != null)
{
f15(_value15);
return;
}
if (_index == 16 && f16 != null)
{
f16(_value16);
return;
}
throw new InvalidOperationException();
}
public TResult Match<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2, Func<T3, TResult> f3, Func<T4, TResult> f4, Func<T5, TResult> f5, Func<T6, TResult> f6, Func<T7, TResult> f7, Func<T8, TResult> f8, Func<T9, TResult> f9, Func<T10, TResult> f10, Func<T11, TResult> f11, Func<T12, TResult> f12, Func<T13, TResult> f13, Func<T14, TResult> f14, Func<T15, TResult> f15, Func<T16, TResult> f16)
{
if (_index == 0 && f0 != null)
{
return f0(_value0);
}
if (_index == 1 && f1 != null)
{
return f1(_value1);
}
if (_index == 2 && f2 != null)
{
return f2(_value2);
}
if (_index == 3 && f3 != null)
{
return f3(_value3);
}
if (_index == 4 && f4 != null)
{
return f4(_value4);
}
if (_index == 5 && f5 != null)
{
return f5(_value5);
}
if (_index == 6 && f6 != null)
{
return f6(_value6);
}
if (_index == 7 && f7 != null)
{
return f7(_value7);
}
if (_index == 8 && f8 != null)
{
return f8(_value8);
}
if (_index == 9 && f9 != null)
{
return f9(_value9);
}
if (_index == 10 && f10 != null)
{
return f10(_value10);
}
if (_index == 11 && f11 != null)
{
return f11(_value11);
}
if (_index == 12 && f12 != null)
{
return f12(_value12);
}
if (_index == 13 && f13 != null)
{
return f13(_value13);
}
if (_index == 14 && f14 != null)
{
return f14(_value14);
}
if (_index == 15 && f15 != null)
{
return f15(_value15);
}
if (_index == 16 && f16 != null)
{
return f16(_value16);
}
throw new InvalidOperationException();
}
public bool TryPickT0(out T0 value, out OneOf<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> remainder)
{
value = IsT0 ? AsT0 : default;
remainder = _index switch
{
0 => default,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT0;
}
public bool TryPickT1(out T1 value, out OneOf<T0, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> remainder)
{
value = IsT1 ? AsT1 : default;
remainder = _index switch
{
0 => AsT0,
1 => default,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT1;
}
public bool TryPickT2(out T2 value, out OneOf<T0, T1, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> remainder)
{
value = IsT2 ? AsT2 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => default,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT2;
}
public bool TryPickT3(out T3 value, out OneOf<T0, T1, T2, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> remainder)
{
value = IsT3 ? AsT3 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => default,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT3;
}
public bool TryPickT4(out T4 value, out OneOf<T0, T1, T2, T3, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> remainder)
{
value = IsT4 ? AsT4 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => default,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT4;
}
public bool TryPickT5(out T5 value, out OneOf<T0, T1, T2, T3, T4, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> remainder)
{
value = IsT5 ? AsT5 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => default,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT5;
}
public bool TryPickT6(out T6 value, out OneOf<T0, T1, T2, T3, T4, T5, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> remainder)
{
value = IsT6 ? AsT6 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => default,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT6;
}
public bool TryPickT7(out T7 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T8, T9, T10, T11, T12, T13, T14, T15, T16> remainder)
{
value = IsT7 ? AsT7 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => default,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT7;
}
public bool TryPickT8(out T8 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T9, T10, T11, T12, T13, T14, T15, T16> remainder)
{
value = IsT8 ? AsT8 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => default,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT8;
}
public bool TryPickT9(out T9 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T10, T11, T12, T13, T14, T15, T16> remainder)
{
value = IsT9 ? AsT9 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => default,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT9;
}
public bool TryPickT10(out T10 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T11, T12, T13, T14, T15, T16> remainder)
{
value = IsT10 ? AsT10 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => default,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT10;
}
public bool TryPickT11(out T11 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T12, T13, T14, T15, T16> remainder)
{
value = IsT11 ? AsT11 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => default,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT11;
}
public bool TryPickT12(out T12 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T13, T14, T15, T16> remainder)
{
value = IsT12 ? AsT12 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => default,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT12;
}
public bool TryPickT13(out T13 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T14, T15, T16> remainder)
{
value = IsT13 ? AsT13 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => default,
14 => AsT14,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT13;
}
public bool TryPickT14(out T14 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T15, T16> remainder)
{
value = IsT14 ? AsT14 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => default,
15 => AsT15,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT14;
}
public bool TryPickT15(out T15 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T16> remainder)
{
value = IsT15 ? AsT15 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => default,
16 => AsT16,
_ => throw new InvalidOperationException()
};
return this.IsT15;
}
public bool TryPickT16(out T16 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> remainder)
{
value = IsT16 ? AsT16 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => default,
_ => throw new InvalidOperationException()
};
return this.IsT16;
}
bool Equals(OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> other) =>
_index == other._index &&
_index switch
{
0 => Equals(_value0, other._value0),
1 => Equals(_value1, other._value1),
2 => Equals(_value2, other._value2),
3 => Equals(_value3, other._value3),
4 => Equals(_value4, other._value4),
5 => Equals(_value5, other._value5),
6 => Equals(_value6, other._value6),
7 => Equals(_value7, other._value7),
8 => Equals(_value8, other._value8),
9 => Equals(_value9, other._value9),
10 => Equals(_value10, other._value10),
11 => Equals(_value11, other._value11),
12 => Equals(_value12, other._value12),
13 => Equals(_value13, other._value13),
14 => Equals(_value14, other._value14),
15 => Equals(_value15, other._value15),
16 => Equals(_value16, other._value16),
_ => false
};
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj)) {
return true;
}
return obj is OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> o && Equals(o);
}
public override string ToString() =>
_index switch {
0 => FormatValue(_value0),
1 => FormatValue(_value1),
2 => FormatValue(_value2),
3 => FormatValue(_value3),
4 => FormatValue(_value4),
5 => FormatValue(_value5),
6 => FormatValue(_value6),
7 => FormatValue(_value7),
8 => FormatValue(_value8),
9 => FormatValue(_value9),
10 => FormatValue(_value10),
11 => FormatValue(_value11),
12 => FormatValue(_value12),
13 => FormatValue(_value13),
14 => FormatValue(_value14),
15 => FormatValue(_value15),
16 => FormatValue(_value16),
_ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the OneOf codegen.")
};
public override int GetHashCode()
{
unchecked
{
int hashCode = _index switch
{
0 => _value0?.GetHashCode(),
1 => _value1?.GetHashCode(),
2 => _value2?.GetHashCode(),
3 => _value3?.GetHashCode(),
4 => _value4?.GetHashCode(),
5 => _value5?.GetHashCode(),
6 => _value6?.GetHashCode(),
7 => _value7?.GetHashCode(),
8 => _value8?.GetHashCode(),
9 => _value9?.GetHashCode(),
10 => _value10?.GetHashCode(),
11 => _value11?.GetHashCode(),
12 => _value12?.GetHashCode(),
13 => _value13?.GetHashCode(),
14 => _value14?.GetHashCode(),
15 => _value15?.GetHashCode(),
16 => _value16?.GetHashCode(),
_ => 0
} ?? 0;
return (hashCode*397) ^ _index;
}
}
}
}
| |
using System;
using Moq;
using Stratis.Bitcoin.Features.SmartContracts.Networks;
using Stratis.SmartContracts.Core;
using Stratis.SmartContracts.CLR;
using Xunit;
namespace Stratis.SmartContracts.Token.Tests
{
public class StandardTokenTests
{
private readonly Mock<ISmartContractState> mockContractState;
private readonly Mock<IPersistentState> mockPersistentState;
private readonly Mock<IContractLogger> mockContractLogger;
private Address owner;
private Address sender;
private Address contract;
private Address spender;
private Address destination;
public StandardTokenTests()
{
var network = new SmartContractPosTest();
this.mockContractLogger = new Mock<IContractLogger>();
this.mockPersistentState = new Mock<IPersistentState>();
this.mockContractState = new Mock<ISmartContractState>();
this.mockContractState.Setup(s => s.PersistentState).Returns(this.mockPersistentState.Object);
this.mockContractState.Setup(s => s.ContractLogger).Returns(this.mockContractLogger.Object);
this.owner = "0x0000000000000000000000000000000000000001".HexToAddress();
this.sender = "0x0000000000000000000000000000000000000002".HexToAddress();
this.contract = "0x0000000000000000000000000000000000000003".HexToAddress();
this.spender = "0x0000000000000000000000000000000000000004".HexToAddress();
this.destination = "0x0000000000000000000000000000000000000005".HexToAddress();
}
[Fact]
public void Constructor_Sets_TotalSupply()
{
this.mockContractState.Setup(m => m.Message).Returns(new Message(this.contract, this.owner, 0));
ulong totalSupply = 100_000;
var standardToken = new StandardToken(this.mockContractState.Object, totalSupply);
// Verify that PersistentState was called with the total supply
this.mockPersistentState.Verify(s => s.SetUInt64(nameof(StandardToken.TotalSupply), totalSupply));
}
[Fact]
public void Constructor_Assigns_TotalSupply_To_Owner()
{
ulong totalSupply = 100_000;
this.mockContractState.Setup(m => m.Message).Returns(new Message(this.contract, this.owner, 0));
var standardToken = new StandardToken(this.mockContractState.Object, totalSupply);
// Verify that PersistentState was called with the total supply
this.mockPersistentState.Verify(s => s.SetUInt64($"Balance:{this.owner}", totalSupply));
}
[Fact]
public void GetBalance_Returns_Correct_Balance()
{
ulong balance = 100;
this.mockContractState.Setup(m => m.Message).Returns(new Message(this.contract, this.owner, 0));
var standardToken = new StandardToken(this.mockContractState.Object, 100_000);
// Setup the balance of the address in persistent state
this.mockPersistentState.Setup(s => s.GetUInt64($"Balance:{this.spender}")).Returns(balance);
Assert.Equal(balance, standardToken.GetBalance(this.spender));
}
[Fact]
public void Approve_Sets_Approval_Correctly()
{
ulong balance = 100_000;
ulong approval = 1000;
// Setup the Message.Sender address
this.mockContractState.Setup(m => m.Message).Returns(new Message(this.contract, this.owner, 0));
var standardToken = new StandardToken(this.mockContractState.Object, 100_000);
standardToken.Approve(this.spender, 0, approval);
this.mockPersistentState.Verify(s => s.SetUInt64($"Allowance:{this.owner}:{this.spender}", approval));
this.mockContractLogger.Verify(l => l.Log(It.IsAny<ISmartContractState>(), new StandardToken.ApprovalLog { Owner = this.owner, Spender = this.spender, Amount = approval, OldAmount = 0 }));
}
[Fact]
public void Approve_Sets_Approval_Correctly_When_NonZero()
{
ulong balance = 100_000;
ulong approval = 1000;
ulong newApproval = 2000;
// Setup the Message.Sender address
this.mockContractState.Setup(m => m.Message).Returns(new Message(this.contract, this.owner, 0));
var standardToken = new StandardToken(this.mockContractState.Object, 100_000);
// Set up an existing allowance
this.mockPersistentState.Setup(s => s.GetUInt64($"Allowance:{this.owner}:{this.spender}")).Returns(approval);
standardToken.Approve(this.spender, approval, newApproval);
this.mockPersistentState.Verify(s => s.SetUInt64($"Allowance:{this.owner}:{this.spender}", newApproval));
this.mockContractLogger.Verify(l => l.Log(It.IsAny<ISmartContractState>(), new StandardToken.ApprovalLog { Owner = this.owner, Spender = this.spender, Amount = newApproval, OldAmount = approval }));
}
[Fact]
public void Approve_Does_Not_Set_Approval_If_Different()
{
ulong balance = 100_000;
ulong approval = 1000;
ulong newApproval = 2000;
// Setup the Message.Sender address
this.mockContractState.Setup(m => m.Message).Returns(new Message(this.contract, this.owner, 0));
var standardToken = new StandardToken(this.mockContractState.Object, 100_000);
// Set up an existing allowance
this.mockPersistentState.Setup(s => s.GetUInt64($"Allowance:{this.owner}:{this.spender}")).Returns(approval);
// Attempt to set the new approval for a different earlier approval
var differentApproval = approval + 1;
Assert.False(standardToken.Approve(this.spender, differentApproval, newApproval));
this.mockPersistentState.Verify(s => s.SetUInt64($"Allowance:{this.owner}:{this.spender}", It.IsAny<ulong>()), Times.Never);
}
[Fact]
public void Allowance_Gets_Correctly()
{
ulong balance = 100_000;
ulong approval = 1000;
this.mockContractState.Setup(m => m.Message).Returns(new Message(this.contract, this.sender, 0));
var standardToken = new StandardToken(this.mockContractState.Object, 100_000);
standardToken.Allowance(this.owner, this.spender);
this.mockPersistentState.Verify(s => s.GetUInt64($"Allowance:{this.owner}:{this.spender}"));
}
[Fact]
public void Transfer_0_Returns_True()
{
ulong amount = 0;
// Setup the Message.Sender address
this.mockContractState.Setup(m => m.Message)
.Returns(new Message(this.contract, this.sender, 0));
var standardToken = new StandardToken(this.mockContractState.Object, 100_000);
Assert.True(standardToken.TransferTo(this.destination, amount));
this.mockContractLogger.Verify(l => l.Log(It.IsAny<ISmartContractState>(), new StandardToken.TransferLog { From = this.sender, To = this.destination, Amount = amount }));
}
[Fact]
public void Transfer_Greater_Than_Balance_Returns_False()
{
ulong balance = 0;
ulong amount = balance + 1;
// Setup the Message.Sender address
this.mockContractState.Setup(m => m.Message)
.Returns(new Message(this.contract, this.sender, 0));
var standardToken = new StandardToken(this.mockContractState.Object, 100_000);
// Setup the balance of the address in persistent state
this.mockPersistentState.Setup(s => s.GetUInt64($"Balance:{this.sender}")).Returns(balance);
Assert.False(standardToken.TransferTo(this.destination, amount));
// Verify we queried the balance
this.mockPersistentState.Verify(s => s.GetUInt64($"Balance:{this.sender}"));
}
[Fact]
public void Transfer_To_Destination_With_Balance_Greater_Than_uint_MaxValue_Returns_False()
{
ulong destinationBalance = ulong.MaxValue;
ulong senderBalance = 100;
ulong amount = senderBalance - 1; // Transfer less than the balance
// Setup the Message.Sender address
this.mockContractState.Setup(m => m.Message)
.Returns(new Message(this.contract, this.sender, 0));
var standardToken = new StandardToken(this.mockContractState.Object, 100_000);
// Setup the balance of the address in persistent state
this.mockPersistentState.Setup(s => s.GetUInt64($"Balance:{this.sender}")).Returns(senderBalance);
// Setup the destination's balance to be ulong.MaxValue
this.mockPersistentState.Setup(s => s.GetUInt64($"Balance:{this.destination}")).Returns(destinationBalance);
Assert.ThrowsAny<OverflowException>(() => standardToken.TransferTo(this.destination, amount));
// Verify we queried the sender's balance
this.mockPersistentState.Verify(s => s.GetUInt64($"Balance:{this.sender}"));
// Verify we queried the destination's balance
this.mockPersistentState.Verify(s => s.GetUInt64($"Balance:{this.destination}"));
}
[Fact]
public void Transfer_To_Destination_Success_Returns_True()
{
ulong destinationBalance = 400_000;
ulong senderBalance = 100;
ulong amount = senderBalance - 1; // Transfer less than the balance
// Setup the Message.Sender address
this.mockContractState.Setup(m => m.Message)
.Returns(new Message(this.contract, this.sender, 0));
var standardToken = new StandardToken(this.mockContractState.Object, 100_000);
int callOrder = 1;
// Setup the balance of the address in persistent state
this.mockPersistentState.Setup(s => s.GetUInt64($"Balance:{this.sender}")).Returns(senderBalance)
.Callback(() => Assert.Equal(1, callOrder++));
// Setup the destination's balance
this.mockPersistentState.Setup(s => s.GetUInt64($"Balance:{this.destination}")).Returns(destinationBalance)
.Callback(() => Assert.Equal(2, callOrder++));
// Setup the sender's balance
this.mockPersistentState.Setup(s => s.SetUInt64($"Balance:{this.sender}", It.IsAny<uint>()))
.Callback(() => Assert.Equal(3, callOrder++));
// Setup the destination's balance. Important that this happens AFTER setting the sender's balance
this.mockPersistentState.Setup(s => s.SetUInt64($"Balance:{this.destination}", It.IsAny<uint>()))
.Callback(() => Assert.Equal(4, callOrder++));
Assert.True(standardToken.TransferTo(this.destination, amount));
// Verify we queried the sender's balance
this.mockPersistentState.Verify(s => s.GetUInt64($"Balance:{this.sender}"));
// Verify we queried the destination's balance
this.mockPersistentState.Verify(s => s.GetUInt64($"Balance:{this.destination}"));
// Verify we set the sender's balance
this.mockPersistentState.Verify(s => s.SetUInt64($"Balance:{this.sender}", senderBalance - amount));
// Verify we set the receiver's balance
this.mockPersistentState.Verify(s => s.SetUInt64($"Balance:{this.destination}", destinationBalance + amount));
this.mockContractLogger.Verify(l => l.Log(It.IsAny<ISmartContractState>(), new StandardToken.TransferLog { From = this.sender, To = this.destination, Amount = amount }));
}
[Fact]
public void TransferFrom_0_Returns_True()
{
ulong amount = 0;
// Setup the Message.Sender address
this.mockContractState.Setup(m => m.Message)
.Returns(new Message(this.contract, this.sender, 0));
var standardToken = new StandardToken(this.mockContractState.Object, 100_000);
Assert.True(standardToken.TransferFrom(this.owner, this.destination, amount));
this.mockContractLogger.Verify(l => l.Log(It.IsAny<ISmartContractState>(), new StandardToken.TransferLog { From = this.owner, To = this.destination, Amount = amount }));
}
[Fact]
public void TransferFrom_Greater_Than_Senders_Allowance_Returns_False()
{
ulong allowance = 0;
ulong amount = allowance + 1;
ulong balance = amount + 1; // Balance should be more than amount we are trying to send
// Setup the Message.Sender address
this.mockContractState.Setup(m => m.Message)
.Returns(new Message(this.contract, this.sender, 0));
var standardToken = new StandardToken(this.mockContractState.Object, 100_000);
// Setup the balance of the owner in persistent state
this.mockPersistentState.Setup(s => s.GetUInt64($"Balance:{this.owner}")).Returns(balance);
// Setup the balance of the address in persistent state
this.mockPersistentState.Setup(s => s.GetUInt64($"Allowance:{this.owner}:{this.sender}")).Returns(allowance);
Assert.False(standardToken.TransferFrom(this.owner, this.destination, amount));
// Verify we queried the sender's allowance
this.mockPersistentState.Verify(s => s.GetUInt64($"Allowance:{this.owner}:{this.sender}"));
// Verify we queried the owner's balance
this.mockPersistentState.Verify(s => s.GetUInt64($"Balance:{this.owner}"));
}
[Fact]
public void TransferFrom_Greater_Than_Owners_Balance_Returns_False()
{
ulong balance = 0; // Balance should be less than amount we are trying to send
ulong amount = balance + 1;
ulong allowance = amount + 1; // Allowance should be more than amount we are trying to send
// Setup the Message.Sender address
this.mockContractState.Setup(m => m.Message)
.Returns(new Message(this.contract, this.sender, 0));
var standardToken = new StandardToken(this.mockContractState.Object, 100_000);
// Setup the balance of the owner in persistent state
this.mockPersistentState.Setup(s => s.GetUInt64($"Balance:{this.owner}")).Returns(balance);
// Setup the allowance of the sender in persistent state
this.mockPersistentState.Setup(s => s.GetUInt64($"Allowance:{this.owner}:{this.sender}")).Returns(allowance);
Assert.False(standardToken.TransferFrom(this.owner, this.destination, amount));
// Verify we queried the sender's allowance
this.mockPersistentState.Verify(s => s.GetUInt64($"Allowance:{this.owner}:{this.sender}"));
// Verify we queried the owner's balance
this.mockPersistentState.Verify(s => s.GetUInt64($"Balance:{this.owner}"));
}
[Fact]
public void TransferFrom_To_Destination_With_Balance_Greater_Than_uint_MaxValue_Returns_False()
{
ulong destinationBalance = ulong.MaxValue; // Destination balance should be ulong.MaxValue
ulong amount = 1;
ulong allowance = amount + 1; // Allowance should be more than amount we are trying to send
ulong ownerBalance = allowance + 1; // Owner balance should be more than allowance
// Setup the Message.Sender address
this.mockContractState.Setup(m => m.Message)
.Returns(new Message(this.contract, this.sender, 0));
var standardToken = new StandardToken(this.mockContractState.Object, 100_000);
// Setup the balance of the owner in persistent state
this.mockPersistentState.Setup(s => s.GetUInt64($"Balance:{this.owner}")).Returns(ownerBalance);
// Setup the balance of the destination in persistent state
this.mockPersistentState.Setup(s => s.GetUInt64($"Balance:{this.destination}")).Returns(destinationBalance);
// Setup the allowance of the sender in persistent state
this.mockPersistentState.Setup(s => s.GetUInt64($"Allowance:{this.owner}:{this.sender}")).Returns(allowance);
Assert.ThrowsAny<OverflowException>(() => standardToken.TransferFrom(this.owner, this.destination, amount));
// Verify we queried the sender's allowance
this.mockPersistentState.Verify(s => s.GetUInt64($"Allowance:{this.owner}:{this.sender}"));
// Verify we queried the owner's balance
this.mockPersistentState.Verify(s => s.GetUInt64($"Balance:{this.owner}"));
}
[Fact]
public void TransferFrom_To_Destination_Success_Returns_True()
{
ulong destinationBalance = 100;
ulong amount = 1;
ulong allowance = amount + 1; // Allowance should be more than amount we are trying to send
ulong ownerBalance = allowance + 1; // Owner balance should be more than allowance
// Setup the Message.Sender address
this.mockContractState.Setup(m => m.Message)
.Returns(new Message(this.contract, this.sender, 0));
var standardToken = new StandardToken(this.mockContractState.Object, 100_000);
int callOrder = 1;
// Setup the allowance of the sender in persistent state
this.mockPersistentState.Setup(s => s.GetUInt64($"Allowance:{this.owner}:{this.sender}")).Returns(allowance)
.Callback(() => Assert.Equal(1, callOrder++));
// Setup the balance of the owner in persistent state
this.mockPersistentState.Setup(s => s.GetUInt64($"Balance:{this.owner}")).Returns(ownerBalance)
.Callback(() => Assert.Equal(2, callOrder++));
// Setup the balance of the destination in persistent state
this.mockPersistentState.Setup(s => s.GetUInt64($"Balance:{this.destination}")).Returns(destinationBalance)
.Callback(() => Assert.Equal(3, callOrder++));
// Set the sender's new allowance
this.mockPersistentState.Setup(s => s.SetUInt64($"Allowance:{this.owner}:{this.sender}", It.IsAny<uint>()))
.Callback(() => Assert.Equal(4, callOrder++));
// Set the owner's new balance
this.mockPersistentState.Setup(s => s.SetUInt64($"Balance:{this.owner}", It.IsAny<uint>()))
.Callback(() => Assert.Equal(5, callOrder++));
// Setup the destination's balance. Important that this happens AFTER setting the owner's balance
this.mockPersistentState.Setup(s => s.SetUInt64($"Balance:{this.destination}", It.IsAny<uint>()))
.Callback(() => Assert.Equal(6, callOrder++));
Assert.True(standardToken.TransferFrom(this.owner, this.destination, amount));
// Verify we queried the sender's allowance
this.mockPersistentState.Verify(s => s.GetUInt64($"Allowance:{this.owner}:{this.sender}"));
// Verify we queried the owner's balance
this.mockPersistentState.Verify(s => s.GetUInt64($"Balance:{this.owner}"));
// Verify we queried the destination's balance
this.mockPersistentState.Verify(s => s.GetUInt64($"Balance:{this.destination}"));
// Verify we set the sender's allowance
this.mockPersistentState.Verify(s => s.SetUInt64($"Allowance:{this.owner}:{this.sender}", allowance - amount));
// Verify we set the owner's balance
this.mockPersistentState.Verify(s => s.SetUInt64($"Balance:{this.owner}", ownerBalance - amount));
// Verify we set the receiver's balance
this.mockPersistentState.Verify(s => s.SetUInt64($"Balance:{this.destination}", destinationBalance + amount));
this.mockContractLogger.Verify(l => l.Log(It.IsAny<ISmartContractState>(), new StandardToken.TransferLog { From = this.owner, To = this.destination, Amount = amount }));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System;
using Microsoft.Build.Construction;
using System.Reflection;
using Xunit;
using Shouldly;
namespace Microsoft.Build.UnitTests.Construction
{
/// <summary>
/// Tests for the ElementLocation class
/// </summary>
public class ElementLocationPublic_Tests
{
/// <summary>
/// Check that we can get the file name off an element and attribute, even if
/// it wouldn't normally have got one because the project wasn't
/// loaded from disk, or has been edited since.
/// This is really a test of our XmlDocumentWithLocation.
/// </summary>
[Fact]
public void ShouldHaveFilePathLocationEvenIfNotLoadedNorSavedYet()
{
ProjectRootElement project = ProjectRootElement.Create();
project.FullPath = "c:\\x";
ProjectTargetElement target = project.CreateTargetElement("t");
target.Outputs = "o";
project.AppendChild(target);
Assert.Equal(project.FullPath, target.Location.File);
Assert.Equal(project.FullPath, target.OutputsLocation.File);
}
/// <summary>
/// Element location should reflect rename.
/// This is really a test of our XmlXXXXWithLocation.
/// </summary>
[Fact]
public void XmlLocationReflectsRename()
{
ProjectRootElement project = ProjectRootElement.Create();
project.FullPath = "c:\\x";
ProjectTargetElement target = project.CreateTargetElement("t");
target.Outputs = "o";
project.AppendChild(target);
Assert.Equal(project.FullPath, target.Location.File);
Assert.Equal(project.FullPath, target.OutputsLocation.File);
project.FullPath = "c:\\y";
Assert.Equal(project.FullPath, target.Location.File);
Assert.Equal(project.FullPath, target.OutputsLocation.File);
}
/// <summary>
/// We should cache ElementLocation objects for perf.
/// </summary>
[Fact]
public void XmlLocationsAreCached()
{
ProjectRootElement project = ProjectRootElement.Create();
project.FullPath = "c:\\x";
ProjectTargetElement target = project.CreateTargetElement("t");
target.Outputs = "o";
project.AppendChild(target);
ElementLocation e1 = target.Location;
ElementLocation e2 = target.OutputsLocation;
Assert.True(Object.ReferenceEquals(e1, target.Location));
Assert.True(Object.ReferenceEquals(e2, target.OutputsLocation));
}
/// <summary>
/// Test many of the getters
/// </summary>
[Fact]
public void LocationStringsMedley()
{
string content = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<UsingTask TaskName='t' AssemblyName='a' Condition='true'/>
<UsingTask TaskName='t' AssemblyFile='a' Condition='true'/>
<ItemDefinitionGroup Condition='true' Label='l'>
<m Condition='true'/>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='i' Condition='true' Exclude='r'>
<m Condition='true'/>
</i>
</ItemGroup>
<PropertyGroup>
<p Condition='true'/>
</PropertyGroup>
<Target Name='Build' Condition='true' Inputs='i' Outputs='o'>
<ItemGroup>
<i Include='i' Condition='true' Exclude='r'>
<m Condition='true'/>
</i>
<i Remove='r'/>
</ItemGroup>
<PropertyGroup>
<p Condition='true'/>
</PropertyGroup>
<Error Text='xyz' ContinueOnError='true' Importance='high'/>
</Target>
<Import Project='p' Condition='false'/>
</Project>
";
var project = ObjectModelHelpers.CreateInMemoryProject(content);
string locations = project.Xml.Location.LocationString + "\r\n";
List<string> attributeLocations = new List<string>(2);
foreach (var element in project.Xml.AllChildren)
{
foreach (var property in element.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (!property.Name.Equals("ImplicitImportLocation") && property.Name.Contains("Location"))
{
if (property.Name == "ParameterLocations")
{
var values = new List<KeyValuePair<string, ElementLocation>>((ICollection<KeyValuePair<string, ElementLocation>>)property.GetValue(element, null));
values.ForEach(value => attributeLocations.Add(value.Key + ":" + value.Value.LocationString));
}
else
{
var value = ((ElementLocation)property.GetValue(element, null));
if (value != null) // null means attribute is not present
{
locations += value.LocationString + "\r\n";
}
}
}
}
}
locations = locations.Replace(project.FullPath, "c:\\foo\\bar.csproj");
string expected = @"c:\foo\bar.csproj (2,13)
c:\foo\bar.csproj (3,32)
c:\foo\bar.csproj (3,45)
c:\foo\bar.csproj (3,62)
c:\foo\bar.csproj (3,21)
c:\foo\bar.csproj (4,32)
c:\foo\bar.csproj (4,45)
c:\foo\bar.csproj (4,62)
c:\foo\bar.csproj (4,21)
c:\foo\bar.csproj (5,42)
c:\foo\bar.csproj (5,59)
c:\foo\bar.csproj (5,21)
c:\foo\bar.csproj (6,28)
c:\foo\bar.csproj (6,25)
c:\foo\bar.csproj (8,21)
c:\foo\bar.csproj (9,28)
c:\foo\bar.csproj (9,57)
c:\foo\bar.csproj (9,40)
c:\foo\bar.csproj (9,25)
c:\foo\bar.csproj (10,32)
c:\foo\bar.csproj (10,29)
c:\foo\bar.csproj (13,21)
c:\foo\bar.csproj (14,28)
c:\foo\bar.csproj (14,25)
c:\foo\bar.csproj (16,29)
c:\foo\bar.csproj (16,59)
c:\foo\bar.csproj (16,70)
c:\foo\bar.csproj (16,29)
c:\foo\bar.csproj (16,42)
c:\foo\bar.csproj (16,21)
c:\foo\bar.csproj (17,25)
c:\foo\bar.csproj (18,32)
c:\foo\bar.csproj (18,61)
c:\foo\bar.csproj (18,44)
c:\foo\bar.csproj (18,29)
c:\foo\bar.csproj (19,36)
c:\foo\bar.csproj (19,33)
c:\foo\bar.csproj (21,32)
c:\foo\bar.csproj (21,29)
c:\foo\bar.csproj (23,25)
c:\foo\bar.csproj (24,32)
c:\foo\bar.csproj (24,29)
c:\foo\bar.csproj (26,43)
c:\foo\bar.csproj (26,25)
c:\foo\bar.csproj (28,29)
c:\foo\bar.csproj (28,41)
c:\foo\bar.csproj (28,21)
";
Helpers.VerifyAssertLineByLine(expected, locations);
// attribute order depends on dictionary internals
attributeLocations.ShouldBe(new[] { "Text: (26,32)", "Importance: (26,66)" }, ignoreOrder: true);
}
}
}
| |
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 BookShop.WebApi.Areas.HelpPage.ModelDescriptions;
using BookShop.WebApi.Areas.HelpPage.Models;
namespace BookShop.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);
}
}
}
}
| |
// 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.Globalization;
using System.Numerics.Hashing;
using System.Runtime.CompilerServices;
using System.Text;
namespace System.Numerics
{
/// <summary>
/// A structure encapsulating four single precision floating point values and provides hardware accelerated methods.
/// </summary>
public partial struct Vector4 : IEquatable<Vector4>, IFormattable
{
#region Public Static Properties
/// <summary>
/// Returns the vector (0,0,0,0).
/// </summary>
public static Vector4 Zero { get { return new Vector4(); } }
/// <summary>
/// Returns the vector (1,1,1,1).
/// </summary>
public static Vector4 One { get { return new Vector4(1.0f, 1.0f, 1.0f, 1.0f); } }
/// <summary>
/// Returns the vector (1,0,0,0).
/// </summary>
public static Vector4 UnitX { get { return new Vector4(1.0f, 0.0f, 0.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,1,0,0).
/// </summary>
public static Vector4 UnitY { get { return new Vector4(0.0f, 1.0f, 0.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,0,1,0).
/// </summary>
public static Vector4 UnitZ { get { return new Vector4(0.0f, 0.0f, 1.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,0,0,1).
/// </summary>
public static Vector4 UnitW { get { return new Vector4(0.0f, 0.0f, 0.0f, 1.0f); } }
#endregion Public Static Properties
#region Public instance methods
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int hash = this.X.GetHashCode();
hash = HashHelpers.Combine(hash, this.Y.GetHashCode());
hash = HashHelpers.Combine(hash, this.Z.GetHashCode());
hash = HashHelpers.Combine(hash, this.W.GetHashCode());
return hash;
}
/// <summary>
/// Returns a boolean indicating whether the given Object is equal to this Vector4 instance.
/// </summary>
/// <param name="obj">The Object to compare against.</param>
/// <returns>True if the Object is equal to this Vector4; False otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool Equals(object obj)
{
if (!(obj is Vector4))
return false;
return Equals((Vector4)obj);
}
/// <summary>
/// Returns a String representing this Vector4 instance.
/// </summary>
/// <returns>The string representation.</returns>
public override string ToString()
{
return ToString("G", CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a String representing this Vector4 instance, using the specified format to format individual elements.
/// </summary>
/// <param name="format">The format of individual elements.</param>
/// <returns>The string representation.</returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a String representing this Vector4 instance, using the specified format to format individual elements
/// and the given IFormatProvider.
/// </summary>
/// <param name="format">The format of individual elements.</param>
/// <param name="formatProvider">The format provider to use when formatting elements.</param>
/// <returns>The string representation.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
StringBuilder sb = new StringBuilder();
string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator;
sb.Append('<');
sb.Append(this.X.ToString(format, formatProvider));
sb.Append(separator);
sb.Append(' ');
sb.Append(this.Y.ToString(format, formatProvider));
sb.Append(separator);
sb.Append(' ');
sb.Append(this.Z.ToString(format, formatProvider));
sb.Append(separator);
sb.Append(' ');
sb.Append(this.W.ToString(format, formatProvider));
sb.Append('>');
return sb.ToString();
}
/// <summary>
/// Returns the length of the vector. This operation is cheaper than Length().
/// </summary>
/// <returns>The vector's length.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float Length()
{
if (Vector.IsHardwareAccelerated)
{
float ls = Vector4.Dot(this, this);
return MathF.Sqrt(ls);
}
else
{
float ls = X * X + Y * Y + Z * Z + W * W;
return MathF.Sqrt(ls);
}
}
/// <summary>
/// Returns the length of the vector squared.
/// </summary>
/// <returns>The vector's length squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float LengthSquared()
{
if (Vector.IsHardwareAccelerated)
{
return Vector4.Dot(this, this);
}
else
{
return X * X + Y * Y + Z * Z + W * W;
}
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the Euclidean distance between the two given points.
/// </summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Distance(Vector4 value1, Vector4 value2)
{
if (Vector.IsHardwareAccelerated)
{
Vector4 difference = value1 - value2;
float ls = Vector4.Dot(difference, difference);
return MathF.Sqrt(ls);
}
else
{
float dx = value1.X - value2.X;
float dy = value1.Y - value2.Y;
float dz = value1.Z - value2.Z;
float dw = value1.W - value2.W;
float ls = dx * dx + dy * dy + dz * dz + dw * dw;
return MathF.Sqrt(ls);
}
}
/// <summary>
/// Returns the Euclidean distance squared between the two given points.
/// </summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float DistanceSquared(Vector4 value1, Vector4 value2)
{
if (Vector.IsHardwareAccelerated)
{
Vector4 difference = value1 - value2;
return Vector4.Dot(difference, difference);
}
else
{
float dx = value1.X - value2.X;
float dy = value1.Y - value2.Y;
float dz = value1.Z - value2.Z;
float dw = value1.W - value2.W;
return dx * dx + dy * dy + dz * dz + dw * dw;
}
}
/// <summary>
/// Returns a vector with the same direction as the given vector, but with a length of 1.
/// </summary>
/// <param name="vector">The vector to normalize.</param>
/// <returns>The normalized vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Normalize(Vector4 vector)
{
if (Vector.IsHardwareAccelerated)
{
float length = vector.Length();
return vector / length;
}
else
{
float ls = vector.X * vector.X + vector.Y * vector.Y + vector.Z * vector.Z + vector.W * vector.W;
float invNorm = 1.0f / MathF.Sqrt(ls);
return new Vector4(
vector.X * invNorm,
vector.Y * invNorm,
vector.Z * invNorm,
vector.W * invNorm);
}
}
/// <summary>
/// Restricts a vector between a min and max value.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>The restricted vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Clamp(Vector4 value1, Vector4 min, Vector4 max)
{
// This compare order is very important!!!
// We must follow HLSL behavior in the case user specified min value is bigger than max value.
float x = value1.X;
x = (x > max.X) ? max.X : x;
x = (x < min.X) ? min.X : x;
float y = value1.Y;
y = (y > max.Y) ? max.Y : y;
y = (y < min.Y) ? min.Y : y;
float z = value1.Z;
z = (z > max.Z) ? max.Z : z;
z = (z < min.Z) ? min.Z : z;
float w = value1.W;
w = (w > max.W) ? max.W : w;
w = (w < min.W) ? min.W : w;
return new Vector4(x, y, z, w);
}
/// <summary>
/// Linearly interpolates between two vectors based on the given weighting.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <param name="amount">Value between 0 and 1 indicating the weight of the second source vector.</param>
/// <returns>The interpolated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Lerp(Vector4 value1, Vector4 value2, float amount)
{
return new Vector4(
value1.X + (value2.X - value1.X) * amount,
value1.Y + (value2.Y - value1.Y) * amount,
value1.Z + (value2.Z - value1.Z) * amount,
value1.W + (value2.W - value1.W) * amount);
}
/// <summary>
/// Transforms a vector by the given matrix.
/// </summary>
/// <param name="position">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector2 position, Matrix4x4 matrix)
{
return new Vector4(
position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41,
position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42,
position.X * matrix.M13 + position.Y * matrix.M23 + matrix.M43,
position.X * matrix.M14 + position.Y * matrix.M24 + matrix.M44);
}
/// <summary>
/// Transforms a vector by the given matrix.
/// </summary>
/// <param name="position">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector3 position, Matrix4x4 matrix)
{
return new Vector4(
position.X * matrix.M11 + position.Y * matrix.M21 + position.Z * matrix.M31 + matrix.M41,
position.X * matrix.M12 + position.Y * matrix.M22 + position.Z * matrix.M32 + matrix.M42,
position.X * matrix.M13 + position.Y * matrix.M23 + position.Z * matrix.M33 + matrix.M43,
position.X * matrix.M14 + position.Y * matrix.M24 + position.Z * matrix.M34 + matrix.M44);
}
/// <summary>
/// Transforms a vector by the given matrix.
/// </summary>
/// <param name="vector">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector4 vector, Matrix4x4 matrix)
{
return new Vector4(
vector.X * matrix.M11 + vector.Y * matrix.M21 + vector.Z * matrix.M31 + vector.W * matrix.M41,
vector.X * matrix.M12 + vector.Y * matrix.M22 + vector.Z * matrix.M32 + vector.W * matrix.M42,
vector.X * matrix.M13 + vector.Y * matrix.M23 + vector.Z * matrix.M33 + vector.W * matrix.M43,
vector.X * matrix.M14 + vector.Y * matrix.M24 + vector.Z * matrix.M34 + vector.W * matrix.M44);
}
/// <summary>
/// Transforms a vector by the given Quaternion rotation value.
/// </summary>
/// <param name="value">The source vector to be rotated.</param>
/// <param name="rotation">The rotation to apply.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector2 value, Quaternion rotation)
{
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wx2 = rotation.W * x2;
float wy2 = rotation.W * y2;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float xz2 = rotation.X * z2;
float yy2 = rotation.Y * y2;
float yz2 = rotation.Y * z2;
float zz2 = rotation.Z * z2;
return new Vector4(
value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2),
value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2),
value.X * (xz2 - wy2) + value.Y * (yz2 + wx2),
1.0f);
}
/// <summary>
/// Transforms a vector by the given Quaternion rotation value.
/// </summary>
/// <param name="value">The source vector to be rotated.</param>
/// <param name="rotation">The rotation to apply.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector3 value, Quaternion rotation)
{
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wx2 = rotation.W * x2;
float wy2 = rotation.W * y2;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float xz2 = rotation.X * z2;
float yy2 = rotation.Y * y2;
float yz2 = rotation.Y * z2;
float zz2 = rotation.Z * z2;
return new Vector4(
value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2) + value.Z * (xz2 + wy2),
value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2) + value.Z * (yz2 - wx2),
value.X * (xz2 - wy2) + value.Y * (yz2 + wx2) + value.Z * (1.0f - xx2 - yy2),
1.0f);
}
/// <summary>
/// Transforms a vector by the given Quaternion rotation value.
/// </summary>
/// <param name="value">The source vector to be rotated.</param>
/// <param name="rotation">The rotation to apply.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector4 value, Quaternion rotation)
{
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wx2 = rotation.W * x2;
float wy2 = rotation.W * y2;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float xz2 = rotation.X * z2;
float yy2 = rotation.Y * y2;
float yz2 = rotation.Y * z2;
float zz2 = rotation.Z * z2;
return new Vector4(
value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2) + value.Z * (xz2 + wy2),
value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2) + value.Z * (yz2 - wx2),
value.X * (xz2 - wy2) + value.Y * (yz2 + wx2) + value.Z * (1.0f - xx2 - yy2),
value.W);
}
#endregion Public Static Methods
#region Public operator methods
// All these methods should be inlines as they are implemented
// over JIT intrinsics
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Add(Vector4 left, Vector4 right)
{
return left + right;
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Subtract(Vector4 left, Vector4 right)
{
return left - right;
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Multiply(Vector4 left, Vector4 right)
{
return left * right;
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Multiply(Vector4 left, Single right)
{
return left * new Vector4(right, right, right, right);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Multiply(Single left, Vector4 right)
{
return new Vector4(left, left, left, left) * right;
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Divide(Vector4 left, Vector4 right)
{
return left / right;
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="divisor">The scalar value.</param>
/// <returns>The result of the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Divide(Vector4 left, Single divisor)
{
return left / divisor;
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Negate(Vector4 value)
{
return -value;
}
#endregion Public operator methods
}
}
| |
using System;
using System.Collections.Specialized;
using System.IO;
using System.Security.Principal;
using System.Text;
using System.Web;
namespace Coevery.Mvc.Wrappers {
public abstract class HttpRequestBaseWrapper : HttpRequestBase {
protected readonly HttpRequestBase _httpRequestBase;
protected HttpRequestBaseWrapper(HttpRequestBase httpRequestBase) {
_httpRequestBase = httpRequestBase;
}
public override byte[] BinaryRead(int count) {
return _httpRequestBase.BinaryRead(count);
}
public override int[] MapImageCoordinates(string imageFieldName) {
return _httpRequestBase.MapImageCoordinates(imageFieldName);
}
public override string MapPath(string virtualPath) {
return _httpRequestBase.MapPath(virtualPath);
}
public override string MapPath(string virtualPath, string baseVirtualDir, bool allowCrossAppMapping) {
return _httpRequestBase.MapPath(virtualPath, baseVirtualDir, allowCrossAppMapping);
}
public override void SaveAs(string filename, bool includeHeaders) {
_httpRequestBase.SaveAs(filename, includeHeaders);
}
public override void ValidateInput() {
_httpRequestBase.ValidateInput();
}
public override string[] AcceptTypes {
get {
return _httpRequestBase.AcceptTypes;
}
}
public override string AnonymousID {
get {
return _httpRequestBase.AnonymousID;
}
}
public override string ApplicationPath {
get {
return _httpRequestBase.ApplicationPath;
}
}
public override string AppRelativeCurrentExecutionFilePath {
get {
return _httpRequestBase.AppRelativeCurrentExecutionFilePath;
}
}
public override HttpBrowserCapabilitiesBase Browser {
get {
return _httpRequestBase.Browser;
}
}
public override HttpClientCertificate ClientCertificate {
get {
return _httpRequestBase.ClientCertificate;
}
}
public override Encoding ContentEncoding {
get {
return _httpRequestBase.ContentEncoding;
}
set {
_httpRequestBase.ContentEncoding = value;
}
}
public override int ContentLength {
get {
return _httpRequestBase.ContentLength;
}
}
public override string ContentType {
get {
return _httpRequestBase.ContentType;
}
set {
_httpRequestBase.ContentType = value;
}
}
public override HttpCookieCollection Cookies {
get {
return _httpRequestBase.Cookies;
}
}
public override string CurrentExecutionFilePath {
get {
return _httpRequestBase.CurrentExecutionFilePath;
}
}
public override string FilePath {
get {
return _httpRequestBase.FilePath;
}
}
public override HttpFileCollectionBase Files {
get {
return _httpRequestBase.Files;
}
}
public override Stream Filter {
get {
return _httpRequestBase.Filter;
}
set {
_httpRequestBase.Filter = value;
}
}
public override NameValueCollection Form {
get {
return _httpRequestBase.Form;
}
}
public override NameValueCollection Headers {
get {
return _httpRequestBase.Headers;
}
}
public override string HttpMethod {
get {
return _httpRequestBase.HttpMethod;
}
}
public override Stream InputStream {
get {
return _httpRequestBase.InputStream;
}
}
public override bool IsAuthenticated {
get {
return _httpRequestBase.IsAuthenticated;
}
}
public override bool IsLocal {
get {
return _httpRequestBase.IsLocal;
}
}
public override bool IsSecureConnection {
get {
return _httpRequestBase.IsSecureConnection;
}
}
public override string this[string key] {
get {
return _httpRequestBase[key];
}
}
public override WindowsIdentity LogonUserIdentity {
get {
return _httpRequestBase.LogonUserIdentity;
}
}
public override NameValueCollection Params {
get {
return _httpRequestBase.Params;
}
}
public override string Path {
get {
return _httpRequestBase.Path;
}
}
public override string PathInfo {
get {
return _httpRequestBase.PathInfo;
}
}
public override string PhysicalApplicationPath {
get {
return _httpRequestBase.PhysicalApplicationPath;
}
}
public override string PhysicalPath {
get {
return _httpRequestBase.PhysicalPath;
}
}
public override NameValueCollection QueryString {
get {
return _httpRequestBase.QueryString;
}
}
public override string RawUrl {
get {
return _httpRequestBase.RawUrl;
}
}
public override string RequestType {
get {
return _httpRequestBase.RequestType;
}
set {
_httpRequestBase.RequestType = value;
}
}
public override NameValueCollection ServerVariables {
get {
return _httpRequestBase.ServerVariables;
}
}
public override int TotalBytes {
get {
return _httpRequestBase.TotalBytes;
}
}
public override Uri Url {
get {
return _httpRequestBase.Url;
}
}
public override Uri UrlReferrer {
get {
return _httpRequestBase.UrlReferrer;
}
}
public override string UserAgent {
get {
return _httpRequestBase.UserAgent;
}
}
public override string UserHostAddress {
get {
return _httpRequestBase.UserHostAddress;
}
}
public override string UserHostName {
get {
return _httpRequestBase.UserHostName;
}
}
public override string[] UserLanguages {
get {
return _httpRequestBase.UserLanguages;
}
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// CSF Strands Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SCSFDataSet : EduHubDataSet<SCSF>
{
/// <inheritdoc />
public override string Name { get { return "SCSF"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal SCSFDataSet(EduHubContext Context)
: base(Context)
{
Index_SCSFKEY = new Lazy<Dictionary<string, SCSF>>(() => this.ToDictionary(i => i.SCSFKEY));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="SCSF" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="SCSF" /> fields for each CSV column header</returns>
internal override Action<SCSF, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<SCSF, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "SCSFKEY":
mapper[i] = (e, v) => e.SCSFKEY = v;
break;
case "KLA":
mapper[i] = (e, v) => e.KLA = v;
break;
case "STRAND":
mapper[i] = (e, v) => e.STRAND = v;
break;
case "SUB_STRAND":
mapper[i] = (e, v) => e.SUB_STRAND = v;
break;
case "ENABLED":
mapper[i] = (e, v) => e.ENABLED = v;
break;
case "DEET_REQUIRED":
mapper[i] = (e, v) => e.DEET_REQUIRED = v;
break;
case "LOW_LEVEL":
mapper[i] = (e, v) => e.LOW_LEVEL = v == null ? (short?)null : short.Parse(v);
break;
case "HIGH_LEVEL":
mapper[i] = (e, v) => e.HIGH_LEVEL = v == null ? (short?)null : short.Parse(v);
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="SCSF" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="SCSF" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="SCSF" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{SCSF}"/> of entities</returns>
internal override IEnumerable<SCSF> ApplyDeltaEntities(IEnumerable<SCSF> Entities, List<SCSF> DeltaEntities)
{
HashSet<string> Index_SCSFKEY = new HashSet<string>(DeltaEntities.Select(i => i.SCSFKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.SCSFKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_SCSFKEY.Remove(entity.SCSFKEY);
if (entity.SCSFKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, SCSF>> Index_SCSFKEY;
#endregion
#region Index Methods
/// <summary>
/// Find SCSF by SCSFKEY field
/// </summary>
/// <param name="SCSFKEY">SCSFKEY value used to find SCSF</param>
/// <returns>Related SCSF entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SCSF FindBySCSFKEY(string SCSFKEY)
{
return Index_SCSFKEY.Value[SCSFKEY];
}
/// <summary>
/// Attempt to find SCSF by SCSFKEY field
/// </summary>
/// <param name="SCSFKEY">SCSFKEY value used to find SCSF</param>
/// <param name="Value">Related SCSF entity</param>
/// <returns>True if the related SCSF entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySCSFKEY(string SCSFKEY, out SCSF Value)
{
return Index_SCSFKEY.Value.TryGetValue(SCSFKEY, out Value);
}
/// <summary>
/// Attempt to find SCSF by SCSFKEY field
/// </summary>
/// <param name="SCSFKEY">SCSFKEY value used to find SCSF</param>
/// <returns>Related SCSF entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SCSF TryFindBySCSFKEY(string SCSFKEY)
{
SCSF value;
if (Index_SCSFKEY.Value.TryGetValue(SCSFKEY, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a SCSF table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SCSF]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SCSF](
[SCSFKEY] varchar(5) NOT NULL,
[KLA] varchar(40) NULL,
[STRAND] varchar(40) NULL,
[SUB_STRAND] varchar(40) NULL,
[ENABLED] varchar(1) NULL,
[DEET_REQUIRED] varchar(1) NULL,
[LOW_LEVEL] smallint NULL,
[HIGH_LEVEL] smallint NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [SCSF_Index_SCSFKEY] PRIMARY KEY CLUSTERED (
[SCSFKEY] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="SCSFDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="SCSFDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SCSF"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="SCSF"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SCSF> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_SCSFKEY = new List<string>();
foreach (var entity in Entities)
{
Index_SCSFKEY.Add(entity.SCSFKEY);
}
builder.AppendLine("DELETE [dbo].[SCSF] WHERE");
// Index_SCSFKEY
builder.Append("[SCSFKEY] IN (");
for (int index = 0; index < Index_SCSFKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// SCSFKEY
var parameterSCSFKEY = $"@p{parameterIndex++}";
builder.Append(parameterSCSFKEY);
command.Parameters.Add(parameterSCSFKEY, SqlDbType.VarChar, 5).Value = Index_SCSFKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SCSF data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SCSF data set</returns>
public override EduHubDataSetDataReader<SCSF> GetDataSetDataReader()
{
return new SCSFDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SCSF data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SCSF data set</returns>
public override EduHubDataSetDataReader<SCSF> GetDataSetDataReader(List<SCSF> Entities)
{
return new SCSFDataReader(new EduHubDataSetLoadedReader<SCSF>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class SCSFDataReader : EduHubDataSetDataReader<SCSF>
{
public SCSFDataReader(IEduHubDataSetReader<SCSF> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 11; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // SCSFKEY
return Current.SCSFKEY;
case 1: // KLA
return Current.KLA;
case 2: // STRAND
return Current.STRAND;
case 3: // SUB_STRAND
return Current.SUB_STRAND;
case 4: // ENABLED
return Current.ENABLED;
case 5: // DEET_REQUIRED
return Current.DEET_REQUIRED;
case 6: // LOW_LEVEL
return Current.LOW_LEVEL;
case 7: // HIGH_LEVEL
return Current.HIGH_LEVEL;
case 8: // LW_DATE
return Current.LW_DATE;
case 9: // LW_TIME
return Current.LW_TIME;
case 10: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // KLA
return Current.KLA == null;
case 2: // STRAND
return Current.STRAND == null;
case 3: // SUB_STRAND
return Current.SUB_STRAND == null;
case 4: // ENABLED
return Current.ENABLED == null;
case 5: // DEET_REQUIRED
return Current.DEET_REQUIRED == null;
case 6: // LOW_LEVEL
return Current.LOW_LEVEL == null;
case 7: // HIGH_LEVEL
return Current.HIGH_LEVEL == null;
case 8: // LW_DATE
return Current.LW_DATE == null;
case 9: // LW_TIME
return Current.LW_TIME == null;
case 10: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // SCSFKEY
return "SCSFKEY";
case 1: // KLA
return "KLA";
case 2: // STRAND
return "STRAND";
case 3: // SUB_STRAND
return "SUB_STRAND";
case 4: // ENABLED
return "ENABLED";
case 5: // DEET_REQUIRED
return "DEET_REQUIRED";
case 6: // LOW_LEVEL
return "LOW_LEVEL";
case 7: // HIGH_LEVEL
return "HIGH_LEVEL";
case 8: // LW_DATE
return "LW_DATE";
case 9: // LW_TIME
return "LW_TIME";
case 10: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "SCSFKEY":
return 0;
case "KLA":
return 1;
case "STRAND":
return 2;
case "SUB_STRAND":
return 3;
case "ENABLED":
return 4;
case "DEET_REQUIRED":
return 5;
case "LOW_LEVEL":
return 6;
case "HIGH_LEVEL":
return 7;
case "LW_DATE":
return 8;
case "LW_TIME":
return 9;
case "LW_USER":
return 10;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
// <copyright file="DummyClient.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
namespace GooglePlayGames.BasicApi
{
using System;
using GooglePlayGames.BasicApi.Multiplayer;
using GooglePlayGames.OurUtils;
using UnityEngine.SocialPlatforms;
/// <summary>
/// Dummy client used in Editor.
/// </summary>
/// <remarks>Google Play Game Services are not supported in the Editor
/// environment, so this client is used as a placeholder.
/// </remarks>
public class DummyClient : IPlayGamesClient
{
/// <summary>
/// Starts the authentication process.
/// </summary>
/// <remarks> If silent == true, no UIs will be shown
/// (if UIs are needed, it will fail rather than show them). If silent == false,
/// this may show UIs, consent dialogs, etc.
/// At the end of the process, callback will be invoked to notify of the result.
/// Once the callback returns true, the user is considered to be authenticated
/// forever after.
/// </remarks>
/// <param name="callback">Callback when completed.</param>
/// <param name="silent">If set to <c>true</c> silent.</param>
public void Authenticate(Action<bool, string> callback, bool silent)
{
LogUsage();
if (callback != null)
{
callback(false, "Not implemented on this platform");
}
}
/// <summary>
/// Returns whether or not user is authenticated.
/// </summary>
/// <returns>true if authenticated</returns>
/// <c>false</c>
public bool IsAuthenticated()
{
LogUsage();
return false;
}
/// <summary>
/// Signs the user out.
/// </summary>
public void SignOut()
{
LogUsage();
}
/// <summary>
/// Returns an access token.
/// </summary>
/// <returns>The access token.</returns>
public string GetAccessToken()
{
LogUsage();
return "DummyAccessToken";
}
/// <summary>
/// Retrieves an id token, which can be verified server side, if they are logged in.
/// </summary>
/// <param name="idTokenCallback">The callback invoked with the token</param>
/// <returns>The identifier token.</returns>
public void GetIdToken(Action<string> idTokenCallback)
{
LogUsage();
if (idTokenCallback != null) {
idTokenCallback("DummyIdToken");
}
}
/// <summary>
/// Returns the authenticated user's ID. Note that this value may change if a user signs
/// on and signs in with a different account.
/// </summary>
/// <returns>The user identifier.</returns>
public string GetUserId()
{
LogUsage();
return "DummyID";
}
/// <summary>
/// Retrieves an OAuth 2.0 bearer token for the client.
/// </summary>
/// <returns>A string representing the bearer token.</returns>
public string GetToken()
{
return "DummyToken";
}
/// <summary>
/// Asynchronously retrieves the server auth code for this client.
/// </summary>
/// <remarks>
/// Note: This function is only implemented for Android.
/// </remarks>
/// <param name="serverClientId">The Client ID.</param>
/// <param name="callback">Callback for response.</param>
public void GetServerAuthCode(string serverClientId, Action<CommonStatusCodes, string> callback)
{
LogUsage();
if (callback != null)
{
callback(CommonStatusCodes.ApiNotConnected, "DummyServerAuthCode");
}
}
/// <summary>
/// Gets the user's email.
/// </summary>
/// <remarks>The email address returned is selected by the user from the accounts present
/// on the device. There is no guarantee this uniquely identifies the player.
/// For unique identification use the id property of the local player.
/// The user can also choose to not select any email address, meaning it is not
/// available.</remarks>
/// <returns>The user email or null if not authenticated or the permission is
/// not available.</returns>
public string GetUserEmail()
{
return string.Empty;
}
/// <summary>
/// Gets the user's email with a callback.
/// </summary>
/// <remarks>The email address returned is selected by the user from the accounts present
/// on the device. There is no guarantee this uniquely identifies the player.
/// For unique identification use the id property of the local player.
/// The user can also choose to not select any email address, meaning it is not
/// available.</remarks>
/// <param name="callback">The callback with a status code of the request,
/// and string which is the email. It can be null.</param>
public void GetUserEmail(Action<CommonStatusCodes, string> callback)
{
LogUsage();
if (callback != null)
{
callback(CommonStatusCodes.ApiNotConnected, null);
}
}
/// <summary>
/// Gets the player stats.
/// </summary>
/// <param name="callback">Callback for response.</param>
public void GetPlayerStats(Action<CommonStatusCodes, PlayerStats> callback)
{
LogUsage();
callback(CommonStatusCodes.ApiNotConnected, new PlayerStats());
}
/// <summary>
/// Returns a human readable name for the user, if they are logged in.
/// </summary>
/// <returns>The user display name.</returns>
public string GetUserDisplayName()
{
LogUsage();
return "Player";
}
/// <summary>
/// Returns the user's avatar url, if they are logged in and have an avatar.
/// </summary>
/// <returns>The user image URL.</returns>
public string GetUserImageUrl()
{
LogUsage();
return null;
}
/// <summary>
/// Loads the players specified.
/// </summary>
/// <remarks> This is mainly used by the leaderboard
/// APIs to get the information of a high scorer.
/// </remarks>
/// <param name="userIds">User identifiers.</param>
/// <param name="callback">Callback to invoke when completed.</param>
public void LoadUsers(string[] userIds, Action<IUserProfile[]> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(null);
}
}
/// <summary>
/// Loads the achievements for the current player.
/// </summary>
/// <param name="callback">Callback to invoke when completed.</param>
public void LoadAchievements(Action<Achievement[]> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(null);
}
}
/// <summary>
/// Returns the achievement corresponding to the passed achievement identifier.
/// </summary>
/// <returns>The achievement.</returns>
/// <param name="achId">Achievement identifier.</param>
public Achievement GetAchievement(string achId)
{
LogUsage();
return null;
}
/// <summary>
/// Unlocks the achievement.
/// </summary>
/// <param name="achId">Achievement identifier.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void UnlockAchievement(string achId, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Reveals the achievement.
/// </summary>
/// <param name="achId">Achievement identifier.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void RevealAchievement(string achId, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Increments the achievement.
/// </summary>
/// <param name="achId">Achievement identifier.</param>
/// <param name="steps">Steps to increment by..</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void IncrementAchievement(string achId, int steps, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Set an achievement to have at least the given number of steps completed.
/// </summary>
/// <remarks>
/// Calling this method while the achievement already has more steps than
/// the provided value is a no-op. Once the achievement reaches the
/// maximum number of steps, the achievement is automatically unlocked,
/// and any further mutation operations are ignored.
/// </remarks>
/// <param name="achId">Achievement identifier.</param>
/// <param name="steps">Steps to increment to at least.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void SetStepsAtLeast(string achId, int steps, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Shows the achievements UI
/// </summary>
/// <param name="callback">Callback to invoke when complete.</param>
public void ShowAchievementsUI(Action<UIStatus> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(UIStatus.VersionUpdateRequired);
}
}
/// <summary>
/// Shows the leaderboard UI
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="span">Timespan to display.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void ShowLeaderboardUI(
string leaderboardId,
LeaderboardTimeSpan span,
Action<UIStatus> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(UIStatus.VersionUpdateRequired);
}
}
/// <summary>
/// Returns the max number of scores returned per call.
/// </summary>
/// <returns>The max results.</returns>
public int LeaderboardMaxResults()
{
return 25;
}
/// <summary>
/// Loads the score data for the given leaderboard.
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="start">Start indicating the top scores or player centric</param>
/// <param name="rowCount">Row count.</param>
/// <param name="collection">Collection to display.</param>
/// <param name="timeSpan">Time span.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void LoadScores(
string leaderboardId,
LeaderboardStart start,
int rowCount,
LeaderboardCollection collection,
LeaderboardTimeSpan timeSpan,
Action<LeaderboardScoreData> callback)
{
LogUsage();
if (callback != null)
{
callback(new LeaderboardScoreData(
leaderboardId,
ResponseStatus.LicenseCheckFailed));
}
}
/// <summary>
/// Loads the more scores for the leaderboard.
/// </summary>
/// <remarks>The token is accessed
/// by calling LoadScores() with a positive row count.
/// </remarks>
/// <param name="token">Token used to start loading scores.</param>
/// <param name="rowCount">Max number of scores to return.
/// This can be limited by the SDK.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void LoadMoreScores(
ScorePageToken token,
int rowCount,
Action<LeaderboardScoreData> callback)
{
LogUsage();
if (callback != null)
{
callback(new LeaderboardScoreData(
token.LeaderboardId,
ResponseStatus.LicenseCheckFailed));
}
}
/// <summary>
/// Submits the score.
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="score">Score to submit.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void SubmitScore(string leaderboardId, long score, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Submits the score for the currently signed-in player
/// to the leaderboard associated with a specific id
/// and metadata (such as something the player did to earn the score).
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="score">Score value to submit.</param>
/// <param name="metadata">Metadata about the score.</param>
/// <param name="callback">Callback upon completion.</param>
public void SubmitScore(
string leaderboardId,
long score,
string metadata,
Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Returns a real-time multiplayer client.
/// </summary>
/// <seealso cref="GooglePlayGames.Multiplayer.IRealTimeMultiplayerClient"></seealso>
/// <returns>The rtmp client.</returns>
public IRealTimeMultiplayerClient GetRtmpClient()
{
LogUsage();
return null;
}
/// <summary>
/// Returns a turn-based multiplayer client.
/// </summary>
/// <returns>The tbmp client.</returns>
public ITurnBasedMultiplayerClient GetTbmpClient()
{
LogUsage();
return null;
}
/// <summary>
/// Gets the saved game client.
/// </summary>
/// <returns>The saved game client.</returns>
public SavedGame.ISavedGameClient GetSavedGameClient()
{
LogUsage();
return null;
}
/// <summary>
/// Gets the events client.
/// </summary>
/// <returns>The events client.</returns>
public GooglePlayGames.BasicApi.Events.IEventsClient GetEventsClient()
{
LogUsage();
return null;
}
/// <summary>
/// Gets the quests client.
/// </summary>
/// <returns>The quests client.</returns>
public GooglePlayGames.BasicApi.Quests.IQuestsClient GetQuestsClient()
{
LogUsage();
return null;
}
/// <summary>
/// Registers the invitation delegate.
/// </summary>
/// <param name="invitationDelegate">Invitation delegate.</param>
public void RegisterInvitationDelegate(InvitationReceivedDelegate invitationDelegate)
{
LogUsage();
}
/// <summary>
/// Gets the invitation from notification.
/// </summary>
/// <returns>The invitation from notification.</returns>
public Invitation GetInvitationFromNotification()
{
LogUsage();
return null;
}
/// <summary>
/// Determines whether this instance has invitation from notification.
/// </summary>
/// <returns><c>true</c> if this instance has invitation from notification; otherwise, <c>false</c>.</returns>
public bool HasInvitationFromNotification()
{
LogUsage();
return false;
}
/// <summary>
/// Load friends of the authenticated user
/// </summary>
/// <param name="callback">Callback invoked when complete. bool argument
/// indicates success.</param>
public void LoadFriends(Action<bool> callback)
{
LogUsage();
callback(false);
}
/// <summary>
/// Gets the friends.
/// </summary>
/// <returns>The friends.</returns>
public IUserProfile[] GetFriends()
{
LogUsage();
return new IUserProfile[0];
}
/// <summary>
/// Gets the Android API client. Returns null on non-Android players.
/// </summary>
/// <returns>The API client.</returns>
public IntPtr GetApiClient()
{
LogUsage();
return IntPtr.Zero;
}
/// <summary>
/// Logs the usage.
/// </summary>
private static void LogUsage()
{
Logger.d("Received method call on DummyClient - using stub implementation.");
}
}
}
#endif
| |
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
/// A custom editor for properties on the ResonanceAudioMaterialMap script. This appears in the
/// Inspector window of a ResonanceAudioMaterialMap object.
[CustomEditor(typeof(ResonanceAudioMaterialMap))]
public class ResonanceAudioMaterialMapEditor : Editor {
private SerializedProperty materialMappingGuids = null;
private SerializedProperty materialMappingSurfaceMaterials = null;
private GUIContent clearAllMappingLabel = new GUIContent("Reset All",
"Resets the material mapping selections to default.");
// The thumbnail previews of the surface materials in the inspector window, shown as solid color
// patches.
private Texture2D[] surfaceMaterialPreviews = null;
// Stored asset previews and names corresponding to GUIDS. Generated once when the Editor is
// enabled.
private Dictionary<string, Texture2D> assetPreviewFromGuid = null;
private Dictionary<string, string> guidNameFromGuid = null;
// Since asset previews for Unity Materials are loaded asynchronously, we keep a dictionary of
// those whose previews are not ready yet, and show a default icon for them.
private Dictionary<string, Material> materialWaitingForPreviewFromGuid = null;
private Texture2D cachedMaterialIcon = null;
private const int guidLabelWidth = 150;
private const int materialRowMargin = 5;
private const int materialPreviewSize = 50;
private GUILayoutOption previewHeight = null;
private GUILayoutOption previewWidth = null;
private GUIStyle materialRowStyle = null;
// The scroll position of the material mapping UI.
private Vector2 scrollPosition = Vector2.zero;
void OnEnable() {
InitializeProperties();
InitializeGuiParameters();
InitializeSurfaceMaterialPreviews();
materialWaitingForPreviewFromGuid = new Dictionary<string, Material>();
assetPreviewFromGuid = new Dictionary<string, Texture2D>();
guidNameFromGuid = new Dictionary<string, string>();
}
public override void OnInspectorGUI() {
serializedObject.Update();
DrawMaterialMappingGUI();
serializedObject.ApplyModifiedProperties();
}
// Initializes the material mapper and loads properties to be displayed in this window.
private void InitializeProperties() {
var surfaceMaterialFromGuid = serializedObject.FindProperty("surfaceMaterialFromGuid");
materialMappingGuids = surfaceMaterialFromGuid.FindPropertyRelative("guids");
materialMappingSurfaceMaterials =
surfaceMaterialFromGuid.FindPropertyRelative("surfaceMaterials");
}
// Initializes various GUI parameters.
private void InitializeGuiParameters() {
previewHeight = GUILayout.Height((float) materialPreviewSize);
previewWidth = GUILayout.Width((float) materialPreviewSize);
materialRowStyle = new GUIStyle();
materialRowStyle.margin = new RectOffset(materialRowMargin, materialRowMargin,
materialRowMargin, materialRowMargin);
}
// Initializes the thumbnail previews used in the material picking UI. Each surface material
// is shown as a square filled with solid color.
private void InitializeSurfaceMaterialPreviews() {
int numSurfaceMaterials = ResonanceAudioMaterialMap.surfaceMaterialColors.Length;
surfaceMaterialPreviews = new Texture2D[numSurfaceMaterials];
for (int surfaceMaterialIndex = 0; surfaceMaterialIndex < numSurfaceMaterials;
++surfaceMaterialIndex) {
var color = ResonanceAudioMaterialMap.surfaceMaterialColors[surfaceMaterialIndex];
Texture2D surfaceMaterialPreview = new Texture2D(materialPreviewSize, materialPreviewSize);
var pixelArraySize = surfaceMaterialPreview.GetPixels().Length;
Color[] pixelArray = new Color[pixelArraySize];
for (int pixelArrayIndex = 0; pixelArrayIndex < pixelArraySize; ++pixelArrayIndex) {
pixelArray[pixelArrayIndex] = color;
}
surfaceMaterialPreview.SetPixels(pixelArray);
surfaceMaterialPreview.Apply();
surfaceMaterialPreviews[surfaceMaterialIndex] = surfaceMaterialPreview;
}
}
// Draws the material mapping GUI. The GUI is organized as rows, each row having a GUID (a Unity
// Material or a TerrainData) on the left, and the mapped surface materials on the right.
private void DrawMaterialMappingGUI() {
// Show the material mapping as rows.
scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, GUILayout.ExpandHeight(false));
for (int i = 0; i < materialMappingGuids.arraySize; ++i) {
string guid = materialMappingGuids.GetArrayElementAtIndex(i).stringValue;
Texture2D assetPreview = null;
string guidName = null;
// Use the stored asset preview and GUID name or try to load them.
if((!assetPreviewFromGuid.TryGetValue(guid, out assetPreview) ||
!guidNameFromGuid.TryGetValue(guid, out guidName)) &&
!LoadAssetPreviewsAndGuidName(guid, out assetPreview, out guidName)) {
// Skip this row if the asset preview and GUID name are not stored and cannot be loaded.
continue;
}
// If the asset preview for the material has not been loaded, attempt to load it again.
Material materialWaitingForPreview = null;
if (materialWaitingForPreviewFromGuid.TryGetValue(guid, out materialWaitingForPreview)) {
assetPreview = GetClonedPreviewOrDefaultIconForMaterial(guid, materialWaitingForPreview);
assetPreviewFromGuid[guid] = assetPreview;
}
EditorGUILayout.BeginHorizontal(materialRowStyle);
GUILayout.Space(15 * EditorGUI.indentLevel);
DrawGuidColumn(assetPreview, guidName);
DrawSurfaceMaterialColumn(materialMappingSurfaceMaterials.GetArrayElementAtIndex(i));
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndScrollView();
EditorGUILayout.Separator();
DrawClearAllButton();
}
// Draws the GUID column: the thumbnail preview first, followed by the name.
private void DrawGuidColumn(Texture2D assetPreview, string guidName) {
// Draw the preview.
GUILayout.Box(assetPreview, GUIStyle.none, previewHeight, previewWidth);
// Display the name.
if (guidName != null) {
EditorGUILayout.LabelField(guidName, GUILayout.Width(guidLabelWidth));
}
}
// Draws the surface material column: the thumbnail preview first, followed by a drop-down menu
// to let users choose the mapped material.
private void DrawSurfaceMaterialColumn(SerializedProperty surfaceMaterialProperty) {
// Draw the preview.
var preview = surfaceMaterialPreviews[surfaceMaterialProperty.enumValueIndex];
GUILayout.Box(preview, GUIStyle.none, previewHeight, previewWidth);
// Draw the drop-down menu.
EditorGUILayout.PropertyField(surfaceMaterialProperty, GUIContent.none);
}
// Draws the "Clear All" button and clears the material mapping (by clearing the underlying
// serialized lists).
private void DrawClearAllButton() {
EditorGUILayout.BeginHorizontal();
GUILayout.Space(15 * EditorGUI.indentLevel);
if (GUILayout.Button(clearAllMappingLabel)) {
materialMappingGuids.ClearArray();
materialMappingSurfaceMaterials.ClearArray();
}
EditorGUILayout.EndHorizontal();
}
// Initializes the asset preview and name for a GUID to be shown in the UI, depending on
// whether the GUID identifies a Unity Material or a TerrainData.
private bool LoadAssetPreviewsAndGuidName(string guid, out Texture2D assetPreview,
out string guidName) {
string assetPath = AssetDatabase.GUIDToAssetPath(guid);
Material unityMaterial = (Material) AssetDatabase.LoadAssetAtPath(assetPath, typeof(Material));
if (unityMaterial != null) {
assetPreview = GetClonedPreviewOrDefaultIconForMaterial(guid, unityMaterial);
guidName = unityMaterial.name;
assetPreviewFromGuid.Add(guid, assetPreview);
guidNameFromGuid.Add(guid, guidName);
return true;
}
TerrainData terrainData = (TerrainData) AssetDatabase.LoadAssetAtPath(assetPath,
typeof(TerrainData));
if (terrainData != null) {
assetPreview = AssetPreview.GetMiniThumbnail(terrainData);
guidName = terrainData.name;
assetPreviewFromGuid.Add(guid, assetPreview);
guidNameFromGuid.Add(guid, guidName);
return true;
}
// Neither a Unity Material nor a TerrainData can be loaded from the GUID (perhaps the asset
// is removed from the project).
assetPreview = null;
guidName = null;
return false;
}
// Clones the asset preview for a Unity Material and returns it. If the asset preview is not
// loaded yet, records the Unity Material and returs a default icon.
private Texture2D GetClonedPreviewOrDefaultIconForMaterial(string guid, Material unityMaterial) {
Texture2D assetPreview = null;
var assetPreviewReference = AssetPreview.GetAssetPreview(unityMaterial);
if (assetPreviewReference != null) {
assetPreview = Instantiate<Texture2D>(assetPreviewReference);
materialWaitingForPreviewFromGuid.Remove(guid);
} else {
if (cachedMaterialIcon == null) {
string assetPath = AssetDatabase.GUIDToAssetPath(guid);
cachedMaterialIcon = (Texture2D) AssetDatabase.GetCachedIcon(assetPath);
}
assetPreview = cachedMaterialIcon;
materialWaitingForPreviewFromGuid[guid] = unityMaterial;
}
return assetPreview;
}
}
| |
// 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.Runtime.InteropServices;
using TestLibrary;
public class ReversePInvoke_MashalArrayByOut_AsManagedTest
{
public static int arrSize = 10;
public static int failures = 0;
#region Func Sig
[DllImport("ReversePInvokePassingByOutNative", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DoCallBack_MarshalByteArray_AsParam_AsByOut([MarshalAs(UnmanagedType.FunctionPtr)]DelByteArrByOutAsCdeclCaller caller);
[DllImport("ReversePInvokePassingByOutNative", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DoCallBack_MarshalSbyteArray_AsParam_AsByOut([MarshalAs(UnmanagedType.FunctionPtr)]DelSbyteArrByOutAsCdeclCaller caller);
[DllImport("ReversePInvokePassingByOutNative", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DoCallBack_MarshalShortArray_AsParam_AsByOut([MarshalAs(UnmanagedType.FunctionPtr)]DelShortArrByOutAsCdeclCaller caller);
[DllImport("ReversePInvokePassingByOutNative", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DoCallBack_MarshalShortArrayReturnNegativeSize_AsParam_AsByOut([MarshalAs(UnmanagedType.FunctionPtr)]DelShortArrByOutAsCdeclCaller caller);
[DllImport("ReversePInvokePassingByOutNative", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DoCallBack_MarshalUshortArray_AsParam_AsByOut([MarshalAs(UnmanagedType.FunctionPtr)]DelUshortArrByOutAsCdeclCaller caller);
[DllImport("ReversePInvokePassingByOutNative", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DoCallBack_MarshalInt32Array_AsParam_AsByOut([MarshalAs(UnmanagedType.FunctionPtr)]DelInt32ArrByOutAsCdeclCaller caller);
[DllImport("ReversePInvokePassingByOutNative", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DoCallBack_MarshalUint32Array_AsParam_AsByOut([MarshalAs(UnmanagedType.FunctionPtr)]DelUint32ArrByOutAsCdeclCaller caller);
[DllImport("ReversePInvokePassingByOutNative", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DoCallBack_MarshalLongArray_AsParam_AsByOut([MarshalAs(UnmanagedType.FunctionPtr)]DelLongArrByOutAsCdeclCaller caller);
[DllImport("ReversePInvokePassingByOutNative", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DoCallBack_MarshalUlongArray_AsParam_AsByOut([MarshalAs(UnmanagedType.FunctionPtr)]DelUlongArrByOutAsCdeclCaller caller);
[DllImport("ReversePInvokePassingByOutNative", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DoCallBack_MarshalStringArray_AsParam_AsByOut([MarshalAs(UnmanagedType.FunctionPtr)]DelStringArrByOutAsCdeclCaller caller);
#endregion
#region Delegate Method
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool DelByteArrByOutAsCdeclCaller([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out byte[] arrArg, out byte arraySize);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool DelSbyteArrByOutAsCdeclCaller(out sbyte arraySize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] out sbyte[] arrArg);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool DelShortArrByOutAsCdeclCaller([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out short[] arrArg, out short arraySize);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool DelUshortArrByOutAsCdeclCaller([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out ushort[] arrArg, out ushort arraySize);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool DelInt32ArrByOutAsCdeclCaller([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out Int32[] arrArg, out Int32 arraySize);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool DelUint32ArrByOutAsCdeclCaller([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out UInt32[] arrArg, out UInt32 arraySize);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool DelLongArrByOutAsCdeclCaller([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out long[] arrArg, out long arraySize);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool DelUlongArrByOutAsCdeclCaller([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out ulong[] arrArg, out ulong arraySize);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool DelStringArrByOutAsCdeclCaller([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1, ArraySubType = UnmanagedType.BStr)] out string[] arrArg, out Int32 arraySize);
#endregion
#region Test Method
//Type: byte ==> BYTE Array Size: byte.MinValue ==> 20
public static bool TestMethodForByteArray_AsReversePInvokeByOut_AsCdecl([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out byte[] arrArg, out byte arraySize)
{
arrArg = Helper.GetExpChangeArray<byte>(20);
arraySize = 20;
return true;
}
//Type: sbyte ==> CHAR Array Size: 1 ==> sbyte.MaxValue
public static bool TestMethodForSbyteArray_AsReversePInvokeByOut_AsCdecl(out sbyte arraySize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] out sbyte[] arrArg)
{
arrArg = Helper.GetExpChangeArray<sbyte>(sbyte.MaxValue);
arraySize = sbyte.MaxValue;
return true;
}
//Type: short ==> SHORT Array Size: -1 ==> 20(Actual 10 ==> 20)
public static bool TestMethodForShortArray_AsReversePInvokeByOut_AsCdecl([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out short[] arrArg, out short arraySize)
{
arrArg = Helper.GetExpChangeArray<short>(20);
arraySize = 20;
return true;
}
//Type: short ==> SHORT Array Size: 10 ==> -1(Actual 10 ==> 20)
public static bool TestMethodForShortArrayReturnNegativeSize_AsReversePInvokeByOut_AsCdecl([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out short[] arrArg, out short arraySize)
{
arrArg = Helper.GetExpChangeArray<short>(20);
arraySize = -1;
return true;
}
//Type: ushort ==> USHORT Array Size: ushort.MaxValue ==> 20
public static bool TestMethodForUshortArray_AsReversePInvokeByOut_AsCdecl([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out ushort[] arrArg, out ushort arraySize)
{
arrArg = Helper.GetExpChangeArray<ushort>(20);
arraySize = 20;
return true;
}
//Type: Int32 ==> LONG Array Size: 10 ==> 20
public static bool TestMethodForInt32Array_AsReversePInvokeByOut_AsCdecl([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out Int32[] arrArg, out Int32 arraySize)
{
arrArg = Helper.GetExpChangeArray<Int32>(20);
arraySize = 20;
return true;
}
//Type: UInt32 ==> ULONG Array Size: 10 ==> 20
public static bool TestMethodForUint32Array_AsReversePInvokeByOut_AsCdecl([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out UInt32[] arrArg, out UInt32 arraySize)
{
arrArg = Helper.GetExpChangeArray<UInt32>(20);
arraySize = 20;
return true;
}
//Type: long ==> LONGLONG Array Size: 10 ==> 20
public static bool TestMethodForLongArray_AsReversePInvokeByOut_AsCdecl([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out long[] arrArg, out long arraySize)
{
arrArg = Helper.GetExpChangeArray<long>(20);
arraySize = 20;
return true;
}
//Type: ulong ==> ULONGLONG Array Size: 10 ==> 20
public static bool TestMethodForUlongArray_AsReversePInvokeByOut_AsCdecl([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out ulong[] arrArg, out ulong arraySize)
{
arrArg = Helper.GetExpChangeArray<ulong>(20);
arraySize = 20;
return true;
}
//Type: string ==> BSTR Array Size: 10 ==> 20
public static bool TestMethodForStringArray_AsReversePInvokeByOut_AsCdecl([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1, ArraySubType = UnmanagedType.BStr)] out string[] arrArg, out Int32 arraySize)
{
arrArg = Helper.GetExpChangeArray<string>(20);
arraySize = 20;
return true;
}
#endregion
public static void RunTestByOut()
{
Console.WriteLine("ReversePInvoke C-Style Array marshaled by out with SizeParamIndex attribute(by out Array size).");
//Common value type
Console.WriteLine("\tScenario 1 : byte ==> BYTE, Array_Size = byte.MinValue, Return_Array_Size = 20");
Assert.IsTrue(DoCallBack_MarshalByteArray_AsParam_AsByOut(new DelByteArrByOutAsCdeclCaller(TestMethodForByteArray_AsReversePInvokeByOut_AsCdecl)));
Console.WriteLine("\t\tMarshalByteArray_AsReversePInvokeByOut_AsCdecl Passed!");
Console.WriteLine("\tScenario 2 : sbyte ==> CHAR, Array_Size = 1, Return_Array_Size = sbyte.Max");
Assert.IsTrue(DoCallBack_MarshalSbyteArray_AsParam_AsByOut(new DelSbyteArrByOutAsCdeclCaller(TestMethodForSbyteArray_AsReversePInvokeByOut_AsCdecl)));
Console.WriteLine("\t\tMarshalSbyteArray_AsReversePInvokeByOut_AsCdecl Passed!");
Console.WriteLine("\tScenario 3 : short ==> SHORT, Array_Size = -1, Return_Array_Size = 20");
Assert.IsTrue(DoCallBack_MarshalShortArray_AsParam_AsByOut(new DelShortArrByOutAsCdeclCaller(TestMethodForShortArray_AsReversePInvokeByOut_AsCdecl)));
Console.WriteLine("\t\tMarshalShortArray_AsReversePInvokeByOut_AsCdecl Failed!");
Console.WriteLine("\tScenario 4 : short ==> SHORT, Array_Size = 10, Return_Array_Size = -1");
Assert.IsTrue(DoCallBack_MarshalShortArrayReturnNegativeSize_AsParam_AsByOut(new DelShortArrByOutAsCdeclCaller(TestMethodForShortArrayReturnNegativeSize_AsReversePInvokeByOut_AsCdecl)));
Console.WriteLine("\t\tMarshalShortArray_AsReversePInvokeByOut_AsCdecl Passed!");
Console.WriteLine("\tScenario 5 : ushort ==> USHORT, Array_Size = ushort.MaxValue, Return_Array_Size = 20");
Assert.IsTrue(DoCallBack_MarshalUshortArray_AsParam_AsByOut(new DelUshortArrByOutAsCdeclCaller(TestMethodForUshortArray_AsReversePInvokeByOut_AsCdecl)));
Console.WriteLine("\t\tMarshalUshortArray_AsReversePInvokeByOut_AsCdecl Passed!");
Console.WriteLine("\tScenario 6 : Int32 ==> LONG, Array_Size = 10, Return_Array_Size = 20");
Assert.IsTrue(DoCallBack_MarshalInt32Array_AsParam_AsByOut(new DelInt32ArrByOutAsCdeclCaller(TestMethodForInt32Array_AsReversePInvokeByOut_AsCdecl)));
Console.WriteLine("\t\tMarshalInt32Array_AsReversePInvokeByOut_AsCdecl Passed!");
Console.WriteLine("\tScenario 7 : UInt32 ==> ULONG, Array_Size = 10, Return_Array_Size = 20");
Assert.IsTrue(DoCallBack_MarshalUint32Array_AsParam_AsByOut(new DelUint32ArrByOutAsCdeclCaller(TestMethodForUint32Array_AsReversePInvokeByOut_AsCdecl)));
Console.WriteLine("\t\tMarshalUint32Array_AsReversePInvokeByOut_AsCdecl Passed!");
Console.WriteLine("\tScenario 8 : long ==> LONGLONG, Array_Size = 10, Return_Array_Size = 20");
Assert.IsTrue(DoCallBack_MarshalLongArray_AsParam_AsByOut(new DelLongArrByOutAsCdeclCaller(TestMethodForLongArray_AsReversePInvokeByOut_AsCdecl)));
Console.WriteLine("\t\tMarshalLongArray_AsReversePInvokeByOut_AsCdecl Passed!");
Console.WriteLine("\tScenario 9 : ulong ==> ULONGLONG, Array_Size = 10, Return_Array_Size = 20");
Assert.IsTrue(DoCallBack_MarshalUlongArray_AsParam_AsByOut(new DelUlongArrByOutAsCdeclCaller(TestMethodForUlongArray_AsReversePInvokeByOut_AsCdecl)));
Console.WriteLine("\t\tMarshalUlongArray_AsReversePInvokeByOut_AsCdecl Passed!");
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Console.WriteLine("\tScenario 10 : string ==> BSTR, Array_Size = 10, Return_Array_Size = 20");
Assert.IsTrue(DoCallBack_MarshalStringArray_AsParam_AsByOut(new DelStringArrByOutAsCdeclCaller(TestMethodForStringArray_AsReversePInvokeByOut_AsCdecl)));
Console.WriteLine("\t\tMarshalStringArray_AsReversePInvokeByOut_AsCdecl Passed!");
}
}
public static int Main()
{
try{
RunTestByOut();
return 100;
}
catch (Exception e)
{
Console.WriteLine($"Test Failure: {e}");
return 101;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Cci;
using System.Diagnostics.Contracts;
namespace CSharpSourceEmitter {
public partial class SourceEmitter : CodeTraverser, ICSharpSourceEmitter {
public virtual void PrintTypeDefinition(ITypeDefinition typeDefinition) {
Contract.Requires(typeDefinition != null);
if (typeDefinition.IsDelegate) {
PrintDelegateDefinition(typeDefinition);
return;
}
if (((INamedEntity)typeDefinition).Name.Value.Contains("PrivateImplementationDetails")) return;
PrintTypeDefinitionAttributes(typeDefinition);
PrintToken(CSharpToken.Indent);
PrintTypeDefinitionVisibility(typeDefinition);
PrintTypeDefinitionModifiers(typeDefinition);
PrintTypeDefinitionKeywordType(typeDefinition);
PrintTypeDefinitionName(typeDefinition);
if (typeDefinition.IsGeneric) {
this.Traverse(typeDefinition.GenericParameters);
}
PrintTypeDefinitionBaseTypesAndInterfaces(typeDefinition);
PrintTypeDefinitionLeftCurly(typeDefinition);
// Get the members in metadata order for each type
// Note that it's important to preserve the metadata order here (eg. sequential layout fields,
// methods in COMImport types, etc.).
var members = new List<ITypeDefinitionMember>();
foreach (var m in typeDefinition.Methods) members.Add(m);
foreach (var m in typeDefinition.Events) members.Add(m);
foreach (var m in typeDefinition.Properties) members.Add(m);
foreach (var m in typeDefinition.Fields) members.Add(m);
foreach (var m in typeDefinition.NestedTypes) members.Add(m);
Traverse(members);
PrintTypeDefinitionRightCurly(typeDefinition);
}
public virtual void PrintDelegateDefinition(ITypeDefinition delegateDefinition) {
Contract.Requires(delegateDefinition != null);
PrintTypeDefinitionAttributes(delegateDefinition);
PrintToken(CSharpToken.Indent);
IMethodDefinition invokeMethod = null;
foreach (var invokeMember in delegateDefinition.GetMatchingMembers(m => m.Name.Value == "Invoke")) {
IMethodDefinition idef = invokeMember as IMethodDefinition;
if (idef != null) { invokeMethod = idef; break; }
}
PrintTypeDefinitionVisibility(delegateDefinition);
if (IsMethodUnsafe(invokeMethod))
PrintKeywordUnsafe();
PrintKeywordDelegate();
PrintMethodDefinitionReturnType(invokeMethod);
PrintToken(CSharpToken.Space);
PrintTypeDefinitionName(delegateDefinition);
if (delegateDefinition.GenericParameterCount > 0) {
this.Traverse(delegateDefinition.GenericParameters);
}
if (invokeMethod != null)
Traverse(invokeMethod.Parameters);
PrintToken(CSharpToken.Semicolon);
}
public virtual void PrintTypeDefinitionAttributes(ITypeDefinition typeDefinition) {
Contract.Requires(typeDefinition != null);
foreach (var attribute in SortAttributes(typeDefinition.Attributes)) {
// Skip DefaultMemberAttribute on a class that has an indexer
var at = Utils.GetAttributeType(attribute);
if (at == SpecialAttribute.DefaultMemberAttribute &&
IteratorHelper.Any(typeDefinition.Properties, p => IteratorHelper.EnumerableIsNotEmpty(p.Parameters)))
continue;
// Skip ExtensionAttribute
if (at == SpecialAttribute.Extension)
continue;
PrintAttribute(typeDefinition, attribute, true, null);
}
if (typeDefinition.Layout != LayoutKind.Auto) {
PrintPseudoCustomAttribute(typeDefinition,
"System.Runtime.InteropServices.StructLayout",
String.Format("System.Runtime.InteropServices.LayoutKind.{0}", typeDefinition.Layout.ToString()),
true, null);
}
}
public virtual void PrintTypeDefinitionVisibility(ITypeDefinition typeDefinition) {
if (typeDefinition is INamespaceTypeDefinition) {
INamespaceTypeDefinition namespaceTypeDefinition = typeDefinition as INamespaceTypeDefinition;
if (namespaceTypeDefinition.IsPublic)
PrintKeywordPublic();
} else if (typeDefinition is INestedTypeDefinition) {
INestedTypeDefinition nestedTypeDefinition = typeDefinition as INestedTypeDefinition;
PrintTypeMemberVisibility(nestedTypeDefinition.Visibility);
}
}
public virtual void PrintTypeDefinitionModifiers(ITypeDefinition typeDefinition) {
Contract.Requires(typeDefinition != null);
// If it's abstract and sealed and has no ctors, then it's a static class
if (typeDefinition.IsStatic) {
PrintKeywordStatic();
}
else {
if (typeDefinition.IsAbstract && !typeDefinition.IsInterface)
PrintKeywordAbstract();
if (typeDefinition.IsSealed && !typeDefinition.IsValueType)
PrintKeywordSealed();
}
}
public virtual void PrintTypeDefinitionKeywordType(ITypeDefinition typeDefinition) {
Contract.Requires(typeDefinition != null);
if (typeDefinition.IsInterface)
PrintKeywordInterface();
else if (typeDefinition.IsEnum)
PrintKeywordEnum();
else if (typeDefinition.IsValueType)
PrintKeywordStruct();
else
PrintKeywordClass();
}
public virtual void PrintKeywordClass() {
PrintToken(CSharpToken.Class);
}
public virtual void PrintKeywordInterface() {
PrintToken(CSharpToken.Interface);
}
public virtual void PrintKeywordStruct() {
PrintToken(CSharpToken.Struct);
}
public virtual void PrintKeywordEnum() {
PrintToken(CSharpToken.Enum);
}
public virtual void PrintKeywordDelegate() {
PrintToken(CSharpToken.Delegate);
}
public virtual void PrintTypeDefinitionName(ITypeDefinition typeDefinition) {
INamespaceTypeDefinition namespaceTypeDefinition = typeDefinition as INamespaceTypeDefinition;
if (namespaceTypeDefinition != null) {
PrintIdentifier(namespaceTypeDefinition.Name);
return;
}
INestedTypeDefinition nestedTypeDefinition = typeDefinition as INestedTypeDefinition;
if (nestedTypeDefinition != null) {
PrintIdentifier(nestedTypeDefinition.Name);
return;
}
INamedEntity namedEntity = typeDefinition as INamedEntity;
if (namedEntity != null) {
PrintIdentifier(namedEntity.Name);
} else {
sourceEmitterOutput.Write(typeDefinition.ToString());
}
}
public virtual void PrintTypeDefinitionBaseTypesAndInterfaces(ITypeDefinition typeDefinition) {
Contract.Requires(typeDefinition != null);
PrintBaseTypesAndInterfacesList(typeDefinition);
}
public virtual void PrintTypeDefinitionLeftCurly(ITypeDefinition typeDefinition) {
PrintToken(CSharpToken.LeftCurly);
}
public virtual void PrintTypeDefinitionRightCurly(ITypeDefinition typeDefinition) {
PrintToken(CSharpToken.RightCurly);
}
public new void Traverse(IEnumerable<ITypeDefinitionMember> typeMembers) {
Contract.Requires(typeMembers != null);
if (IteratorHelper.EnumerableIsNotEmpty(typeMembers) && IteratorHelper.First(typeMembers).ContainingTypeDefinition.IsEnum) {
// Enums don't get intervening blank lines
foreach (var member in typeMembers)
Traverse(member);
} else {
// Ensure there's exactly one blank line between each non-empty member
VisitWithInterveningBlankLines(typeMembers, m => Traverse(m));
}
}
}
}
| |
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 DataAccessTest.Web.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.IO;
using ATL.Logging;
using System.Collections.Generic;
using static ATL.AudioData.AudioDataManager;
using Commons;
using System.Text;
using static ATL.ChannelsArrangements;
namespace ATL.AudioData.IO
{
/// <summary>
/// Class for Portable Sound Format files manipulation (extensions : .PSF, .PSF1, .PSF2,
/// .MINIPSF, .MINIPSF1, .MINIPSF2, .SSF, .MINISSF, .DSF, .MINIDSF, .GSF, .MINIGSF, .QSF, .MINISQF)
/// According to Neil Corlett's specifications v. 1.6
/// </summary>
class PSF : MetaDataIO, IAudioDataIO
{
// Format Type Names
public const String PSF_FORMAT_UNKNOWN = "Unknown";
public const String PSF_FORMAT_PSF1 = "Playstation";
public const String PSF_FORMAT_PSF2 = "Playstation 2";
public const String PSF_FORMAT_SSF = "Saturn";
public const String PSF_FORMAT_DSF = "Dreamcast";
public const String PSF_FORMAT_USF = "Nintendo 64";
public const String PSF_FORMAT_QSF = "Capcom QSound";
// Tag predefined fields
public const String TAG_LENGTH = "length";
public const String TAG_FADE = "fade";
private const String PSF_FORMAT_TAG = "PSF";
private const String TAG_HEADER = "[TAG]";
private const uint HEADER_LENGTH = 16;
private const byte LINE_FEED = 0x0A;
private const byte SPACE = 0x20;
private const int PSF_DEFAULT_DURATION = 180000; // 3 minutes
private int sampleRate;
private double bitrate;
private double duration;
private bool isValid;
private SizeInfo sizeInfo;
private readonly string filePath;
private static IDictionary<string, byte> frameMapping; // Mapping between PSF frame codes and ATL frame codes
private static IList<string> playbackFrames; // Frames that are required for playback
// ---------- INFORMATIVE INTERFACE IMPLEMENTATIONS & MANDATORY OVERRIDES
// AudioDataIO
public int SampleRate // Sample rate (hz)
{
get { return this.sampleRate; }
}
public bool IsVBR
{
get { return false; }
}
public int CodecFamily
{
get { return AudioDataIOFactory.CF_SEQ_WAV; }
}
public string FileName
{
get { return filePath; }
}
public double BitRate
{
get { return bitrate; }
}
public double Duration
{
get { return duration; }
}
public ChannelsArrangement ChannelsArrangement
{
get { return ChannelsArrangements.STEREO; }
}
public bool IsMetaSupported(int metaDataType)
{
return (metaDataType == MetaDataIOFactory.TAG_NATIVE);
}
// IMetaDataIO
protected override int getDefaultTagOffset()
{
return TO_BUILTIN;
}
protected override int getImplementedTagType()
{
return MetaDataIOFactory.TAG_NATIVE;
}
protected override byte getFrameMapping(string zone, string ID, byte tagVersion)
{
byte supportedMetaId = 255;
// Finds the ATL field identifier according to the ID3v2 version
if (frameMapping.ContainsKey(ID.ToLower())) supportedMetaId = frameMapping[ID.ToLower()];
return supportedMetaId;
}
// === PRIVATE STRUCTURES/SUBCLASSES ===
private class PSFHeader
{
public String FormatTag; // Format tag (should be PSF_FORMAT_TAG)
public byte VersionByte; // Version mark
public uint ReservedAreaLength; // Length of reserved area (bytes)
public uint CompressedProgramLength; // Length of compressed program (bytes)
public void Reset()
{
FormatTag = "";
VersionByte = 0;
ReservedAreaLength = 0;
CompressedProgramLength = 0;
}
}
private class PSFTag
{
public String TagHeader; // Tag header (should be TAG_HEADER)
public int size;
public void Reset()
{
TagHeader = "";
size = 0;
}
}
// ---------- CONSTRUCTORS & INITIALIZERS
static PSF()
{
frameMapping = new Dictionary<string, byte>
{
{ "title", TagData.TAG_FIELD_TITLE },
{ "game", TagData.TAG_FIELD_ALBUM }, // Small innocent semantic shortcut
{ "artist", TagData.TAG_FIELD_ARTIST },
{ "copyright", TagData.TAG_FIELD_COPYRIGHT },
{ "comment", TagData.TAG_FIELD_COMMENT },
{ "year", TagData.TAG_FIELD_RECORDING_YEAR },
{ "genre", TagData.TAG_FIELD_GENRE },
{ "rating", TagData.TAG_FIELD_RATING } // Does not belong to the predefined standard PSF tags
};
playbackFrames = new List<string>
{
"volume",
"length",
"fade",
"filedir",
"filename",
"fileext"
};
}
private void resetData()
{
sampleRate = 44100; // Seems to be de facto value for all PSF files, even though spec doesn't say anything about it
bitrate = 0;
duration = 0;
ResetData();
}
public PSF(string filePath)
{
this.filePath = filePath;
resetData();
}
// ---------- SUPPORT METHODS
private bool readHeader(BinaryReader source, ref PSFHeader header)
{
header.FormatTag = Utils.Latin1Encoding.GetString(source.ReadBytes(3));
if (PSF_FORMAT_TAG == header.FormatTag)
{
header.VersionByte = source.ReadByte();
header.ReservedAreaLength = source.ReadUInt32();
header.CompressedProgramLength = source.ReadUInt32();
return true;
}
else
{
return false;
}
}
private string readPSFLine(Stream source, Encoding encoding)
{
long lineStart = source.Position;
long lineEnd;
bool hasEOL = true;
if (StreamUtils.FindSequence(source, new byte[1] { LINE_FEED }))
{
lineEnd = source.Position;
}
else
{
lineEnd = source.Length;
hasEOL = false;
}
source.Seek(lineStart, SeekOrigin.Begin);
byte[] data = new byte[lineEnd - lineStart];
source.Read(data, 0, data.Length);
for (int i=0;i<data.Length; i++) if (data[i] < SPACE) data[i] = SPACE; // According to spec : "All characters 0x01-0x20 are considered whitespace"
return encoding.GetString(data,0,data.Length - (hasEOL?1:0) ).Trim(); // -1 because we don't want to include LINE_FEED in the result
}
private bool readTag(BinaryReader source, ref PSFTag tag, ReadTagParams readTagParams)
{
long initialPosition = source.BaseStream.Position;
Encoding encoding = Utils.Latin1Encoding;
tag.TagHeader = Utils.Latin1Encoding.GetString(source.ReadBytes(5));
if (TAG_HEADER == tag.TagHeader)
{
string s = readPSFLine(source.BaseStream, encoding);
int equalIndex;
string keyStr, valueStr, lowKeyStr;
string lastKey = "";
string lastValue = "";
bool lengthFieldFound = false;
while ( s != "" )
{
equalIndex = s.IndexOf("=");
if (equalIndex != -1)
{
keyStr = s.Substring(0,equalIndex).Trim();
lowKeyStr = keyStr.ToLower();
valueStr = s.Substring(equalIndex+1, s.Length-(equalIndex+1)).Trim();
if (lowKeyStr.Equals("utf8") && valueStr.Equals("1")) encoding = Encoding.UTF8;
if (lowKeyStr.Equals(TAG_LENGTH) || lowKeyStr.Equals(TAG_FADE))
{
if (lowKeyStr.Equals(TAG_LENGTH)) lengthFieldFound = true;
duration += parsePSFDuration(valueStr);
}
// PSF specifics : a field appearing more than once is the same field, with values spanning over multiple lines
if (lastKey.Equals(keyStr))
{
lastValue += Environment.NewLine + valueStr;
}
else
{
SetMetaField(lastKey, lastValue, readTagParams.ReadAllMetaFrames);
lastValue = valueStr;
}
lastKey = keyStr;
}
s = readPSFLine(source.BaseStream, encoding);
} // Metadata lines
SetMetaField(lastKey, lastValue, readTagParams.ReadAllMetaFrames);
// PSF files without any 'length' tag take default duration, regardless of 'fade' value
if (!lengthFieldFound) duration = PSF_DEFAULT_DURATION;
tag.size = (int)(source.BaseStream.Position - initialPosition);
if (readTagParams.PrepareForWriting)
{
structureHelper.AddZone(initialPosition, tag.size);
}
return true;
}
else
{
return false;
}
}
private double parsePSFDuration(String durationStr)
{
String hStr = "";
String mStr = "";
String sStr = "";
String dStr = "";
double result = 0;
int sepIndex;
// decimal
sepIndex = durationStr.LastIndexOf(".");
if (-1 == sepIndex) sepIndex = durationStr.LastIndexOf(",");
if (-1 != sepIndex)
{
sepIndex++;
dStr = durationStr.Substring(sepIndex,durationStr.Length-sepIndex);
durationStr = durationStr.Substring(0,Math.Max(0,sepIndex-1));
}
// seconds
sepIndex = durationStr.LastIndexOf(":");
sepIndex++;
sStr = durationStr.Substring(sepIndex,durationStr.Length-sepIndex);
//if (1 == sStr.Length) sStr = sStr + "0"; // "2:2" means 2:20 and not 2:02
durationStr = durationStr.Substring(0,Math.Max(0,sepIndex-1));
// minutes
if (durationStr.Length > 0)
{
sepIndex = durationStr.LastIndexOf(":");
sepIndex++;
mStr = durationStr.Substring(sepIndex,durationStr.Length-sepIndex);
durationStr = durationStr.Substring(0,Math.Max(0,sepIndex-1));
}
// hours
if (durationStr.Length > 0)
{
sepIndex = durationStr.LastIndexOf(":");
sepIndex++;
hStr = durationStr.Substring(sepIndex,durationStr.Length-sepIndex);
}
if (dStr != "") result = result + (Int32.Parse(dStr) * 100);
if (sStr != "") result = result + (Int32.Parse(sStr) * 1000);
if (mStr != "") result = result + (Int32.Parse(mStr) * 60000);
if (hStr != "") result = result + (Int32.Parse(hStr) * 3600000);
return result;
}
// === PUBLIC METHODS ===
public bool Read(BinaryReader source, AudioDataManager.SizeInfo sizeInfo, MetaDataIO.ReadTagParams readTagParams)
{
this.sizeInfo = sizeInfo;
return read(source, readTagParams);
}
protected override bool read(BinaryReader source, MetaDataIO.ReadTagParams readTagParams)
{
bool result = true;
PSFHeader header = new PSFHeader();
PSFTag tag = new PSFTag();
header.Reset();
tag.Reset();
resetData();
isValid = readHeader(source, ref header);
if ( !isValid ) throw new Exception("Not a PSF file");
if (source.BaseStream.Length > HEADER_LENGTH+header.CompressedProgramLength+header.ReservedAreaLength)
{
source.BaseStream.Seek((long)(4+header.CompressedProgramLength+header.ReservedAreaLength),SeekOrigin.Current);
if (!readTag(source, ref tag, readTagParams)) throw new Exception("Not a PSF tag");
tagExists = true;
}
bitrate = (sizeInfo.FileSize-tag.size)* 8 / duration;
return result;
}
protected override int write(TagData tag, BinaryWriter w, string zone)
{
int result = 0;
w.Write(Utils.Latin1Encoding.GetBytes(TAG_HEADER));
// Announce UTF-8 support
w.Write(Utils.Latin1Encoding.GetBytes("utf8=1"));
w.Write(LINE_FEED);
IDictionary<byte, string> map = tag.ToMap();
// Supported textual fields
foreach (byte frameType in map.Keys)
{
foreach (string s in frameMapping.Keys)
{
if (frameType == frameMapping[s])
{
if (map[frameType].Length > 0) // No frame with empty value
{
writeTextFrame(w, s, map[frameType]);
result++;
}
break;
}
}
}
// Other textual fields
foreach (MetaFieldInfo fieldInfo in tag.AdditionalFields)
{
if ((fieldInfo.TagType.Equals(MetaDataIOFactory.TAG_ANY) || fieldInfo.TagType.Equals(getImplementedTagType())) && !fieldInfo.MarkedForDeletion && !fieldInfo.NativeFieldCode.Equals("utf8")) // utf8 already written
{
writeTextFrame(w, fieldInfo.NativeFieldCode, fieldInfo.Value);
result++;
}
}
// Remove the last end-of-line character
w.BaseStream.SetLength(w.BaseStream.Length - 1);
return result;
}
private void writeTextFrame(BinaryWriter writer, string frameCode, string text)
{
string[] textLines;
if (text.Contains(Environment.NewLine))
{
// Split a multiple-line value into multiple frames with the same code
textLines = text.Split(Environment.NewLine.ToCharArray());
}
else
{
textLines = new string[1] { text };
}
foreach (string s in textLines)
{
writer.Write(Utils.Latin1Encoding.GetBytes(frameCode));
writer.Write('=');
writer.Write(Encoding.UTF8.GetBytes(s));
writer.Write(LINE_FEED);
}
}
// Specific implementation for conservation of fields that are required for playback
public override bool Remove(BinaryWriter w)
{
TagData tag = new TagData();
foreach (byte b in frameMapping.Values)
{
tag.IntegrateValue(b, "");
}
string fieldCode;
foreach (MetaFieldInfo fieldInfo in GetAdditionalFields())
{
fieldCode = fieldInfo.NativeFieldCode.ToLower();
if (!fieldCode.StartsWith("_") && !playbackFrames.Contains(fieldCode) )
{
MetaFieldInfo emptyFieldInfo = new MetaFieldInfo(fieldInfo);
emptyFieldInfo.MarkedForDeletion = true;
tag.AdditionalFields.Add(emptyFieldInfo);
}
}
w.BaseStream.Seek(sizeInfo.ID3v2Size, SeekOrigin.Begin);
BinaryReader r = new BinaryReader(w.BaseStream);
return Write(r, w, tag);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace NPSSMSVoting.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class Event_Generic : PortsTest
{
// Maximum time to wait for all of the expected events to be firered
private static readonly int MAX_TIME_WAIT = 5000;
// Time to wait in-between triggering events
private static readonly int TRIGERING_EVENTS_WAIT_TIME = 500;
#region Test Cases
[OuterLoop("Slow Test")]
[ConditionalFact(nameof(HasNullModem))]
public void EventHandlers_CalledSerially()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, false, true);
ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, false, true);
ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, false, true);
int numPinChangedEvents = 0, numErrorEvents = 0, numReceivedEvents = 0;
int iterationWaitTime = 100;
/***************************************************************
Scenario Description: All of the event handlers should be called sequentially never
at the same time on multiple thread. Basically we will block each event handler caller thread and verify
that no other thread is in another event handler
***************************************************************/
Debug.WriteLine("Verifying that event handlers are called serially");
com1.WriteTimeout = 5000;
com2.WriteTimeout = 5000;
com1.Open();
com2.Open();
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
com1.PinChanged += pinChangedEventHandler.HandleEvent;
com1.DataReceived += receivedEventHandler.HandleEvent;
com1.ErrorReceived += errorEventHandler.HandleEvent;
//This should cause ErrorEvent to be fired with a parity error since the
//8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark),
//and com2 is writing 0 for this bit
com1.DataBits = 7;
com1.Parity = Parity.Mark;
com2.BaseStream.Write(new byte[1], 0, 1);
Debug.Print("ERROREvent Triggered");
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
//This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged
//since we are setting DtrEnable to true
com2.DtrEnable = true;
Debug.WriteLine("PinChange Triggered");
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
//This should cause ReceivedEvent to be fired with ReceivedChars
//since we are writing some bytes
com1.DataBits = 8;
com1.Parity = Parity.None;
com2.BaseStream.Write(new byte[] { 40 }, 0, 1);
Debug.WriteLine("RxEvent Triggered");
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
//This should cause a frame error since the 8th bit is not set,
//and com1 is set to 7 data bits so the 8th bit will +12v where
//com1 expects the stop bit at the 8th bit to be -12v
com1.DataBits = 7;
com1.Parity = Parity.None;
com2.BaseStream.Write(new byte[] { 0x01 }, 0, 1);
Debug.WriteLine("FrameError Triggered");
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
//This should cause PinChangedEvent to be fired with SerialPinChanges.CtsChanged
//since we are setting RtsEnable to true
com2.RtsEnable = true;
Debug.WriteLine("PinChange Triggered");
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
//This should cause ReceivedEvent to be fired with EofReceived
//since we are writing the EOF char
com1.DataBits = 8;
com1.Parity = Parity.None;
com2.BaseStream.Write(new byte[] { 26 }, 0, 1);
Debug.WriteLine("RxEOF Triggered");
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
//This should cause PinChangedEvent to be fired with SerialPinChanges.Break
//since we are setting BreakState to true
com2.BreakState = true;
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
bool threadFound = true;
Stopwatch sw = Stopwatch.StartNew();
while (threadFound && sw.ElapsedMilliseconds < MAX_TIME_WAIT)
{
threadFound = false;
for (int i = 0; i < MAX_TIME_WAIT / iterationWaitTime; ++i)
{
Debug.WriteLine("Event counts: PinChange {0}, Rx {1}, error {2}", numPinChangedEvents, numReceivedEvents, numErrorEvents);
Debug.WriteLine("Waiting for pinchange event {0}ms", iterationWaitTime);
if (pinChangedEventHandler.WaitForEvent(iterationWaitTime, numPinChangedEvents + 1))
{
// A thread is in PinChangedEvent: verify that it is not in any other handler at the same time
if (receivedEventHandler.NumEventsHandled != numReceivedEvents)
{
Fail("Err_191818ahied A thread is in PinChangedEvent and ReceivedEvent");
}
if (errorEventHandler.NumEventsHandled != numErrorEvents)
{
Fail("Err_198119hjaheid A thread is in PinChangedEvent and ErrorEvent");
}
++numPinChangedEvents;
pinChangedEventHandler.ResumeHandleEvent();
threadFound = true;
break;
}
Debug.WriteLine("Waiting for rx event {0}ms", iterationWaitTime);
if (receivedEventHandler.WaitForEvent(iterationWaitTime, numReceivedEvents + 1))
{
// A thread is in ReceivedEvent: verify that it is not in any other handler at the same time
if (pinChangedEventHandler.NumEventsHandled != numPinChangedEvents)
{
Fail("Err_2288ajed A thread is in ReceivedEvent and PinChangedEvent");
}
if (errorEventHandler.NumEventsHandled != numErrorEvents)
{
Fail("Err_25158ajeiod A thread is in ReceivedEvent and ErrorEvent");
}
++numReceivedEvents;
receivedEventHandler.ResumeHandleEvent();
threadFound = true;
break;
}
Debug.WriteLine("Waiting for error event {0}ms", iterationWaitTime);
if (errorEventHandler.WaitForEvent(iterationWaitTime, numErrorEvents + 1))
{
// A thread is in ErrorEvent: verify that it is not in any other handler at the same time
if (pinChangedEventHandler.NumEventsHandled != numPinChangedEvents)
{
Fail("Err_01208akiehd A thread is in ErrorEvent and PinChangedEvent");
}
if (receivedEventHandler.NumEventsHandled != numReceivedEvents)
{
Fail("Err_1254847ajied A thread is in ErrorEvent and ReceivedEvent");
}
++numErrorEvents;
errorEventHandler.ResumeHandleEvent();
threadFound = true;
break;
}
}
}
if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 3))
{
Fail("Err_2288ajied Expected 3 PinChangedEvents to be fired and only {0} occurred",
pinChangedEventHandler.NumEventsHandled);
}
if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 2))
{
Fail("Err_122808aoeid Expected 2 ReceivedEvents to be fired and only {0} occurred",
receivedEventHandler.NumEventsHandled);
}
if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 2))
{
Fail("Err_215887ajeid Expected 3 ErrorEvents to be fired and only {0} occurred",
errorEventHandler.NumEventsHandled);
}
//[] Verify all PinChangedEvents should have occurred
pinChangedEventHandler.Validate(SerialPinChange.DsrChanged, 0);
pinChangedEventHandler.Validate(SerialPinChange.CtsChanged, 0);
pinChangedEventHandler.Validate(SerialPinChange.Break, 0);
//[] Verify all ReceivedEvent should have occurred
receivedEventHandler.Validate(SerialData.Chars, 0);
receivedEventHandler.Validate(SerialData.Eof, 0);
//[] Verify all ErrorEvents should have occurred
errorEventHandler.Validate(SerialError.RXParity, 0);
errorEventHandler.Validate(SerialError.Frame, 0);
// It's important that we close com1 BEFORE com2 (the using() block would do this the other way around normally)
// This is because we have our special blocking event handlers hooked onto com1, and closing com2 is likely to
// cause a pin-change event which then hangs and prevents com1 from closing.
// An alternative approach would be to unhook all the event-handlers before leaving the using() block.
com1.Close();
}
}
[OuterLoop("Slow Test")]
[ConditionalFact(nameof(HasNullModem))]
public void Thread_In_PinChangedEvent()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, false, true);
Debug.WriteLine(
"Verifying that if a thread is blocked in a PinChangedEvent handler the port can still be closed");
com1.Open();
com2.Open();
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
com1.PinChanged += pinChangedEventHandler.HandleEvent;
//This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged
//since we are setting DtrEnable to true
com2.DtrEnable = true;
if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 1))
{
Fail("Err_32688ajoid Expected 1 PinChangedEvents to be fired and only {0} occurred",
pinChangedEventHandler.NumEventsHandled);
}
Task task = Task.Run(() => com1.Close());
Thread.Sleep(5000);
pinChangedEventHandler.ResumeHandleEvent();
TCSupport.WaitForTaskCompletion(task);
}
}
[OuterLoop("Slow Test")]
[ConditionalFact(nameof(HasNullModem))]
public void Thread_In_ReceivedEvent()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, false, true);
Debug.WriteLine(
"Verifying that if a thread is blocked in a RecevedEvent handler the port can still be closed");
com1.Open();
com2.Open();
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
com1.DataReceived += receivedEventHandler.HandleEvent;
//This should cause ReceivedEvent to be fired with ReceivedChars
//since we are writing some bytes
com1.DataBits = 8;
com1.Parity = Parity.None;
com2.BaseStream.Write(new byte[] { 40 }, 0, 1);
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 1))
{
Fail("Err_122808aoeid Expected 1 ReceivedEvents to be fired and only {0} occurred",
receivedEventHandler.NumEventsHandled);
}
Task task = Task.Run(() => com1.Close());
Thread.Sleep(5000);
receivedEventHandler.ResumeHandleEvent();
TCSupport.WaitForTaskCompletion(task);
}
}
[OuterLoop("Slow Test")]
[ConditionalFact(nameof(HasNullModem))]
public void Thread_In_ErrorEvent()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, false, true);
Debug.WriteLine("Verifying that if a thread is blocked in a ErrorEvent handler the port can still be closed");
com1.Open();
com2.Open();
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
com1.ErrorReceived += errorEventHandler.HandleEvent;
//This should cause ErrorEvent to be fired with a parity error since the
//8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark),
//and com2 is writing 0 for this bit
com1.DataBits = 7;
com1.Parity = Parity.Mark;
com2.BaseStream.Write(new byte[1], 0, 1);
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 1))
{
Fail("Err_215887ajeid Expected 1 ErrorEvents to be fired and only {0} occurred", errorEventHandler.NumEventsHandled);
}
Task task = Task.Run(() => com1.Close());
Thread.Sleep(5000);
errorEventHandler.ResumeHandleEvent();
TCSupport.WaitForTaskCompletion(task);
}
}
#endregion
#region Verification for Test Cases
private class PinChangedEventHandler : TestEventHandler<SerialPinChange>
{
public PinChangedEventHandler(SerialPort com, bool shouldThrow, bool shouldWait) : base(com, shouldThrow, shouldWait)
{
}
public void HandleEvent(object source, SerialPinChangedEventArgs e)
{
HandleEvent(source, e.EventType);
}
}
private class ErrorEventHandler : TestEventHandler<SerialError>
{
public ErrorEventHandler(SerialPort com, bool shouldThrow, bool shouldWait) : base(com, shouldThrow, shouldWait)
{
}
public void HandleEvent(object source, SerialErrorReceivedEventArgs e)
{
HandleEvent(source, e.EventType);
}
}
private class ReceivedEventHandler : TestEventHandler<SerialData>
{
public ReceivedEventHandler(SerialPort com, bool shouldThrow, bool shouldWait) : base(com, shouldThrow, shouldWait)
{
}
public void HandleEvent(object source, SerialDataReceivedEventArgs e)
{
HandleEvent(source, e.EventType);
}
}
#endregion
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// DataSessionResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Wireless.V1.Sim
{
public class DataSessionResource : Resource
{
private static Request BuildReadRequest(ReadDataSessionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Wireless,
"/v1/Sims/" + options.PathSimSid + "/DataSessions",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read DataSession parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of DataSession </returns>
public static ResourceSet<DataSessionResource> Read(ReadDataSessionOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<DataSessionResource>.FromJson("data_sessions", response.Content);
return new ResourceSet<DataSessionResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read DataSession parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of DataSession </returns>
public static async System.Threading.Tasks.Task<ResourceSet<DataSessionResource>> ReadAsync(ReadDataSessionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<DataSessionResource>.FromJson("data_sessions", response.Content);
return new ResourceSet<DataSessionResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathSimSid"> The SID of the Sim resource with the Data Sessions to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of DataSession </returns>
public static ResourceSet<DataSessionResource> Read(string pathSimSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadDataSessionOptions(pathSimSid){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathSimSid"> The SID of the Sim resource with the Data Sessions to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of DataSession </returns>
public static async System.Threading.Tasks.Task<ResourceSet<DataSessionResource>> ReadAsync(string pathSimSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadDataSessionOptions(pathSimSid){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<DataSessionResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<DataSessionResource>.FromJson("data_sessions", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<DataSessionResource> NextPage(Page<DataSessionResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Wireless)
);
var response = client.Request(request);
return Page<DataSessionResource>.FromJson("data_sessions", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<DataSessionResource> PreviousPage(Page<DataSessionResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Wireless)
);
var response = client.Request(request);
return Page<DataSessionResource>.FromJson("data_sessions", response.Content);
}
/// <summary>
/// Converts a JSON string into a DataSessionResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> DataSessionResource object represented by the provided JSON </returns>
public static DataSessionResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<DataSessionResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Sim resource that the Data Session is for
/// </summary>
[JsonProperty("sim_sid")]
public string SimSid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The generation of wireless technology that the device was using
/// </summary>
[JsonProperty("radio_link")]
public string RadioLink { get; private set; }
/// <summary>
/// The 'mobile country code' is the unique ID of the home country where the Data Session took place
/// </summary>
[JsonProperty("operator_mcc")]
public string OperatorMcc { get; private set; }
/// <summary>
/// The 'mobile network code' is the unique ID specific to the mobile operator network where the Data Session took place
/// </summary>
[JsonProperty("operator_mnc")]
public string OperatorMnc { get; private set; }
/// <summary>
/// The three letter country code representing where the device's Data Session took place
/// </summary>
[JsonProperty("operator_country")]
public string OperatorCountry { get; private set; }
/// <summary>
/// The friendly name of the mobile operator network that the SIM-connected device is attached to
/// </summary>
[JsonProperty("operator_name")]
public string OperatorName { get; private set; }
/// <summary>
/// The unique ID of the cellular tower that the device was attached to at the moment when the Data Session was last updated
/// </summary>
[JsonProperty("cell_id")]
public string CellId { get; private set; }
/// <summary>
/// An object with the estimated location where the device's Data Session took place
/// </summary>
[JsonProperty("cell_location_estimate")]
public object CellLocationEstimate { get; private set; }
/// <summary>
/// The number of packets uploaded by the device between the start time and when the Data Session was last updated
/// </summary>
[JsonProperty("packets_uploaded")]
public int? PacketsUploaded { get; private set; }
/// <summary>
/// The number of packets downloaded by the device between the start time and when the Data Session was last updated
/// </summary>
[JsonProperty("packets_downloaded")]
public int? PacketsDownloaded { get; private set; }
/// <summary>
/// The date that the resource was last updated, given as GMT in ISO 8601 format
/// </summary>
[JsonProperty("last_updated")]
public DateTime? LastUpdated { get; private set; }
/// <summary>
/// The date that the Data Session started, given as GMT in ISO 8601 format
/// </summary>
[JsonProperty("start")]
public DateTime? Start { get; private set; }
/// <summary>
/// The date that the record ended, given as GMT in ISO 8601 format
/// </summary>
[JsonProperty("end")]
public DateTime? End { get; private set; }
/// <summary>
/// The unique ID of the device using the SIM to connect
/// </summary>
[JsonProperty("imei")]
public string Imei { get; private set; }
private DataSessionResource()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using isukces.code.vssolutions;
using iSukces.Code.VsSolutions;
using ISukces.SolutionDoctor.Logic.Problems;
using JetBrains.Annotations;
namespace ISukces.SolutionDoctor.Logic.Checkers
{
internal class NugetPackageAssemblyBindingChecker
{
public static IEnumerable<Problem> Check([NotNull] IList<SolutionProject> projects,
HashSet<string> removeBindingRedirect, Dictionary<string, string> forceBindingRedirects)
{
if (projects == null) throw new ArgumentNullException(nameof(projects));
var tmp = new NugetPackageAssemblyBindingChecker
{
_removeBindingRedirect = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
_forceBindingRedirects = new Dictionary<string, NugetVersion>(StringComparer.OrdinalIgnoreCase)
};
if (removeBindingRedirect != null)
foreach (var i in removeBindingRedirect)
tmp._removeBindingRedirect.Add(i);
if (forceBindingRedirects != null)
foreach (var i in forceBindingRedirects)
tmp._forceBindingRedirects[i.Key] = NugetVersion.Parse(i.Value);
return projects.SelectMany(tmp.ScanProject).ToList();
}
public static Result FindPossibleOrNull(FileInfo fileInfo, FrameworkVersion project)
{
string dirShortName = null;
var d = fileInfo.Directory;
var list = new List<string>();
while (d != null)
{
if (d.Name == "lib")
{
dirShortName = list.LastOrDefault();
}
list.Add(d.Name);
d = d.Parent;
}
// var dirShortName = fileInfo.Directory?.Name;
if (string.IsNullOrEmpty(dirShortName))
return null;
var nugetVersions = FrameworkVersion.Parse(dirShortName);
if (nugetVersions is null || nugetVersions.Any(version => version == null))
return null;
// throw new NotSupportedException();
var possible = nugetVersions
.Select(q =>
{
var tmp = project.CanLoad(q);
if (tmp == NugetLoadCompatibility.None)
return null;
return new PossibleToLoadNuget(q, tmp);
})
.Where(a=>a != null)
.OrderBy(a => a)
.ToArray();
switch (possible.Length)
{
case 0:
return null;
case 1:
return new Result(possible[0], new FileName(fileInfo));
default:
return new Result(possible.Last(), new FileName(fileInfo));
}
}
private static void Can(string path, List<FileInfo> sink)
{
var di = new DirectoryInfo(path);
if (!di.Exists)
return;
sink.AddRange(di.GetFiles("*.dll"));
foreach (var i in di.GetDirectories())
Can(i.FullName, sink);
}
private static Func<FileInfo, bool> ContainsPackagePath(NugetPackage package)
{
var path = "\\packages\\" + package.Id + "." + package.Version + "\\";
return a => a != null && a.FullName.ToLower().Contains(path.ToLowerInvariant());
}
private static FileInfo[] FindDlls(SolutionProject project, NugetPackage package)
{
var dlls =
project.References.Select(a => a.HintPath)
.Where(ContainsPackagePath(package))
.ToArray();
var path = Path.Combine(HardCoded.Cache, package.Id, package.Version.ToString(), "lib");
if (Directory.Exists(path))
{
var sink = new List<FileInfo>();
Can(path, sink);
sink.AddRange(dlls);
dlls = sink.ToArray();
}
if (dlls.Length < 2)
return dlls;
var t = project.TargetFrameworkVersion;
if (string.IsNullOrEmpty(t))
return dlls;
var projectFrameworkVersion = FrameworkVersion.Parse(t).Single();
if (projectFrameworkVersion is null)
return dlls;
var tmp = dlls.Select(fileInfo => FindPossibleOrNull(fileInfo, projectFrameworkVersion))
.Where(a => a != null)
.OrderBy(a => a.Loading)
.GroupBy(a => a.File.Name)
.ToDictionary(a => a.Key, a => a.ToArray())
.ToArray();
if (tmp.Length == 1)
{
var values = tmp.Single().Value;
if (values.Length == 1)
return new[] {values.Single().File.GetFileInfo()};
return new[] {values.Last().File.GetFileInfo()};
}
return dlls;
}
private static DllInfo GetDllInfo(FileInfo file)
{
if (!file.Exists)
return new DllInfo(file, null, false);
try
{
/*if (file.FullName.ToLower().Contains("system.io.comp"))
{
Debug.Write("");
{
AppDomain domain = AppDomain.CreateDomain("TempDomain");
InstanceProxy proxy = domain.CreateInstanceAndUnwrap(Assembly.GetAssembly(
typeof(InstanceProxy)).FullName, typeof(InstanceProxy).ToString()) as InstanceProxy;
if (proxy != null)
{
proxy.LoadAssembly(file.FullName);
}
AppDomain.Unload(domain);
}
}*/
var currentAssemblyName = AssemblyName.GetAssemblyName(file.FullName);
var version = currentAssemblyName.Version;
var compression = @"packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll";
if (file.FullName.ToLower().EndsWith(compression.ToLower())) version = Version.Parse("4.2.0.0");
return new DllInfo(file, version.ToString(), true);
}
catch
{
return new DllInfo(file, null, true);
}
}
private IEnumerable<Problem> ScanProject(SolutionProject project)
{
var assemblyBindings = project.AssemblyBindings;
var packageVersion = project.NugetPackages;
if (!assemblyBindings.Any()) yield break;
if (_removeBindingRedirect != null && _removeBindingRedirect.Any())
foreach (var i in assemblyBindings)
if (_removeBindingRedirect.Contains(i.Name))
yield return new NotNecessaryOrForceVersionBindingRedirectProblem
{
Redirect = i,
ProjectFilename = project.Location
};
else if (_forceBindingRedirects.TryGetValue(i.Name, out var version))
if (i.NewVersion != version)
yield return new NotNecessaryOrForceVersionBindingRedirectProblem
{
Redirect = i,
ProjectFilename = project.Location,
Version = version
};
if (!packageVersion.Any()) yield break;
foreach (var package in packageVersion)
{
if (project.Kind == VsProjectKind.Core)
{
var redirects = assemblyBindings.Where(
a => string.Equals(a.Name, package.Id, StringComparison.OrdinalIgnoreCase))
.ToArray();
foreach (var i in redirects)
if (i.Name != package.Id)
yield return new AssemblyRedirectionInvalidPackageId(package.Id, project);
continue;
}
var redirect =
assemblyBindings.FirstOrDefault(
a => string.Equals(a.Name, package.Id, StringComparison.OrdinalIgnoreCase));
if (redirect == null) continue;
var dlls = FindDlls(project, package);
var dlls2 = dlls
.GroupBy(a => a.Name, FileName.FileNameComparer)
.ToDictionary(a => a.Key, a => a.ToArray());
{
bool Check()
{
foreach (var i in dlls2.Keys)
{
var n = new FileInfo(i);
var nn = i.Substring(0, i.Length - n.Extension.Length) + ".resources" + n.Extension;
if (dlls2.ContainsKey(nn))
{
dlls2.Remove(nn);
return true;
}
}
return false;
}
bool next = true;
while (next && dlls2.Count>1)
{
next = Check();
}
}
if (dlls2.Count == 0)
{
yield return new UnableToGetReferencedDllVersionProblem(package.Id, project, "no hint path to dll");
continue;
}
if (dlls2.Count > 1)
{
yield return new UnableToGetReferencedDllVersionProblem(package.Id, project,
$"Too many hint paths to dll for {package.Id} ver {package.Version} package. Probably package contains more than one dll inside.");
continue;
}
dlls = dlls.Where(a =>
{
var name = a.GetShortNameWithoutExtension();
if (_removeBindingRedirect.Contains(name))
return false;
if (_forceBindingRedirects.ContainsKey(name))
return false;
return true;
}).ToArray();
if (dlls.Length == 0) continue;
var versions = dlls.Select(GetDllInfo).Distinct().ToArray();
{
var aa = versions.Where(q => q.DllVersion == null || !q.Exists).ToArray();
if (aa.Any())
{
foreach (var aaa in aa)
yield return
new UnableToGetReferencedDllVersionProblem(package.Id, project,
"Broken file " + aaa?.File);
continue;
}
}
var vers2 = versions.Select(a => a.DllVersion).Distinct().ToArray();
if (vers2.Length != 1)
{
yield return new UnableToGetReferencedDllVersionProblem(package.Id, project,
"Too many possible versions to compare");
continue;
}
if (vers2.Any(a => a == redirect.NewVersion.NormalizedVersion.ToString())) continue;
yield return new WrongBindingRedirectProblem
{
ProjectFilename = project.Location,
Redirect = redirect,
Package = package,
DllVersion = versions[0].DllVersion
};
}
}
private HashSet<string> _removeBindingRedirect;
public Dictionary<string, NugetVersion> _forceBindingRedirects;
[ImmutableObject(true)]
public class Result
{
public Result(PossibleToLoadNuget loading, FileName file)
{
Loading = loading;
File = file;
}
public override string ToString()
{
return $"Loading={Loading}, File={File}";
}
public PossibleToLoadNuget Loading { get; }
public FileName File { get; }
}
public class InstanceProxy : MarshalByRefObject
{
public void LoadAssembly(string path)
{
AppDomain.CurrentDomain.AssemblyResolve += (a, b) => { return null; };
var asm = Assembly.LoadFile(path);
var types = asm.GetExportedTypes();
var ver1 = asm.GetName();
var ver2 = ver1.Version;
Console.WriteLine(ver1);
var assemblyVersion = asm.GetName().Version.ToString();
//string assemblyVersion = Assembly.LoadFile("your assembly file").GetName().Version.ToString();
var fileVersion = FileVersionInfo.GetVersionInfo(asm.Location).FileVersion;
var productVersion = FileVersionInfo.GetVersionInfo(asm.Location).ProductVersion;
var fileVersion2 = FileVersionInfo.GetVersionInfo(path).FileVersion;
var productVersion2 = FileVersionInfo.GetVersionInfo(path).ProductVersion;
// ...see above...
}
}
private class DllInfo
{
public DllInfo(FileInfo file, string dllVersion, bool exists)
{
File = file;
DllVersion = dllVersion;
Exists = exists;
}
public FileInfo File { get; }
public string DllVersion { get; }
public bool Exists { get; }
}
}
}
| |
namespace StudyServer.Models
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class Model1 : DbContext
{
public Model1()
: base("name=Model1")
{
}
public virtual DbSet<BUSINESS_CHANGDAO> BUSINESS_CHANGDAO { get; set; }
public virtual DbSet<BUSINESS_FUSHAN> BUSINESS_FUSHAN { get; set; }
public virtual DbSet<BUSINESS_HAIYANG> BUSINESS_HAIYANG { get; set; }
public virtual DbSet<BUSINESS_LAISHAN> BUSINESS_LAISHAN { get; set; }
public virtual DbSet<BUSINESS_LAIYANG> BUSINESS_LAIYANG { get; set; }
public virtual DbSet<BUSINESS_LAIZHOU> BUSINESS_LAIZHOU { get; set; }
public virtual DbSet<BUSINESS_LONGKOU> BUSINESS_LONGKOU { get; set; }
public virtual DbSet<BUSINESS_MUPING> BUSINESS_MUPING { get; set; }
public virtual DbSet<BUSINESS_PENGLAI> BUSINESS_PENGLAI { get; set; }
public virtual DbSet<BUSINESS_QIXIA> BUSINESS_QIXIA { get; set; }
public virtual DbSet<BUSINESS_ZHAOYUAN> BUSINESS_ZHAOYUAN { get; set; }
public virtual DbSet<BUSINESS_ZHIFU> BUSINESS_ZHIFU { get; set; }
public virtual DbSet<BUSINESSCATEGORY> BUSINESSCATEGORY { get; set; }
public virtual DbSet<BUSINESSORDINAL> BUSINESSORDINAL { get; set; }
public virtual DbSet<CARINFOR> CARINFOR { get; set; }
public virtual DbSet<CATEGORIES> CATEGORIES { get; set; }
public virtual DbSet<CONFIG> CONFIG { get; set; }
public virtual DbSet<CORPORATEINFO> CORPORATEINFO { get; set; }
public virtual DbSet<COUNTY> COUNTY { get; set; }
public virtual DbSet<ONLINEILLEGAL> ONLINEILLEGAL { get; set; }
public virtual DbSet<ONLINERECORD> ONLINERECORD { get; set; }
public virtual DbSet<ONLINEUSER> ONLINEUSER { get; set; }
public virtual DbSet<POPULATION> POPULATION { get; set; }
public virtual DbSet<STUDYHISTORYRECORD> STUDYHISTORYRECORD { get; set; }
public virtual DbSet<SYNCUSER> SYNCUSER { get; set; }
public virtual DbSet<USERS> USERS { get; set; }
public virtual DbSet<ZHIFUBUSINESS> ZHIFUBUSINESS { get; set; }
public virtual DbSet<VITALLOG> VITALLOG { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.SERIAL_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.REJECT_REASON)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.PHONE_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.PROCESS_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.FILE_RECV_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.TRANSFER_STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.UPLOADER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.COMPLETE_PAY_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.ATTENTION)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.POSTPHONE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.POSTADDR)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.CHECK_FILE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.CAR_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.TAX_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.TAX_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.ORIGIN_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_CHANGDAO>()
.Property(e => e.ORIGIN_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.SERIAL_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.REJECT_REASON)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.PHONE_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.PROCESS_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.FILE_RECV_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.TRANSFER_STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.UPLOADER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.COMPLETE_PAY_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.ATTENTION)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.POSTPHONE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.POSTADDR)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.CHECK_FILE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.CAR_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.TAX_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.TAX_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.ORIGIN_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_FUSHAN>()
.Property(e => e.ORIGIN_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.SERIAL_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.REJECT_REASON)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.PHONE_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.PROCESS_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.FILE_RECV_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.TRANSFER_STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.UPLOADER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.COMPLETE_PAY_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.ATTENTION)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.POSTPHONE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.POSTADDR)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.CHECK_FILE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.CAR_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.TAX_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.TAX_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.ORIGIN_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_HAIYANG>()
.Property(e => e.ORIGIN_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.SERIAL_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.REJECT_REASON)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.PHONE_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.PROCESS_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.FILE_RECV_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.TRANSFER_STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.UPLOADER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.COMPLETE_PAY_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.ATTENTION)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.POSTPHONE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.POSTADDR)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.CHECK_FILE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.CAR_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.TAX_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.TAX_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.ORIGIN_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAISHAN>()
.Property(e => e.ORIGIN_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.SERIAL_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.REJECT_REASON)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.PHONE_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.PROCESS_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.FILE_RECV_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.TRANSFER_STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.UPLOADER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.COMPLETE_PAY_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.ATTENTION)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.POSTPHONE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.POSTADDR)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.CHECK_FILE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.CAR_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.TAX_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.TAX_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.ORIGIN_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIYANG>()
.Property(e => e.ORIGIN_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.SERIAL_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.REJECT_REASON)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.PHONE_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.PROCESS_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.FILE_RECV_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.TRANSFER_STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.UPLOADER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.COMPLETE_PAY_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.ATTENTION)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.POSTPHONE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.POSTADDR)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.CHECK_FILE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.CAR_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.TAX_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.TAX_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.ORIGIN_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LAIZHOU>()
.Property(e => e.ORIGIN_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.SERIAL_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.REJECT_REASON)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.PHONE_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.PROCESS_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.FILE_RECV_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.TRANSFER_STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.UPLOADER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.COMPLETE_PAY_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.ATTENTION)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.POSTPHONE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.POSTADDR)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.CHECK_FILE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.CAR_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.TAX_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.TAX_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.ORIGIN_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_LONGKOU>()
.Property(e => e.ORIGIN_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.SERIAL_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.REJECT_REASON)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.PHONE_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.PROCESS_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.FILE_RECV_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.TRANSFER_STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.UPLOADER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.COMPLETE_PAY_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.ATTENTION)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.POSTPHONE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.POSTADDR)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.CHECK_FILE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.CAR_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.TAX_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.TAX_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.ORIGIN_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_MUPING>()
.Property(e => e.ORIGIN_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.SERIAL_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.REJECT_REASON)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.PHONE_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.PROCESS_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.FILE_RECV_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.TRANSFER_STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.UPLOADER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.COMPLETE_PAY_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.ATTENTION)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.POSTPHONE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.POSTADDR)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.CHECK_FILE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.CAR_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.TAX_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.TAX_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.ORIGIN_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_PENGLAI>()
.Property(e => e.ORIGIN_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.SERIAL_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.REJECT_REASON)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.PHONE_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.PROCESS_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.FILE_RECV_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.TRANSFER_STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.UPLOADER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.COMPLETE_PAY_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.ATTENTION)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.POSTPHONE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.POSTADDR)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.CHECK_FILE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.CAR_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.TAX_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.TAX_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.ORIGIN_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_QIXIA>()
.Property(e => e.ORIGIN_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.SERIAL_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.REJECT_REASON)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.PHONE_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.PROCESS_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.FILE_RECV_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.TRANSFER_STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.UPLOADER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.COMPLETE_PAY_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.ATTENTION)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.POSTPHONE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.POSTADDR)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.CHECK_FILE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.CAR_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.TAX_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.TAX_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.ORIGIN_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHAOYUAN>()
.Property(e => e.ORIGIN_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.SERIAL_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.REJECT_REASON)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.PHONE_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.PROCESS_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.FILE_RECV_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.TRANSFER_STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.UPLOADER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.COMPLETE_PAY_USER)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.ATTENTION)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.POSTPHONE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.POSTADDR)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.CHECK_FILE)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.CAR_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.TAX_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.TAX_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.ORIGIN_TYPE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESS_ZHIFU>()
.Property(e => e.ORIGIN_NUM)
.IsUnicode(false);
modelBuilder.Entity<BUSINESSCATEGORY>()
.Property(e => e.BUSINESSCODE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESSCATEGORY>()
.Property(e => e.BUSINESSNAME)
.IsUnicode(false);
modelBuilder.Entity<BUSINESSCATEGORY>()
.Property(e => e.CATEGORY)
.IsUnicode(false);
modelBuilder.Entity<BUSINESSCATEGORY>()
.Property(e => e.SERVICEAPI)
.IsUnicode(false);
modelBuilder.Entity<BUSINESSORDINAL>()
.Property(e => e.BUSINESSDATE)
.IsUnicode(false);
modelBuilder.Entity<BUSINESSORDINAL>()
.Property(e => e.CATEGORY)
.IsUnicode(false);
modelBuilder.Entity<BUSINESSORDINAL>()
.Property(e => e.ORDINAL)
.HasPrecision(38, 0);
modelBuilder.Entity<BUSINESSORDINAL>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.CAR_NUM)
.IsUnicode(false);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.BRAND)
.IsUnicode(false);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.MODEL_TYPE)
.IsUnicode(false);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.VIN)
.IsUnicode(false);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.PLATE_TYPE)
.IsUnicode(false);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.OWNER)
.IsUnicode(false);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.OWNER_ID)
.IsUnicode(false);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.CAR_LENGTH)
.HasPrecision(38, 0);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.CAR_WIDTH)
.HasPrecision(38, 0);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.CAR_HEIGHT)
.HasPrecision(38, 0);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.STANDARD_LENGTH)
.HasPrecision(38, 0);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.STANDARD_WIDTH)
.HasPrecision(38, 0);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.STANDARD_HEIGHT)
.HasPrecision(38, 0);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.QUEUE_NUM)
.IsUnicode(false);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.SERIAL_NUM)
.IsUnicode(false);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.FINISH)
.HasPrecision(38, 0);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.TASK_TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.INSPECTOR)
.IsUnicode(false);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.RECHECKER)
.IsUnicode(false);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.UNLOAD_TASK_NUM)
.IsUnicode(false);
modelBuilder.Entity<CARINFOR>()
.Property(e => e.INVALID_TASK)
.HasPrecision(38, 0);
modelBuilder.Entity<CATEGORIES>()
.Property(e => e.CATEGORY)
.IsUnicode(false);
modelBuilder.Entity<CATEGORIES>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<CONFIG>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<CONFIG>()
.Property(e => e.BUSINESSTABLENAME)
.IsUnicode(false);
modelBuilder.Entity<CORPORATEINFO>()
.Property(e => e.CODE)
.IsUnicode(false);
modelBuilder.Entity<CORPORATEINFO>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<CORPORATEINFO>()
.Property(e => e.ADDRESS)
.IsUnicode(false);
modelBuilder.Entity<CORPORATEINFO>()
.Property(e => e.PHONENUMBER)
.IsUnicode(false);
modelBuilder.Entity<CORPORATEINFO>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<COUNTY>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<COUNTY>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<ONLINEILLEGAL>()
.Property(e => e.IDENTITY)
.IsUnicode(false);
modelBuilder.Entity<ONLINEILLEGAL>()
.Property(e => e.JSON)
.IsUnicode(false);
modelBuilder.Entity<ONLINERECORD>()
.Property(e => e.IDENTITY)
.IsUnicode(false);
modelBuilder.Entity<ONLINERECORD>()
.Property(e => e.RECORD)
.IsUnicode(false);
modelBuilder.Entity<ONLINEUSER>()
.Property(e => e.IDENTITY)
.IsUnicode(false);
modelBuilder.Entity<ONLINEUSER>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<ONLINEUSER>()
.Property(e => e.PHONE)
.IsUnicode(false);
modelBuilder.Entity<ONLINEUSER>()
.Property(e => e.WECHAT)
.IsUnicode(false);
modelBuilder.Entity<ONLINEUSER>()
.Property(e => e.LOG)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.SEX)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.NATION)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.BORN)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.ADDRESS)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.POSTCODE)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.POSTADDRESS)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.MOBILE)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.TELEPHONE)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.EMAIL)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.IDNUM)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.FIRSTFINGER)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.SECONDFINGER)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.LEFTEYE)
.IsUnicode(false);
modelBuilder.Entity<POPULATION>()
.Property(e => e.RIGHTEYE)
.IsUnicode(false);
modelBuilder.Entity<STUDYHISTORYRECORD>()
.Property(e => e.IDENTITY)
.IsUnicode(false);
modelBuilder.Entity<STUDYHISTORYRECORD>()
.Property(e => e.NOTICESTATUS)
.IsUnicode(false);
modelBuilder.Entity<STUDYHISTORYRECORD>()
.Property(e => e.STUDYSTATUS)
.IsUnicode(false);
modelBuilder.Entity<STUDYHISTORYRECORD>()
.Property(e => e.STOPLICENSE)
.IsUnicode(false);
modelBuilder.Entity<STUDYHISTORYRECORD>()
.Property(e => e.ORDINAL)
.HasPrecision(38, 0);
modelBuilder.Entity<SYNCUSER>()
.Property(e => e.IDENTITY)
.IsUnicode(false);
modelBuilder.Entity<SYNCUSER>()
.Property(e => e.NOTICESTATUS)
.IsUnicode(false);
modelBuilder.Entity<SYNCUSER>()
.Property(e => e.STUDYSTATUS)
.IsUnicode(false);
modelBuilder.Entity<SYNCUSER>()
.Property(e => e.STOPLICENSE)
.IsUnicode(false);
modelBuilder.Entity<USERS>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<USERS>()
.Property(e => e.USERNAME)
.IsUnicode(false);
modelBuilder.Entity<USERS>()
.Property(e => e.PASSWORD)
.IsUnicode(false);
modelBuilder.Entity<USERS>()
.Property(e => e.LIMIT)
.IsUnicode(false);
modelBuilder.Entity<USERS>()
.Property(e => e.DEPARTMENT)
.IsUnicode(false);
modelBuilder.Entity<USERS>()
.Property(e => e.POST)
.IsUnicode(false);
modelBuilder.Entity<USERS>()
.Property(e => e.POLICENUM)
.IsUnicode(false);
modelBuilder.Entity<USERS>()
.Property(e => e.REALNAME)
.IsUnicode(false);
modelBuilder.Entity<USERS>()
.Property(e => e.PDA_TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<USERS>()
.Property(e => e.FIRSTFINGER)
.IsUnicode(false);
modelBuilder.Entity<USERS>()
.Property(e => e.SECONDFINGER)
.IsUnicode(false);
modelBuilder.Entity<USERS>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<USERS>()
.Property(e => e.AUTHORITYLEVEL)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.ID)
.HasPrecision(38, 0);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.TYPE)
.HasPrecision(38, 0);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.SERIAL_NUM)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.REJECT_REASON)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.PHONE_NUM)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.PROCESS_USER)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.FILE_RECV_USER)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.TRANSFER_STATUS)
.HasPrecision(38, 0);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.UPLOADER)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.COMPLETE_PAY_USER)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.ATTENTION)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.COUNTYCODE)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.POSTPHONE)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.POSTADDR)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.CHECK_FILE)
.HasPrecision(38, 0);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.CAR_NUM)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.TAX_TYPE)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.TAX_NUM)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.ORIGIN_TYPE)
.IsUnicode(false);
modelBuilder.Entity<ZHIFUBUSINESS>()
.Property(e => e.ORIGIN_NUM)
.IsUnicode(false);
modelBuilder.Entity<VITALLOG>()
.Property(e => e.USERNAME)
.IsUnicode(false);
modelBuilder.Entity<VITALLOG>()
.Property(e => e.KEYWORD)
.IsUnicode(false);
modelBuilder.Entity<VITALLOG>()
.Property(e => e.IP)
.IsUnicode(false);
modelBuilder.Entity<VITALLOG>()
.Property(e => e.OPERATION)
.IsUnicode(false);
}
}
}
| |
/*==========================================================================
* Project: Homebrewer's .NET Gadgeteer Temperature Controller
*
* File: TemperatureControlDataModel.cs
*
* Version: 1.0.0
*
* Type: C# Source Code
*
* Author: James L. Haynes
*
* Description: This the Model. It maintains the the current temperature
* and all system settings
*
* Revision History: 1.0.0: Initial Release
*
* Copyright: 2013, James L. Haynes
* 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 Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Touch;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using Gadgeteer.Modules.GHIElectronics;
namespace NETMFTemperatureController.Model
{
#region Enums
public enum TemperatureUnitsType
{
Celsius,
Fahrenheit
}
public enum TemperatureControlMode
{
modeOff,
modeCool,
modeHeat,
modeHold
}
public enum TemperatureControllerState
{
stateIdle,
stateCooling,
stateHeating
}
#endregion // Enums
public class TemperatureControlDataModel
{
#region Fields
public int IdleScreenTimeout = 10; // Seconds
public int StartupInterval = 3;
public int ControllerInterval = 2;
private Queue temperatureSamples = new Queue();
private int averageCount = 16;
private float sampleAccumulator;
#endregion // Fields
#region Properties
/// <summary>
/// The operation mode of the temperature controller
/// </summary>
public readonly string[] ControllerModeStringTable;
public TemperatureControlMode ControllerMode { get; set; }
/// <summary>
/// The current state of the temperature controller
/// </summary>
public readonly string[] CurrentStateStringTable;
public TemperatureControllerState CurrentState{get; set;}
/// <summary>
/// The currently selected temperature units, either Celsius or Fahrenheit
/// </summary>
private TemperatureUnitsType currentTempUnits;
public TemperatureUnitsType CurrentTempUnits
{
get { return currentTempUnits; }
set
{
if (currentTempUnits != value)
{
currentTempUnits = value;
switch (value)
{
case TemperatureUnitsType.Fahrenheit:
RestartAveraging();
AverageTemperature = ConvertCtoF(AverageTemperature);
TemperatureSetPoint = ConvertCtoF(TemperatureSetPoint);
TemperatureDegreeSymbol = Resources.GetString(Resources.StringResources.fahrenheitUnit);
break;
case TemperatureUnitsType.Celsius:
RestartAveraging();
AverageTemperature = ConvertFtoC(AverageTemperature);
TemperatureSetPoint = ConvertFtoC(TemperatureSetPoint);
TemperatureDegreeSymbol = Resources.GetString(Resources.StringResources.celsiusUnit);
break;
default:
throw new NotSupportedException("Invalid TemperatureUnitsType");
}
}
}
}
public string TemperatureDegreeSymbol { get; private set; }
public float AverageTemperature { get; private set; }
private int hysteresisValue;
public int HysteresisValue
{
get { return hysteresisValue; }
set
{
hysteresisValue = value;
TemperatureSetPointHigh = temperatureSetPoint + hysteresisValue;
TemperatureSetPointLow = temperatureSetPoint - hysteresisValue;
}
}
public float TemperatureSetPointHigh { get; private set; }
public float TemperatureSetPointLow { get; private set; }
private float temperatureSetPoint;
public float TemperatureSetPoint
{
get { return temperatureSetPoint; }
set
{
temperatureSetPoint = value;
TemperatureSetPointHigh = (temperatureSetPoint + hysteresisValue); // To implement hysteresis
TemperatureSetPointLow = (temperatureSetPoint - hysteresisValue);
}
}
#endregion // Properties
#region ctor
public TemperatureControlDataModel()
{
CurrentTempUnits = TemperatureUnitsType.Fahrenheit;
ControllerMode = TemperatureControlMode.modeOff;
CurrentState = TemperatureControllerState.stateIdle;
HysteresisValue = 1;
TemperatureSetPoint = 68;
ControllerModeStringTable = new string[sizeof(TemperatureControlMode)];
ControllerModeStringTable[(int)TemperatureControlMode.modeOff] = Resources.GetString(Resources.StringResources.offModeText);
ControllerModeStringTable[(int)TemperatureControlMode.modeCool] = Resources.GetString(Resources.StringResources.coolModeText);
ControllerModeStringTable[(int)TemperatureControlMode.modeHeat] = Resources.GetString(Resources.StringResources.heatModeText);
ControllerModeStringTable[(int)TemperatureControlMode.modeHold] = Resources.GetString(Resources.StringResources.holdModeText);
CurrentStateStringTable = new string[sizeof(TemperatureControllerState)];
CurrentStateStringTable[(int)TemperatureControllerState.stateIdle] = Resources.GetString(Resources.StringResources.idleStatusText);
CurrentStateStringTable[(int)TemperatureControllerState.stateCooling] = Resources.GetString(Resources.StringResources.coolStatusText);
CurrentStateStringTable[(int)TemperatureControllerState.stateHeating] = Resources.GetString(Resources.StringResources.heatStatusText);
}
#endregion
#region Methods
/// <summary>
/// Keep a running average of temperature samples
/// </summary>
/// <param name="sample"></param>
public void RecordTemperatureSample(float sample)
{
float currentTemperature = sample;
switch (currentTempUnits)
{
case TemperatureUnitsType.Celsius:
break;
case TemperatureUnitsType.Fahrenheit:
currentTemperature = ConvertCtoF(sample);
break;
default:
throw new NotSupportedException("Invalid TemperatureUnitsType");
}
sampleAccumulator += currentTemperature;
temperatureSamples.Enqueue(currentTemperature);
if (temperatureSamples.Count > averageCount)
{
sampleAccumulator -= (float)temperatureSamples.Dequeue();
}
AverageTemperature = sampleAccumulator / temperatureSamples.Count;
}
/// <summary>
/// Clears the queue and accumulator.
/// </summary>
public void RestartAveraging()
{
temperatureSamples.Clear();
sampleAccumulator = 0;
}
/// <summary>
/// This method toggles the temperature display between Celsius and Fahrenheit.
/// </summary>
public void ToggleUnits()
{
switch (CurrentTempUnits)
{
case TemperatureUnitsType.Celsius:
CurrentTempUnits = TemperatureUnitsType.Fahrenheit;
break;
case TemperatureUnitsType.Fahrenheit:
CurrentTempUnits = TemperatureUnitsType.Celsius;
break;
default:
throw new NotSupportedException("Invalid TemperatureUnitsType");
}
}
/// <summary>
/// Cycle down through operating modes
/// </summary>
public void OperatingModePrevious()
{
switch (ControllerMode)
{
case TemperatureControlMode.modeOff:
ControllerMode = TemperatureControlMode.modeHold;
break;
case TemperatureControlMode.modeHold:
ControllerMode = TemperatureControlMode.modeHeat;
break;
case TemperatureControlMode.modeHeat:
ControllerMode = TemperatureControlMode.modeCool;
break;
case TemperatureControlMode.modeCool:
ControllerMode = TemperatureControlMode.modeOff;
break;
default:
throw new NotSupportedException("Invalid TemperatureControlMode");
}
}
/// <summary>
/// Cycle up through operating modes
/// </summary>
public void OperatingModeNext()
{
switch (ControllerMode)
{
case TemperatureControlMode.modeOff:
ControllerMode = TemperatureControlMode.modeCool;
break;
case TemperatureControlMode.modeCool:
ControllerMode = TemperatureControlMode.modeHeat;
break;
case TemperatureControlMode.modeHeat:
ControllerMode = TemperatureControlMode.modeHold;
break;
case TemperatureControlMode.modeHold:
ControllerMode = TemperatureControlMode.modeOff;
break;
default:
throw new NotSupportedException("Invalid TemperatureControlMode");
}
}
/// <summary>
/// This method converts temperature in Celsius to Fahrenheit.
/// </summary>
/// <param name="celsius"></param>
/// <returns></returns>
public static float ConvertCtoF(float celsius)
{
return (((float)celsius * 9) / 5 + 32);
}
/// <summary>
/// This method converts temperature in Fahrenheit to Celsius.
/// </summary>
/// <param name="fahrenheit"></param>
/// <returns></returns>
public static float ConvertFtoC(float fahrenheit)
{
return ((((float)fahrenheit - 32) * 5) / 9);
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.CommandLineUtils;
using Lapis.CommandLineUtils.Models;
using Microsoft.Extensions.DependencyInjection;
using Lapis.CommandLineUtils.Converters;
using Lapis.CommandLineUtils.ResultHandlers;
using Lapis.CommandLineUtils.ExceptionHandlers;
namespace Lapis.CommandLineUtils
{
public static class CommandLineApplicationExtensions
{
public static CommandLineApplicationServiceProviderWrapper Command(this CommandLineApplication app, Type type)
{
return app.Command(type?.GetTypeInfo());
}
public static CommandLineApplicationServiceProviderWrapper Command(this CommandLineApplicationServiceProviderWrapper app, Type type)
{
return app.Command(type?.GetTypeInfo());
}
public static CommandLineApplicationServiceProviderWrapper Command(this CommandLineApplication app, TypeInfo typeInfo)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
if (typeInfo == null)
throw new ArgumentNullException(nameof(typeInfo));
return app
.ConfigureServices(_ => { })
.AddDefaultConverters()
.AddDefaultResultHandlers()
.AddDefaultExceptionHandlers()
.UseDefaultCommandBuilder()
.UseDefaultCommandBinder()
.BuildServices()
.Command(typeInfo);
}
public static CommandLineApplicationServiceProviderWrapper Command(this CommandLineApplication app, MethodInfo methodInfo)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
if (methodInfo == null)
throw new ArgumentNullException(nameof(methodInfo));
return app
.ConfigureServices(_ => { })
.AddDefaultConverters()
.AddDefaultResultHandlers()
.AddDefaultExceptionHandlers()
.UseDefaultCommandBuilder()
.UseDefaultCommandBinder()
.BuildServices()
.Command(methodInfo);
}
public static CommandLineApplicationServiceProviderWrapper Command(this CommandLineApplicationServiceProviderWrapper app, TypeInfo typeInfo)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
if (typeInfo == null)
throw new ArgumentNullException(nameof(typeInfo));
var modelBuilder = app.ServiceProvider.GetService<ICommandModelBuilder>();
var commandModel = modelBuilder.BuildCommand(typeInfo);
if (commandModel == null)
throw new NotSupportedException($"Type {typeInfo.Name} is not supported.");
var binder = app.ServiceProvider.GetService<ICommandBinder>();
binder.BindCommand(app.Application, commandModel);
return app;
}
public static CommandLineApplicationServiceProviderWrapper Command(this CommandLineApplicationServiceProviderWrapper app, MethodInfo methodInfo)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
if (methodInfo == null)
throw new ArgumentNullException(nameof(methodInfo));
var modelBuilder = app.ServiceProvider.GetService<ICommandModelBuilder>();
var commandModel = modelBuilder.BuildCommand(methodInfo);
if (commandModel == null)
throw new NotSupportedException($"Method {methodInfo.Name} is not supported.");
var binder = app.ServiceProvider.GetService<ICommandBinder>();
binder.BindCommand(app.Application, commandModel);
return app;
}
public static CommandLineApplicationServiceCollectionWrapper AddDefaultConverters(this CommandLineApplicationServiceCollectionWrapper app)
{
return app
.AddConverter<SystemConvertConverter>()
.AddConverter<TypeConverterConverter>()
.AddConverter<MethodConverter>()
.AddConverter<ConstrctorConverter>()
.AddConverter<EnumNameConverter>()
.AddConverter<CollectionConverter>();
}
public static CommandLineApplicationServiceCollectionWrapper AddConverter<T>(this CommandLineApplicationServiceCollectionWrapper app)
where T : class, IConverter
{
if (app == null)
throw new ArgumentNullException(nameof(app));
app.Services.AddScoped<T>();
return app;
}
public static CommandLineApplicationServiceCollectionWrapper AddDefaultResultHandlers(this CommandLineApplicationServiceCollectionWrapper app)
{
return app
.AddResultHandler<ConsoleOutResultHandler>();
}
public static CommandLineApplicationServiceCollectionWrapper AddResultHandler<T>(this CommandLineApplicationServiceCollectionWrapper app)
where T : class, IResultHandler
{
if (app == null)
throw new ArgumentNullException(nameof(app));
app.Services.AddScoped<T>();
return app;
}
public static CommandLineApplicationServiceCollectionWrapper AddDefaultExceptionHandlers(this CommandLineApplicationServiceCollectionWrapper app)
{
return app
.AddExceptionHandler<ConsoleErrorExceptionHandler>();
}
public static CommandLineApplicationServiceCollectionWrapper AddExceptionHandler<T>(this CommandLineApplicationServiceCollectionWrapper app)
where T : class, IExceptionHandler
{
if (app == null)
throw new ArgumentNullException(nameof(app));
app.Services.AddScoped<T>();
return app;
}
public static CommandLineApplicationServiceCollectionWrapper UseDefaultCommandBuilder(this CommandLineApplicationServiceCollectionWrapper app)
{
return app.UseCommandBuilder<CommandModelBuilder>();
}
public static CommandLineApplicationServiceCollectionWrapper UseCommandBuilder<T>(this CommandLineApplicationServiceCollectionWrapper app)
where T : class, ICommandModelBuilder
{
if (app == null)
throw new ArgumentNullException(nameof(app));
app.Services.AddScoped<ICommandModelBuilder, T>();
return app;
}
public static CommandLineApplicationServiceCollectionWrapper UseDefaultCommandBinder(this CommandLineApplicationServiceCollectionWrapper app)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
var types = app.Services.Select(d => d.ImplementationType);
app.Services.AddScoped<ICommandBinder, CommandBinder>(serviceProvider =>
new CommandBinder(serviceProvider,
types.Where(d => typeof(IConverter).IsAssignableFrom(d)).ToList(),
types.Where(d => typeof(IResultHandler).IsAssignableFrom(d)).ToList(),
types.Where(d => typeof(IExceptionHandler).IsAssignableFrom(d)).ToList()
)
);
return app;
}
public static CommandLineApplicationServiceCollectionWrapper UseCommandBinder<T>(this CommandLineApplicationServiceCollectionWrapper app)
where T : class, ICommandBinder
{
if (app == null)
throw new ArgumentNullException(nameof(app));
app.Services.AddSingleton<ICommandBinder, T>();
return app;
}
public static CommandLineApplicationServiceCollectionWrapper ConfigureServices(this CommandLineApplication app,
Action<IServiceCollection> serviceConfiguration)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
var services = new ServiceCollection();
serviceConfiguration?.Invoke(services);
return new CommandLineApplicationServiceCollectionWrapper(app, services);
}
public static CommandLineApplicationServiceCollectionWrapper ConfigureServices(this CommandLineApplicationServiceCollectionWrapper app,
Action<IServiceCollection> serviceConfiguration)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
var services = new ServiceCollection();
serviceConfiguration?.Invoke(services);
return app;
}
public static CommandLineApplicationServiceProviderWrapper BuildServices(this CommandLineApplicationServiceCollectionWrapper app)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
return new CommandLineApplicationServiceProviderWrapper(app.Application, app.Services.BuildServiceProvider());
}
public static CommandLineApplicationServiceCollectionWrapper ConfigureApplication(this CommandLineApplicationServiceCollectionWrapper app,
Action<CommandLineApplication> applicationConfiguration)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
applicationConfiguration?.Invoke(app.Application);
return app;
}
public static CommandLineApplicationServiceProviderWrapper ConfigureApplication(this CommandLineApplicationServiceProviderWrapper app,
Action<CommandLineApplication> applicationConfiguration)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
applicationConfiguration?.Invoke(app.Application);
return app;
}
}
public class CommandLineApplicationServiceCollectionWrapper
{
public CommandLineApplicationServiceCollectionWrapper(CommandLineApplication application, IServiceCollection services)
{
if (application == null)
throw new ArgumentNullException(nameof(application));
if (services == null)
throw new ArgumentNullException(nameof(services));
Application = application;
Services = services;
}
public CommandLineApplication Application { get; }
public IServiceCollection Services { get; }
}
public class CommandLineApplicationServiceProviderWrapper
{
public CommandLineApplicationServiceProviderWrapper(CommandLineApplication application, IServiceProvider serviceProvider)
{
if (application == null)
throw new ArgumentNullException(nameof(application));
if (serviceProvider == null)
throw new ArgumentNullException(nameof(serviceProvider));
Application = application;
ServiceProvider = serviceProvider;
}
public CommandLineApplication Application { get; }
public IServiceProvider ServiceProvider { get; }
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Management.TrustBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementTrustBrowserCertificateInfo))]
public partial class ManagementTrust : iControlInterface {
public ManagementTrust() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_authority_device
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
public void add_authority_device(
string address,
string username,
string password,
string device_object_name,
string browser_cert_serial_number,
string browser_cert_signature,
string browser_cert_sha1_fingerprint,
string browser_cert_md5_fingerprint
) {
this.Invoke("add_authority_device", new object [] {
address,
username,
password,
device_object_name,
browser_cert_serial_number,
browser_cert_signature,
browser_cert_sha1_fingerprint,
browser_cert_md5_fingerprint});
}
public System.IAsyncResult Beginadd_authority_device(string address,string username,string password,string device_object_name,string browser_cert_serial_number,string browser_cert_signature,string browser_cert_sha1_fingerprint,string browser_cert_md5_fingerprint, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_authority_device", new object[] {
address,
username,
password,
device_object_name,
browser_cert_serial_number,
browser_cert_signature,
browser_cert_sha1_fingerprint,
browser_cert_md5_fingerprint}, callback, asyncState);
}
public void Endadd_authority_device(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_authority_device_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
public void add_authority_device_v2(
string address,
long port,
string username,
string password,
string device_object_name,
string browser_cert_serial_number,
string browser_cert_signature,
string browser_cert_sha1_fingerprint,
string browser_cert_md5_fingerprint
) {
this.Invoke("add_authority_device_v2", new object [] {
address,
port,
username,
password,
device_object_name,
browser_cert_serial_number,
browser_cert_signature,
browser_cert_sha1_fingerprint,
browser_cert_md5_fingerprint});
}
public System.IAsyncResult Beginadd_authority_device_v2(string address,long port,string username,string password,string device_object_name,string browser_cert_serial_number,string browser_cert_signature,string browser_cert_sha1_fingerprint,string browser_cert_md5_fingerprint, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_authority_device_v2", new object[] {
address,
port,
username,
password,
device_object_name,
browser_cert_serial_number,
browser_cert_signature,
browser_cert_sha1_fingerprint,
browser_cert_md5_fingerprint}, callback, asyncState);
}
public void Endadd_authority_device_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_non_authority_device
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
public void add_non_authority_device(
string address,
string username,
string password,
string device_object_name,
string browser_cert_serial_number,
string browser_cert_signature,
string browser_cert_sha1_fingerprint,
string browser_cert_md5_fingerprint
) {
this.Invoke("add_non_authority_device", new object [] {
address,
username,
password,
device_object_name,
browser_cert_serial_number,
browser_cert_signature,
browser_cert_sha1_fingerprint,
browser_cert_md5_fingerprint});
}
public System.IAsyncResult Beginadd_non_authority_device(string address,string username,string password,string device_object_name,string browser_cert_serial_number,string browser_cert_signature,string browser_cert_sha1_fingerprint,string browser_cert_md5_fingerprint, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_non_authority_device", new object[] {
address,
username,
password,
device_object_name,
browser_cert_serial_number,
browser_cert_signature,
browser_cert_sha1_fingerprint,
browser_cert_md5_fingerprint}, callback, asyncState);
}
public void Endadd_non_authority_device(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_non_authority_device_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
public void add_non_authority_device_v2(
string address,
long port,
string username,
string password,
string device_object_name,
string browser_cert_serial_number,
string browser_cert_signature,
string browser_cert_sha1_fingerprint,
string browser_cert_md5_fingerprint
) {
this.Invoke("add_non_authority_device_v2", new object [] {
address,
port,
username,
password,
device_object_name,
browser_cert_serial_number,
browser_cert_signature,
browser_cert_sha1_fingerprint,
browser_cert_md5_fingerprint});
}
public System.IAsyncResult Beginadd_non_authority_device_v2(string address,long port,string username,string password,string device_object_name,string browser_cert_serial_number,string browser_cert_signature,string browser_cert_sha1_fingerprint,string browser_cert_md5_fingerprint, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_non_authority_device_v2", new object[] {
address,
port,
username,
password,
device_object_name,
browser_cert_serial_number,
browser_cert_signature,
browser_cert_sha1_fingerprint,
browser_cert_md5_fingerprint}, callback, asyncState);
}
public void Endadd_non_authority_device_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// generate_csr
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string generate_csr(
string device
) {
object [] results = this.Invoke("generate_csr", new object [] {
device});
return ((string)(results[0]));
}
public System.IAsyncResult Begingenerate_csr(string device, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("generate_csr", new object[] {
device}, callback, asyncState);
}
public string Endgenerate_csr(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// get_authority_device
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_authority_device(
) {
object [] results = this.Invoke("get_authority_device", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_authority_device(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_authority_device", new object[0], callback, asyncState);
}
public string [] Endget_authority_device(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_browser_certificate
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementTrustBrowserCertificateInfo get_browser_certificate(
string address
) {
object [] results = this.Invoke("get_browser_certificate", new object [] {
address});
return ((ManagementTrustBrowserCertificateInfo)(results[0]));
}
public System.IAsyncResult Beginget_browser_certificate(string address, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_browser_certificate", new object[] {
address}, callback, asyncState);
}
public ManagementTrustBrowserCertificateInfo Endget_browser_certificate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementTrustBrowserCertificateInfo)(results[0]));
}
//-----------------------------------------------------------------------
// get_ca_certificate
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_ca_certificate(
) {
object [] results = this.Invoke("get_ca_certificate", new object [0]);
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_ca_certificate(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ca_certificate", new object[0], callback, asyncState);
}
public string Endget_ca_certificate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// get_device_in_use
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool get_device_in_use(
) {
object [] results = this.Invoke("get_device_in_use", new object [0]);
return ((bool)(results[0]));
}
public System.IAsyncResult Beginget_device_in_use(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_device_in_use", new object[0], callback, asyncState);
}
public bool Endget_device_in_use(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool)(results[0]));
}
//-----------------------------------------------------------------------
// get_device_object_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_device_object_name(
string address,
string username,
string password,
string browser_cert_serial_number,
string browser_cert_signature,
string browser_cert_sha1_fingerprint,
string browser_cert_md5_fingerprint
) {
object [] results = this.Invoke("get_device_object_name", new object [] {
address,
username,
password,
browser_cert_serial_number,
browser_cert_signature,
browser_cert_sha1_fingerprint,
browser_cert_md5_fingerprint});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_device_object_name(string address,string username,string password,string browser_cert_serial_number,string browser_cert_signature,string browser_cert_sha1_fingerprint,string browser_cert_md5_fingerprint, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_device_object_name", new object[] {
address,
username,
password,
browser_cert_serial_number,
browser_cert_signature,
browser_cert_sha1_fingerprint,
browser_cert_md5_fingerprint}, callback, asyncState);
}
public string Endget_device_object_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// get_device_object_name_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_device_object_name_v2(
string address,
long port,
string username,
string password,
string browser_cert_serial_number,
string browser_cert_signature,
string browser_cert_sha1_fingerprint,
string browser_cert_md5_fingerprint
) {
object [] results = this.Invoke("get_device_object_name_v2", new object [] {
address,
port,
username,
password,
browser_cert_serial_number,
browser_cert_signature,
browser_cert_sha1_fingerprint,
browser_cert_md5_fingerprint});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_device_object_name_v2(string address,long port,string username,string password,string browser_cert_serial_number,string browser_cert_signature,string browser_cert_sha1_fingerprint,string browser_cert_md5_fingerprint, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_device_object_name_v2", new object[] {
address,
port,
username,
password,
browser_cert_serial_number,
browser_cert_signature,
browser_cert_sha1_fingerprint,
browser_cert_md5_fingerprint}, callback, asyncState);
}
public string Endget_device_object_name_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// get_guid
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_guid(
string [] domains
) {
object [] results = this.Invoke("get_guid", new object [] {
domains});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_guid(string [] domains, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_guid", new object[] {
domains}, callback, asyncState);
}
public string [] Endget_guid(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_non_authority_device
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_non_authority_device(
) {
object [] results = this.Invoke("get_non_authority_device", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_non_authority_device(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_non_authority_device", new object[0], callback, asyncState);
}
public string [] Endget_non_authority_device(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// install_authority_trust
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
public void install_authority_trust(
string device,
string identity_cert,
string ca_cert,
string ca_key,
string [] authorities,
string [] management_addresses,
string [] configsync_addresses
) {
this.Invoke("install_authority_trust", new object [] {
device,
identity_cert,
ca_cert,
ca_key,
authorities,
management_addresses,
configsync_addresses});
}
public System.IAsyncResult Begininstall_authority_trust(string device,string identity_cert,string ca_cert,string ca_key,string [] authorities,string [] management_addresses,string [] configsync_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("install_authority_trust", new object[] {
device,
identity_cert,
ca_cert,
ca_key,
authorities,
management_addresses,
configsync_addresses}, callback, asyncState);
}
public void Endinstall_authority_trust(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// install_device_trust
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
public void install_device_trust(
string device,
string identity_cert,
string ca_cert,
string [] authorities,
string [] management_addresses,
string [] configsync_addresses
) {
this.Invoke("install_device_trust", new object [] {
device,
identity_cert,
ca_cert,
authorities,
management_addresses,
configsync_addresses});
}
public System.IAsyncResult Begininstall_device_trust(string device,string identity_cert,string ca_cert,string [] authorities,string [] management_addresses,string [] configsync_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("install_device_trust", new object[] {
device,
identity_cert,
ca_cert,
authorities,
management_addresses,
configsync_addresses}, callback, asyncState);
}
public void Endinstall_device_trust(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_device
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
public void remove_device(
string [] devices
) {
this.Invoke("remove_device", new object [] {
devices});
}
public System.IAsyncResult Beginremove_device(string [] devices, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_device", new object[] {
devices}, callback, asyncState);
}
public void Endremove_device(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// reset_all
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Trust",
RequestNamespace="urn:iControl:Management/Trust", ResponseNamespace="urn:iControl:Management/Trust")]
public void reset_all(
string device_object_name,
bool keep_current_authority,
string authority_cert,
string authority_key
) {
this.Invoke("reset_all", new object [] {
device_object_name,
keep_current_authority,
authority_cert,
authority_key});
}
public System.IAsyncResult Beginreset_all(string device_object_name,bool keep_current_authority,string authority_cert,string authority_key, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_all", new object[] {
device_object_name,
keep_current_authority,
authority_cert,
authority_key}, callback, asyncState);
}
public void Endreset_all(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.Trust.BrowserCertificateInfo", Namespace = "urn:iControl")]
public partial class ManagementTrustBrowserCertificateInfo
{
private string subject_nameField;
public string subject_name
{
get { return this.subject_nameField; }
set { this.subject_nameField = value; }
}
private string serial_numberField;
public string serial_number
{
get { return this.serial_numberField; }
set { this.serial_numberField = value; }
}
private string expiration_dateField;
public string expiration_date
{
get { return this.expiration_dateField; }
set { this.expiration_dateField = value; }
}
private string signatureField;
public string signature
{
get { return this.signatureField; }
set { this.signatureField = value; }
}
private string sha1_fingerprintField;
public string sha1_fingerprint
{
get { return this.sha1_fingerprintField; }
set { this.sha1_fingerprintField = value; }
}
private string md5_fingerprintField;
public string md5_fingerprint
{
get { return this.md5_fingerprintField; }
set { this.md5_fingerprintField = value; }
}
};
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public class HttpClient : HttpMessageInvoker
{
#region Fields
private static readonly TimeSpan s_defaultTimeout = TimeSpan.FromSeconds(100);
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
private static readonly TimeSpan s_infiniteTimeout = Threading.Timeout.InfiniteTimeSpan;
private const HttpCompletionOption defaultCompletionOption = HttpCompletionOption.ResponseContentRead;
private volatile bool _operationStarted;
private volatile bool _disposed;
private CancellationTokenSource _pendingRequestsCts;
private HttpRequestHeaders _defaultRequestHeaders;
private Uri _baseAddress;
private TimeSpan _timeout;
private long _maxResponseContentBufferSize;
#endregion Fields
#region Properties
public HttpRequestHeaders DefaultRequestHeaders
{
get
{
if (_defaultRequestHeaders == null)
{
_defaultRequestHeaders = new HttpRequestHeaders();
}
return _defaultRequestHeaders;
}
}
public Uri BaseAddress
{
get { return _baseAddress; }
set
{
CheckBaseAddress(value, "value");
CheckDisposedOrStarted();
if (HttpEventSource.Log.IsEnabled()) HttpEventSource.UriBaseAddress(this, _baseAddress.ToString());
_baseAddress = value;
}
}
public TimeSpan Timeout
{
get { return _timeout; }
set
{
if (value != s_infiniteTimeout && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException("value");
}
CheckDisposedOrStarted();
_timeout = value;
}
}
public long MaxResponseContentBufferSize
{
get { return _maxResponseContentBufferSize; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException("value");
}
if (value > HttpContent.MaxBufferSize)
{
throw new ArgumentOutOfRangeException("value", value,
string.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize));
}
CheckDisposedOrStarted();
_maxResponseContentBufferSize = value;
}
}
#endregion Properties
#region Constructors
public HttpClient()
: this(new HttpClientHandler())
{
}
public HttpClient(HttpMessageHandler handler)
: this(handler, true)
{
}
public HttpClient(HttpMessageHandler handler, bool disposeHandler)
: base(handler, disposeHandler)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", handler);
_timeout = s_defaultTimeout;
_maxResponseContentBufferSize = HttpContent.MaxBufferSize;
_pendingRequestsCts = new CancellationTokenSource();
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
}
#endregion Constructors
#region Public Send
#region Simple Get Overloads
public Task<string> GetStringAsync(string requestUri)
{
return GetStringAsync(CreateUri(requestUri));
}
public Task<string> GetStringAsync(Uri requestUri)
{
return GetContentAsync(requestUri, HttpCompletionOption.ResponseContentRead, string.Empty,
content => content.ReadAsStringAsync());
}
public Task<byte[]> GetByteArrayAsync(string requestUri)
{
return GetByteArrayAsync(CreateUri(requestUri));
}
public Task<byte[]> GetByteArrayAsync(Uri requestUri)
{
return GetContentAsync(requestUri, HttpCompletionOption.ResponseContentRead, Array.Empty<byte>(),
content => content.ReadAsByteArrayAsync());
}
// Unbuffered by default
public Task<Stream> GetStreamAsync(string requestUri)
{
return GetStreamAsync(CreateUri(requestUri));
}
// Unbuffered by default
public Task<Stream> GetStreamAsync(Uri requestUri)
{
return GetContentAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, Stream.Null,
content => content.ReadAsStreamAsync());
}
private Task<T> GetContentAsync<T>(Uri requestUri, HttpCompletionOption completionOption, T defaultValue,
Func<HttpContent, Task<T>> readAs)
{
TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
GetAsync(requestUri, completionOption).ContinueWithStandard(requestTask =>
{
if (HandleRequestFaultsAndCancelation(requestTask, tcs))
{
return;
}
HttpResponseMessage response = requestTask.Result;
if (response.Content == null)
{
tcs.TrySetResult(defaultValue);
return;
}
try
{
readAs(response.Content).ContinueWithStandard(contentTask =>
{
if (!HttpUtilities.HandleFaultsAndCancelation(contentTask, tcs))
{
tcs.TrySetResult(contentTask.Result);
}
});
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
});
return tcs.Task;
}
#endregion Simple Get Overloads
#region REST Send Overloads
public Task<HttpResponseMessage> GetAsync(string requestUri)
{
return GetAsync(CreateUri(requestUri));
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri)
{
return GetAsync(requestUri, defaultCompletionOption);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption)
{
return GetAsync(CreateUri(requestUri), completionOption);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption)
{
return GetAsync(requestUri, completionOption, CancellationToken.None);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, CancellationToken cancellationToken)
{
return GetAsync(CreateUri(requestUri), cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, CancellationToken cancellationToken)
{
return GetAsync(requestUri, defaultCompletionOption, cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
return GetAsync(CreateUri(requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)
{
return PostAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content)
{
return PostAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PostAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content)
{
return PutAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content)
{
return PutAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PutAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> DeleteAsync(string requestUri)
{
return DeleteAsync(CreateUri(requestUri));
}
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri)
{
return DeleteAsync(requestUri, CancellationToken.None);
}
public Task<HttpResponseMessage> DeleteAsync(string requestUri, CancellationToken cancellationToken)
{
return DeleteAsync(CreateUri(requestUri), cancellationToken);
}
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri, CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri), cancellationToken);
}
#endregion REST Send Overloads
#region Advanced Send Overloads
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
{
return SendAsync(request, defaultCompletionOption, CancellationToken.None);
}
public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
return SendAsync(request, defaultCompletionOption, cancellationToken);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption)
{
return SendAsync(request, completionOption, CancellationToken.None);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
CheckDisposed();
CheckRequestMessage(request);
SetOperationStarted();
PrepareRequestMessage(request);
// PrepareRequestMessage will resolve the request address against the base address.
CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken,
_pendingRequestsCts.Token);
SetTimeout(linkedCts);
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
base.SendAsync(request, linkedCts.Token).ContinueWithStandard(task =>
{
try
{
// The request is completed. Dispose the request content.
DisposeRequestContent(request);
if (task.IsFaulted)
{
SetTaskFaulted(request, linkedCts, tcs, task.Exception.GetBaseException());
return;
}
if (task.IsCanceled)
{
SetTaskCanceled(request, linkedCts, tcs);
return;
}
HttpResponseMessage response = task.Result;
if (response == null)
{
SetTaskFaulted(request, linkedCts, tcs,
new InvalidOperationException(SR.net_http_handler_noresponse));
return;
}
// If we don't have a response content, just return the response message.
if ((response.Content == null) || (completionOption == HttpCompletionOption.ResponseHeadersRead))
{
SetTaskCompleted(request, linkedCts, tcs, response);
return;
}
Debug.Assert(completionOption == HttpCompletionOption.ResponseContentRead,
"Unknown completion option.");
// We have an assigned content. Start loading it into a buffer and return response message once
// the whole content is buffered.
StartContentBuffering(request, linkedCts, tcs, response);
}
catch (Exception e)
{
// Make sure we catch any exception, otherwise the task will catch it and throw in the finalizer.
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, "SendAsync", e);
tcs.TrySetException(e);
}
});
return tcs.Task;
}
public void CancelPendingRequests()
{
CheckDisposed();
if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, "CancelPendingRequests", "");
// With every request we link this cancellation token source.
CancellationTokenSource currentCts = Interlocked.Exchange(ref _pendingRequestsCts,
new CancellationTokenSource());
currentCts.Cancel();
currentCts.Dispose();
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, "CancelPendingRequests", "");
}
#endregion Advanced Send Overloads
#endregion Public Send
#region IDisposable Members
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
// Cancel all pending requests (if any). Note that we don't call CancelPendingRequests() but cancel
// the CTS directly. The reason is that CancelPendingRequests() would cancel the current CTS and create
// a new CTS. We don't want a new CTS in this case.
_pendingRequestsCts.Cancel();
_pendingRequestsCts.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region Private Helpers
private void DisposeRequestContent(HttpRequestMessage request)
{
Contract.Requires(request != null);
// When a request completes, HttpClient disposes the request content so the user doesn't have to. This also
// ensures that a HttpContent object is only sent once using HttpClient (similar to HttpRequestMessages
// that can also be sent only once).
HttpContent content = request.Content;
if (content != null)
{
content.Dispose();
}
}
private void StartContentBuffering(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource,
TaskCompletionSource<HttpResponseMessage> tcs, HttpResponseMessage response)
{
response.Content.LoadIntoBufferAsync(_maxResponseContentBufferSize).ContinueWithStandard(contentTask =>
{
try
{
// Make sure to dispose the CTS _before_ setting TaskCompletionSource. Otherwise the task will be
// completed and the user may dispose the user CTS on the continuation task leading to a race cond.
bool isCancellationRequested = cancellationTokenSource.Token.IsCancellationRequested;
// contentTask.Exception is always != null if IsFaulted is true. However, we need to access the
// Exception property, otherwise the Task considers the excpetion as "unhandled" and will throw in
// its finalizer.
if (contentTask.IsFaulted)
{
response.Dispose();
// If the cancellation token was canceled, we consider the exception to be caused by the
// cancellation (e.g. WebException when reading from canceled response stream).
if (isCancellationRequested && (contentTask.Exception.GetBaseException() is HttpRequestException))
{
SetTaskCanceled(request, cancellationTokenSource, tcs);
}
else
{
SetTaskFaulted(request, cancellationTokenSource, tcs, contentTask.Exception.GetBaseException());
}
return;
}
if (contentTask.IsCanceled)
{
response.Dispose();
SetTaskCanceled(request, cancellationTokenSource, tcs);
return;
}
// When buffering content is completed, set the Task as completed.
SetTaskCompleted(request, cancellationTokenSource, tcs, response);
}
catch (Exception e)
{
// Make sure we catch any exception, otherwise the task will catch it and throw in the finalizer.
response.Dispose();
tcs.TrySetException(e);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, "SendAsync", e);
}
});
}
private void SetOperationStarted()
{
// This method flags the HttpClient instances as "active". I.e. we executed at least one request (or are
// in the process of doing so). This information is used to lock-down all property setters. Once a
// Send/SendAsync operation started, no property can be changed.
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
}
private static void CheckRequestMessage(HttpRequestMessage request)
{
if (!request.MarkAsSent())
{
throw new InvalidOperationException(SR.net_http_client_request_already_sent);
}
}
private void PrepareRequestMessage(HttpRequestMessage request)
{
Uri requestUri = null;
if ((request.RequestUri == null) && (_baseAddress == null))
{
throw new InvalidOperationException(SR.net_http_client_invalid_requesturi);
}
if (request.RequestUri == null)
{
requestUri = _baseAddress;
}
else
{
// If the request Uri is an absolute Uri, just use it. Otherwise try to combine it with the base Uri.
if (!request.RequestUri.IsAbsoluteUri)
{
if (_baseAddress == null)
{
throw new InvalidOperationException(SR.net_http_client_invalid_requesturi);
}
else
{
requestUri = new Uri(_baseAddress, request.RequestUri);
}
}
}
// We modified the original request Uri. Assign the new Uri to the request message.
if (requestUri != null)
{
request.RequestUri = requestUri;
}
// Add default headers
if (_defaultRequestHeaders != null)
{
request.Headers.AddHeaders(_defaultRequestHeaders);
}
}
private static void CheckBaseAddress(Uri baseAddress, string parameterName)
{
if (baseAddress == null)
{
return; // It's OK to not have a base address specified.
}
if (!baseAddress.IsAbsoluteUri)
{
throw new ArgumentException(SR.net_http_client_absolute_baseaddress_required, parameterName);
}
if (!HttpUtilities.IsHttpUri(baseAddress))
{
throw new ArgumentException(SR.net_http_client_http_baseaddress_required, parameterName);
}
}
private void SetTaskFaulted(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource,
TaskCompletionSource<HttpResponseMessage> tcs, Exception e)
{
LogSendError(request, cancellationTokenSource, "SendAsync", e);
tcs.TrySetException(e);
cancellationTokenSource.Dispose();
}
private void SetTaskCanceled(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource,
TaskCompletionSource<HttpResponseMessage> tcs)
{
LogSendError(request, cancellationTokenSource, "SendAsync", null);
tcs.TrySetCanceled(cancellationTokenSource.Token);
cancellationTokenSource.Dispose();
}
private void SetTaskCompleted(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource,
TaskCompletionSource<HttpResponseMessage> tcs, HttpResponseMessage response)
{
if (HttpEventSource.Log.IsEnabled()) HttpEventSource.ClientSendCompleted(this, response, request);
tcs.TrySetResult(response);
cancellationTokenSource.Dispose();
}
private void SetTimeout(CancellationTokenSource cancellationTokenSource)
{
Contract.Requires(cancellationTokenSource != null);
if (_timeout != s_infiniteTimeout)
{
cancellationTokenSource.CancelAfter(_timeout);
}
}
private void LogSendError(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource,
string method, Exception e)
{
Contract.Requires(request != null);
if (cancellationTokenSource.IsCancellationRequested)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, this, method, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_client_send_canceled, LoggingHash.GetObjectLogHash(request)));
}
else
{
Debug.Assert(e != null);
if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, this, method, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_client_send_error, LoggingHash.GetObjectLogHash(request), e));
}
}
private Uri CreateUri(String uri)
{
if (string.IsNullOrEmpty(uri))
{
return null;
}
return new Uri(uri, UriKind.RelativeOrAbsolute);
}
// Returns true if the task was faulted or canceled and sets tcs accordingly. Non-success status codes count as
// faults in cases where the HttpResponseMessage object will not be returned to the developer.
private static bool HandleRequestFaultsAndCancelation<T>(Task<HttpResponseMessage> task,
TaskCompletionSource<T> tcs)
{
if (HttpUtilities.HandleFaultsAndCancelation(task, tcs))
{
return true;
}
HttpResponseMessage response = task.Result;
if (!response.IsSuccessStatusCode)
{
if (response.Content != null)
{
response.Content.Dispose();
}
tcs.TrySetException(new HttpRequestException(
string.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_message_not_success_statuscode, (int)response.StatusCode,
response.ReasonPhrase)));
return true;
}
return false;
}
#endregion Private Helpers
}
}
| |
namespace distribution_explorer
{
partial class DistexForm
{
/// <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(DistexForm));
this.modeLabel = new System.Windows.Forms.Label();
this.propertiesTab = new System.Windows.Forms.TabControl();
this.DistributionTab = new System.Windows.Forms.TabPage();
this.parameter3 = new System.Windows.Forms.TextBox();
this.parameter3Label = new System.Windows.Forms.Label();
this.distributionNameLabel = new System.Windows.Forms.Label();
this.parameter2Label = new System.Windows.Forms.Label();
this.parameter1Label = new System.Windows.Forms.Label();
this.parameter2 = new System.Windows.Forms.TextBox();
this.parameter1 = new System.Windows.Forms.TextBox();
this.distribution = new System.Windows.Forms.ComboBox();
this.PropertiesTabPage = new System.Windows.Forms.TabPage();
this.toLabel2 = new System.Windows.Forms.Label();
this.toLabel1 = new System.Windows.Forms.Label();
this.supportUpperLabel = new System.Windows.Forms.Label();
this.supportLowerLabel = new System.Windows.Forms.Label();
this.supportLabel = new System.Windows.Forms.Label();
this.rangeGreatestLabel = new System.Windows.Forms.Label();
this.rangeLowestLabel = new System.Windows.Forms.Label();
this.rangeLabel = new System.Windows.Forms.Label();
this.parameter3ValueLabel = new System.Windows.Forms.Label();
this.parameter2ValueLabel = new System.Windows.Forms.Label();
this.parameter1ValueLabel = new System.Windows.Forms.Label();
this.distributionValueLabel = new System.Windows.Forms.Label();
this.parameterLabel3 = new System.Windows.Forms.Label();
this.parameterLabel2 = new System.Windows.Forms.Label();
this.parameterLabel1 = new System.Windows.Forms.Label();
this.DistributionLabel = new System.Windows.Forms.Label();
this.coefficient_of_variation = new System.Windows.Forms.Label();
this.CVlabel = new System.Windows.Forms.Label();
this.kurtosis_excess = new System.Windows.Forms.Label();
this.kurtosisExcessLabel = new System.Windows.Forms.Label();
this.kurtosis = new System.Windows.Forms.Label();
this.kurtosisLabel = new System.Windows.Forms.Label();
this.skewness = new System.Windows.Forms.Label();
this.skewnessLabel = new System.Windows.Forms.Label();
this.median = new System.Windows.Forms.Label();
this.standard_deviation = new System.Windows.Forms.Label();
this.stddevLabel = new System.Windows.Forms.Label();
this.variance = new System.Windows.Forms.Label();
this.varianceLabel = new System.Windows.Forms.Label();
this.medianLabel = new System.Windows.Forms.Label();
this.mode = new System.Windows.Forms.Label();
this.mean = new System.Windows.Forms.Label();
this.meanLabel = new System.Windows.Forms.Label();
this.cdfTabPage = new System.Windows.Forms.TabPage();
this.CDF_data = new System.Windows.Forms.DataGridView();
this.RandomVariable = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.PDF = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.CDF = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.CCDF = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.QuantileTabPage = new System.Windows.Forms.TabPage();
this.QuantileData = new System.Windows.Forms.DataGridView();
this.RiskLevel = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.LowerCriticalValue = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.UpperCriticalValue = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.printPreviewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.customizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.propertiesTab.SuspendLayout();
this.DistributionTab.SuspendLayout();
this.PropertiesTabPage.SuspendLayout();
this.cdfTabPage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.CDF_data)).BeginInit();
this.QuantileTabPage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.QuantileData)).BeginInit();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// modeLabel
//
this.modeLabel.AutoSize = true;
this.modeLabel.Location = new System.Drawing.Point(45, 197);
this.modeLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.modeLabel.Name = "modeLabel";
this.modeLabel.Size = new System.Drawing.Size(44, 18);
this.modeLabel.TabIndex = 0;
this.modeLabel.Text = "Mode";
//
// propertiesTab
//
this.propertiesTab.AccessibleDescription = "Statistical distribution properties tab";
this.propertiesTab.AccessibleName = "Properties tab";
this.propertiesTab.Controls.Add(this.DistributionTab);
this.propertiesTab.Controls.Add(this.PropertiesTabPage);
this.propertiesTab.Controls.Add(this.cdfTabPage);
this.propertiesTab.Controls.Add(this.QuantileTabPage);
this.propertiesTab.Dock = System.Windows.Forms.DockStyle.Fill;
this.propertiesTab.Font = new System.Drawing.Font("Tahoma", 8.400001F);
this.propertiesTab.Location = new System.Drawing.Point(0, 26);
this.propertiesTab.Margin = new System.Windows.Forms.Padding(4);
this.propertiesTab.Name = "propertiesTab";
this.propertiesTab.SelectedIndex = 0;
this.propertiesTab.ShowToolTips = true;
this.propertiesTab.Size = new System.Drawing.Size(642, 585);
this.propertiesTab.TabIndex = 0;
this.propertiesTab.Deselecting += new System.Windows.Forms.TabControlCancelEventHandler(this.properties_tab_Deselecting);
this.propertiesTab.SelectedIndexChanged += new System.EventHandler(this.properties_tab_SelectedIndexChanged);
//
// DistributionTab
//
this.DistributionTab.AccessibleDescription = "Distribution Tab";
this.DistributionTab.AccessibleName = "DistributionTab";
this.DistributionTab.BackColor = System.Drawing.SystemColors.Control;
this.DistributionTab.Controls.Add(this.parameter3);
this.DistributionTab.Controls.Add(this.parameter3Label);
this.DistributionTab.Controls.Add(this.distributionNameLabel);
this.DistributionTab.Controls.Add(this.parameter2Label);
this.DistributionTab.Controls.Add(this.parameter1Label);
this.DistributionTab.Controls.Add(this.parameter2);
this.DistributionTab.Controls.Add(this.parameter1);
this.DistributionTab.Controls.Add(this.distribution);
this.DistributionTab.Location = new System.Drawing.Point(4, 26);
this.DistributionTab.Margin = new System.Windows.Forms.Padding(700, 4, 4, 4);
this.DistributionTab.Name = "DistributionTab";
this.DistributionTab.Padding = new System.Windows.Forms.Padding(4);
this.DistributionTab.Size = new System.Drawing.Size(634, 555);
this.DistributionTab.TabIndex = 0;
this.DistributionTab.Text = "Distribution";
this.DistributionTab.ToolTipText = "Choose the Statistical Distribution and provide parameter(s)";
this.DistributionTab.UseVisualStyleBackColor = true;
this.DistributionTab.Click += new System.EventHandler(this.tabPage1_Click);
//
// parameter3
//
this.parameter3.Location = new System.Drawing.Point(200, 232);
this.parameter3.Name = "parameter3";
this.parameter3.Size = new System.Drawing.Size(341, 24);
this.parameter3.TabIndex = 6;
//
// parameter3Label
//
this.parameter3Label.AutoSize = true;
this.parameter3Label.Location = new System.Drawing.Point(31, 232);
this.parameter3Label.Name = "parameter3Label";
this.parameter3Label.Size = new System.Drawing.Size(170, 18);
this.parameter3Label.TabIndex = 5;
this.parameter3Label.Text = "Parameter 3 (if required)";
this.parameter3Label.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.toolTip1.SetToolTip(this.parameter3Label, "Enter value of 3nd Parameter of the chosen distribution");
//
// distributionNameLabel
//
this.distributionNameLabel.AutoSize = true;
this.distributionNameLabel.Location = new System.Drawing.Point(31, 58);
this.distributionNameLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.distributionNameLabel.Name = "distributionNameLabel";
this.distributionNameLabel.Size = new System.Drawing.Size(78, 18);
this.distributionNameLabel.TabIndex = 2;
this.distributionNameLabel.Text = "Distribution";
this.distributionNameLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// parameter2Label
//
this.parameter2Label.AutoSize = true;
this.parameter2Label.Location = new System.Drawing.Point(28, 174);
this.parameter2Label.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.parameter2Label.Name = "parameter2Label";
this.parameter2Label.Size = new System.Drawing.Size(170, 18);
this.parameter2Label.TabIndex = 4;
this.parameter2Label.Text = "Parameter 2 (if required)";
this.parameter2Label.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.toolTip1.SetToolTip(this.parameter2Label, "Enter value of 2nd Parameter of the chosen distribution");
//
// parameter1Label
//
this.parameter1Label.AutoSize = true;
this.parameter1Label.ForeColor = System.Drawing.Color.Black;
this.parameter1Label.Location = new System.Drawing.Point(28, 116);
this.parameter1Label.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.parameter1Label.Name = "parameter1Label";
this.parameter1Label.Size = new System.Drawing.Size(89, 18);
this.parameter1Label.TabIndex = 3;
this.parameter1Label.Text = "Parameter 1";
this.parameter1Label.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// parameter2
//
this.parameter2.Location = new System.Drawing.Point(200, 171);
this.parameter2.Margin = new System.Windows.Forms.Padding(4);
this.parameter2.Name = "parameter2";
this.parameter2.Size = new System.Drawing.Size(341, 24);
this.parameter2.TabIndex = 2;
//
// parameter1
//
this.parameter1.Location = new System.Drawing.Point(200, 110);
this.parameter1.Margin = new System.Windows.Forms.Padding(4);
this.parameter1.Name = "parameter1";
this.parameter1.Size = new System.Drawing.Size(341, 24);
this.parameter1.TabIndex = 1;
//
// distribution
//
this.distribution.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.distribution.FormattingEnabled = true;
this.distribution.Location = new System.Drawing.Point(200, 51);
this.distribution.Margin = new System.Windows.Forms.Padding(4);
this.distribution.MaxDropDownItems = 20;
this.distribution.Name = "distribution";
this.distribution.Size = new System.Drawing.Size(341, 25);
this.distribution.TabIndex = 0;
this.distribution.SelectedIndexChanged += new System.EventHandler(this.distribution_SelectedIndexChanged);
//
// PropertiesTabPage
//
this.PropertiesTabPage.AccessibleDescription = "Show properties of distribution ";
this.PropertiesTabPage.AccessibleName = "PropertiesTabPage";
this.PropertiesTabPage.AccessibleRole = System.Windows.Forms.AccessibleRole.None;
this.PropertiesTabPage.BackColor = System.Drawing.SystemColors.Control;
this.PropertiesTabPage.Controls.Add(this.toLabel2);
this.PropertiesTabPage.Controls.Add(this.toLabel1);
this.PropertiesTabPage.Controls.Add(this.supportUpperLabel);
this.PropertiesTabPage.Controls.Add(this.supportLowerLabel);
this.PropertiesTabPage.Controls.Add(this.supportLabel);
this.PropertiesTabPage.Controls.Add(this.rangeGreatestLabel);
this.PropertiesTabPage.Controls.Add(this.rangeLowestLabel);
this.PropertiesTabPage.Controls.Add(this.rangeLabel);
this.PropertiesTabPage.Controls.Add(this.parameter3ValueLabel);
this.PropertiesTabPage.Controls.Add(this.parameter2ValueLabel);
this.PropertiesTabPage.Controls.Add(this.parameter1ValueLabel);
this.PropertiesTabPage.Controls.Add(this.distributionValueLabel);
this.PropertiesTabPage.Controls.Add(this.parameterLabel3);
this.PropertiesTabPage.Controls.Add(this.parameterLabel2);
this.PropertiesTabPage.Controls.Add(this.parameterLabel1);
this.PropertiesTabPage.Controls.Add(this.DistributionLabel);
this.PropertiesTabPage.Controls.Add(this.coefficient_of_variation);
this.PropertiesTabPage.Controls.Add(this.CVlabel);
this.PropertiesTabPage.Controls.Add(this.kurtosis_excess);
this.PropertiesTabPage.Controls.Add(this.kurtosisExcessLabel);
this.PropertiesTabPage.Controls.Add(this.kurtosis);
this.PropertiesTabPage.Controls.Add(this.kurtosisLabel);
this.PropertiesTabPage.Controls.Add(this.skewness);
this.PropertiesTabPage.Controls.Add(this.skewnessLabel);
this.PropertiesTabPage.Controls.Add(this.median);
this.PropertiesTabPage.Controls.Add(this.standard_deviation);
this.PropertiesTabPage.Controls.Add(this.stddevLabel);
this.PropertiesTabPage.Controls.Add(this.variance);
this.PropertiesTabPage.Controls.Add(this.varianceLabel);
this.PropertiesTabPage.Controls.Add(this.medianLabel);
this.PropertiesTabPage.Controls.Add(this.mode);
this.PropertiesTabPage.Controls.Add(this.modeLabel);
this.PropertiesTabPage.Controls.Add(this.mean);
this.PropertiesTabPage.Controls.Add(this.meanLabel);
this.PropertiesTabPage.ForeColor = System.Drawing.SystemColors.WindowText;
this.PropertiesTabPage.Location = new System.Drawing.Point(4, 26);
this.PropertiesTabPage.Margin = new System.Windows.Forms.Padding(4);
this.PropertiesTabPage.Name = "PropertiesTabPage";
this.PropertiesTabPage.Padding = new System.Windows.Forms.Padding(4);
this.PropertiesTabPage.Size = new System.Drawing.Size(634, 555);
this.PropertiesTabPage.TabIndex = 1;
this.PropertiesTabPage.Text = "Properties";
this.PropertiesTabPage.ToolTipText = "Shows properties of chosen distribution.";
this.PropertiesTabPage.UseVisualStyleBackColor = true;
this.PropertiesTabPage.Enter += new System.EventHandler(this.tabPage2_Enter);
//
// toLabel2
//
this.toLabel2.AutoSize = true;
this.toLabel2.Location = new System.Drawing.Point(384, 483);
this.toLabel2.Name = "toLabel2";
this.toLabel2.Size = new System.Drawing.Size(21, 18);
this.toLabel2.TabIndex = 25;
this.toLabel2.Text = "to";
//
// toLabel1
//
this.toLabel1.AutoSize = true;
this.toLabel1.Location = new System.Drawing.Point(384, 449);
this.toLabel1.Name = "toLabel1";
this.toLabel1.Size = new System.Drawing.Size(21, 18);
this.toLabel1.TabIndex = 24;
this.toLabel1.Text = "to";
//
// supportUpperLabel
//
this.supportUpperLabel.AutoSize = true;
this.supportUpperLabel.Location = new System.Drawing.Point(411, 483);
this.supportUpperLabel.Name = "supportUpperLabel";
this.supportUpperLabel.Size = new System.Drawing.Size(131, 18);
this.supportUpperLabel.TabIndex = 23;
this.supportUpperLabel.Text = "supportUpperValue";
this.toolTip1.SetToolTip(this.supportUpperLabel, "PDF and CDF are unity for x argument values greater than this value.");
//
// supportLowerLabel
//
this.supportLowerLabel.AutoSize = true;
this.supportLowerLabel.Location = new System.Drawing.Point(207, 483);
this.supportLowerLabel.Name = "supportLowerLabel";
this.supportLowerLabel.Size = new System.Drawing.Size(130, 18);
this.supportLowerLabel.TabIndex = 22;
this.supportLowerLabel.Text = "supportLowerValue";
this.toolTip1.SetToolTip(this.supportLowerLabel, "PDF and CDF are zero for values of argument X less than this value.");
//
// supportLabel
//
this.supportLabel.AutoSize = true;
this.supportLabel.Location = new System.Drawing.Point(45, 483);
this.supportLabel.Name = "supportLabel";
this.supportLabel.Size = new System.Drawing.Size(74, 18);
this.supportLabel.TabIndex = 21;
this.supportLabel.Text = "Supported";
this.toolTip1.SetToolTip(this.supportLabel, "Range over which pdf is >0 but not yet =1");
//
// rangeGreatestLabel
//
this.rangeGreatestLabel.AutoSize = true;
this.rangeGreatestLabel.Location = new System.Drawing.Point(411, 449);
this.rangeGreatestLabel.Name = "rangeGreatestLabel";
this.rangeGreatestLabel.Size = new System.Drawing.Size(136, 18);
this.rangeGreatestLabel.TabIndex = 20;
this.rangeGreatestLabel.Text = "rangeGreatestValue";
this.toolTip1.SetToolTip(this.rangeGreatestLabel, "Greatest argument X for calculating PDF and CDF.");
//
// rangeLowestLabel
//
this.rangeLowestLabel.AllowDrop = true;
this.rangeLowestLabel.AutoSize = true;
this.rangeLowestLabel.Location = new System.Drawing.Point(207, 449);
this.rangeLowestLabel.Name = "rangeLowestLabel";
this.rangeLowestLabel.Size = new System.Drawing.Size(125, 18);
this.rangeLowestLabel.TabIndex = 19;
this.rangeLowestLabel.Text = "rangeLowestValue";
this.toolTip1.SetToolTip(this.rangeLowestLabel, "Lowest argument X for calculating PDF and CDF.");
//
// rangeLabel
//
this.rangeLabel.AutoSize = true;
this.rangeLabel.Location = new System.Drawing.Point(45, 449);
this.rangeLabel.Name = "rangeLabel";
this.rangeLabel.Size = new System.Drawing.Size(49, 18);
this.rangeLabel.TabIndex = 18;
this.rangeLabel.Text = "Range";
this.toolTip1.SetToolTip(this.rangeLabel, "Lowest and greatest possible value of x argument for PDF & CDF.");
//
// parameter3ValueLabel
//
this.parameter3ValueLabel.AutoSize = true;
this.parameter3ValueLabel.Location = new System.Drawing.Point(204, 118);
this.parameter3ValueLabel.Name = "parameter3ValueLabel";
this.parameter3ValueLabel.Size = new System.Drawing.Size(128, 18);
this.parameter3ValueLabel.TabIndex = 17;
this.parameter3ValueLabel.Text = "parameter 3 value";
this.toolTip1.SetToolTip(this.parameter3ValueLabel, "Show 3rd parameter provided (if any).");
//
// parameter2ValueLabel
//
this.parameter2ValueLabel.AutoSize = true;
this.parameter2ValueLabel.Location = new System.Drawing.Point(204, 87);
this.parameter2ValueLabel.Name = "parameter2ValueLabel";
this.parameter2ValueLabel.Size = new System.Drawing.Size(128, 18);
this.parameter2ValueLabel.TabIndex = 16;
this.parameter2ValueLabel.Text = "parameter 2 value";
this.toolTip1.SetToolTip(this.parameter2ValueLabel, "Show 2nd parameter provided (if any).");
//
// parameter1ValueLabel
//
this.parameter1ValueLabel.AutoSize = true;
this.parameter1ValueLabel.Location = new System.Drawing.Point(204, 54);
this.parameter1ValueLabel.Name = "parameter1ValueLabel";
this.parameter1ValueLabel.Size = new System.Drawing.Size(128, 18);
this.parameter1ValueLabel.TabIndex = 15;
this.parameter1ValueLabel.Text = "parameter 1 value";
this.toolTip1.SetToolTip(this.parameter1ValueLabel, "Show 1st parameter provided.");
//
// distributionValueLabel
//
this.distributionValueLabel.AutoSize = true;
this.distributionValueLabel.Location = new System.Drawing.Point(204, 24);
this.distributionValueLabel.Name = "distributionValueLabel";
this.distributionValueLabel.Size = new System.Drawing.Size(118, 18);
this.distributionValueLabel.TabIndex = 14;
this.distributionValueLabel.Text = "distribution name";
this.toolTip1.SetToolTip(this.distributionValueLabel, "Show name of chosen distribution");
//
// parameterLabel3
//
this.parameterLabel3.AutoSize = true;
this.parameterLabel3.Location = new System.Drawing.Point(45, 118);
this.parameterLabel3.Name = "parameterLabel3";
this.parameterLabel3.Size = new System.Drawing.Size(142, 18);
this.parameterLabel3.TabIndex = 13;
this.parameterLabel3.Text = "Parameter 3 (if any)";
//
// parameterLabel2
//
this.parameterLabel2.AutoSize = true;
this.parameterLabel2.Location = new System.Drawing.Point(45, 87);
this.parameterLabel2.Name = "parameterLabel2";
this.parameterLabel2.Size = new System.Drawing.Size(142, 18);
this.parameterLabel2.TabIndex = 12;
this.parameterLabel2.Text = "Parameter 2 (if any)";
//
// parameterLabel1
//
this.parameterLabel1.AutoSize = true;
this.parameterLabel1.Location = new System.Drawing.Point(45, 54);
this.parameterLabel1.Name = "parameterLabel1";
this.parameterLabel1.Size = new System.Drawing.Size(89, 18);
this.parameterLabel1.TabIndex = 11;
this.parameterLabel1.Text = "Parameter 1";
//
// DistributionLabel
//
this.DistributionLabel.AutoSize = true;
this.DistributionLabel.Location = new System.Drawing.Point(45, 24);
this.DistributionLabel.Name = "DistributionLabel";
this.DistributionLabel.Size = new System.Drawing.Size(78, 18);
this.DistributionLabel.TabIndex = 10;
this.DistributionLabel.Text = "Distribution";
//
// coefficient_of_variation
//
this.coefficient_of_variation.AutoSize = true;
this.coefficient_of_variation.Location = new System.Drawing.Point(204, 318);
this.coefficient_of_variation.Name = "coefficient_of_variation";
this.coefficient_of_variation.Size = new System.Drawing.Size(65, 18);
this.coefficient_of_variation.TabIndex = 9;
this.coefficient_of_variation.Text = "CV value";
//
// CVlabel
//
this.CVlabel.AutoSize = true;
this.CVlabel.Location = new System.Drawing.Point(45, 318);
this.CVlabel.Name = "CVlabel";
this.CVlabel.Size = new System.Drawing.Size(152, 18);
this.CVlabel.TabIndex = 8;
this.CVlabel.Text = "Coefficient of variation";
this.toolTip1.SetToolTip(this.CVlabel, "or relative standard deviation that is standard deviation/mean");
//
// kurtosis_excess
//
this.kurtosis_excess.AutoSize = true;
this.kurtosis_excess.Location = new System.Drawing.Point(204, 414);
this.kurtosis_excess.Name = "kurtosis_excess";
this.kurtosis_excess.Size = new System.Drawing.Size(146, 18);
this.kurtosis_excess.TabIndex = 7;
this.kurtosis_excess.Text = "kurtosis excess value";
//
// kurtosisExcessLabel
//
this.kurtosisExcessLabel.AutoSize = true;
this.kurtosisExcessLabel.Location = new System.Drawing.Point(45, 414);
this.kurtosisExcessLabel.Name = "kurtosisExcessLabel";
this.kurtosisExcessLabel.Size = new System.Drawing.Size(109, 18);
this.kurtosisExcessLabel.TabIndex = 6;
this.kurtosisExcessLabel.Text = "Kurtosis excess";
//
// kurtosis
//
this.kurtosis.AutoSize = true;
this.kurtosis.Location = new System.Drawing.Point(204, 383);
this.kurtosis.Name = "kurtosis";
this.kurtosis.Size = new System.Drawing.Size(96, 18);
this.kurtosis.TabIndex = 5;
this.kurtosis.Text = "kurtosis value";
//
// kurtosisLabel
//
this.kurtosisLabel.AutoSize = true;
this.kurtosisLabel.Location = new System.Drawing.Point(45, 383);
this.kurtosisLabel.Name = "kurtosisLabel";
this.kurtosisLabel.Size = new System.Drawing.Size(59, 18);
this.kurtosisLabel.TabIndex = 4;
this.kurtosisLabel.Text = "Kurtosis";
//
// skewness
//
this.skewness.AutoSize = true;
this.skewness.Location = new System.Drawing.Point(204, 351);
this.skewness.Name = "skewness";
this.skewness.Size = new System.Drawing.Size(109, 18);
this.skewness.TabIndex = 3;
this.skewness.Text = "skewness value";
//
// skewnessLabel
//
this.skewnessLabel.AutoSize = true;
this.skewnessLabel.Location = new System.Drawing.Point(45, 351);
this.skewnessLabel.Name = "skewnessLabel";
this.skewnessLabel.Size = new System.Drawing.Size(71, 18);
this.skewnessLabel.TabIndex = 0;
this.skewnessLabel.Text = "Skewness";
//
// median
//
this.median.AutoSize = true;
this.median.Location = new System.Drawing.Point(204, 228);
this.median.Name = "median";
this.median.Size = new System.Drawing.Size(94, 18);
this.median.TabIndex = 1;
this.median.Text = "median value";
//
// standard_deviation
//
this.standard_deviation.AutoSize = true;
this.standard_deviation.Location = new System.Drawing.Point(204, 286);
this.standard_deviation.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.standard_deviation.Name = "standard_deviation";
this.standard_deviation.Size = new System.Drawing.Size(94, 18);
this.standard_deviation.TabIndex = 0;
this.standard_deviation.Text = "StdDev value";
//
// stddevLabel
//
this.stddevLabel.AutoSize = true;
this.stddevLabel.Location = new System.Drawing.Point(45, 286);
this.stddevLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.stddevLabel.Name = "stddevLabel";
this.stddevLabel.Size = new System.Drawing.Size(130, 18);
this.stddevLabel.TabIndex = 0;
this.stddevLabel.Text = "Standard Deviation";
this.toolTip1.SetToolTip(this.stddevLabel, "sqrt(");
//
// variance
//
this.variance.AutoSize = true;
this.variance.Location = new System.Drawing.Point(204, 257);
this.variance.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.variance.Name = "variance";
this.variance.Size = new System.Drawing.Size(101, 18);
this.variance.TabIndex = 0;
this.variance.Text = "variance value";
//
// varianceLabel
//
this.varianceLabel.AutoSize = true;
this.varianceLabel.Location = new System.Drawing.Point(45, 257);
this.varianceLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.varianceLabel.Name = "varianceLabel";
this.varianceLabel.Size = new System.Drawing.Size(63, 18);
this.varianceLabel.TabIndex = 0;
this.varianceLabel.Text = "Variance";
this.toolTip1.SetToolTip(this.varianceLabel, "standard deviation squared");
//
// medianLabel
//
this.medianLabel.AutoSize = true;
this.medianLabel.Location = new System.Drawing.Point(45, 228);
this.medianLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.medianLabel.Name = "medianLabel";
this.medianLabel.Size = new System.Drawing.Size(54, 18);
this.medianLabel.TabIndex = 0;
this.medianLabel.Text = "Median";
this.toolTip1.SetToolTip(this.medianLabel, "media is quantile(0.5)");
//
// mode
//
this.mode.AutoSize = true;
this.mode.Location = new System.Drawing.Point(204, 197);
this.mode.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.mode.Name = "mode";
this.mode.Size = new System.Drawing.Size(84, 18);
this.mode.TabIndex = 0;
this.mode.Text = "mode value";
//
// mean
//
this.mean.AutoSize = true;
this.mean.Location = new System.Drawing.Point(204, 169);
this.mean.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.mean.Name = "mean";
this.mean.Size = new System.Drawing.Size(84, 18);
this.mean.TabIndex = 0;
this.mean.Text = "mean value";
//
// meanLabel
//
this.meanLabel.AutoSize = true;
this.meanLabel.Location = new System.Drawing.Point(45, 169);
this.meanLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.meanLabel.Name = "meanLabel";
this.meanLabel.Size = new System.Drawing.Size(44, 18);
this.meanLabel.TabIndex = 0;
this.meanLabel.Text = "Mean";
//
// cdfTabPage
//
this.cdfTabPage.Controls.Add(this.CDF_data);
this.cdfTabPage.Location = new System.Drawing.Point(4, 26);
this.cdfTabPage.Margin = new System.Windows.Forms.Padding(4);
this.cdfTabPage.Name = "cdfTabPage";
this.cdfTabPage.Padding = new System.Windows.Forms.Padding(4);
this.cdfTabPage.Size = new System.Drawing.Size(634, 555);
this.cdfTabPage.TabIndex = 2;
this.cdfTabPage.Text = "PDF and CDF";
this.cdfTabPage.ToolTipText = "Probability Density and Cumulative Distribution Function (and complement) for ran" +
"dom variate x";
this.cdfTabPage.UseVisualStyleBackColor = true;
//
// CDF_data
//
this.CDF_data.AccessibleDescription = "PDF, CDF & complement Data Page";
this.CDF_data.AccessibleName = "CDF Tab";
this.CDF_data.AccessibleRole = System.Windows.Forms.AccessibleRole.PageTab;
this.CDF_data.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.CDF_data.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.RandomVariable,
this.PDF,
this.CDF,
this.CCDF});
this.CDF_data.Dock = System.Windows.Forms.DockStyle.Fill;
this.CDF_data.Location = new System.Drawing.Point(4, 4);
this.CDF_data.Margin = new System.Windows.Forms.Padding(4);
this.CDF_data.Name = "CDF_data";
this.CDF_data.RowTemplate.Height = 24;
this.CDF_data.Size = new System.Drawing.Size(626, 547);
this.CDF_data.TabIndex = 0;
this.CDF_data.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellEndEdit);
this.CDF_data.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.CDF_data_CellContentClick);
//
// RandomVariable
//
this.RandomVariable.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.RandomVariable.HeaderText = "Random Variable";
this.RandomVariable.Name = "RandomVariable";
//
// PDF
//
this.PDF.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.PDF.HeaderText = "PDF";
this.PDF.Name = "PDF";
this.PDF.ReadOnly = true;
//
// CDF
//
this.CDF.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.CDF.HeaderText = "CDF";
this.CDF.Name = "CDF";
this.CDF.ReadOnly = true;
//
// CCDF
//
this.CCDF.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.CCDF.HeaderText = "1-CDF";
this.CCDF.Name = "CCDF";
this.CCDF.ReadOnly = true;
//
// QuantileTabPage
//
this.QuantileTabPage.Controls.Add(this.QuantileData);
this.QuantileTabPage.Location = new System.Drawing.Point(4, 26);
this.QuantileTabPage.Margin = new System.Windows.Forms.Padding(4);
this.QuantileTabPage.Name = "QuantileTabPage";
this.QuantileTabPage.Padding = new System.Windows.Forms.Padding(4);
this.QuantileTabPage.Size = new System.Drawing.Size(634, 555);
this.QuantileTabPage.TabIndex = 3;
this.QuantileTabPage.Text = "Critical Values";
this.QuantileTabPage.ToolTipText = "Critical values (quantiles or percentiles of probability 1 - alpha)";
this.QuantileTabPage.UseVisualStyleBackColor = true;
this.QuantileTabPage.Enter += new System.EventHandler(this.QuantileTab_Enter);
//
// QuantileData
//
this.QuantileData.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.QuantileData.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.RiskLevel,
this.LowerCriticalValue,
this.UpperCriticalValue});
this.QuantileData.Dock = System.Windows.Forms.DockStyle.Fill;
this.QuantileData.Location = new System.Drawing.Point(4, 4);
this.QuantileData.Margin = new System.Windows.Forms.Padding(4);
this.QuantileData.Name = "QuantileData";
this.QuantileData.RowTemplate.Height = 24;
this.QuantileData.Size = new System.Drawing.Size(626, 547);
this.QuantileData.TabIndex = 0;
this.QuantileData.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.QuantileData_CellEndEdit);
//
// RiskLevel
//
this.RiskLevel.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.RiskLevel.HeaderText = "Risk Level (alpha)";
this.RiskLevel.Name = "RiskLevel";
//
// LowerCriticalValue
//
this.LowerCriticalValue.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.LowerCriticalValue.HeaderText = "Lower Critical Value";
this.LowerCriticalValue.Name = "LowerCriticalValue";
this.LowerCriticalValue.ReadOnly = true;
//
// UpperCriticalValue
//
this.UpperCriticalValue.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.UpperCriticalValue.HeaderText = "Upper Critical Value";
this.UpperCriticalValue.Name = "UpperCriticalValue";
this.UpperCriticalValue.ReadOnly = true;
//
// menuStrip1
//
this.menuStrip1.BackColor = System.Drawing.SystemColors.Control;
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(642, 26);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripMenuItem,
this.openToolStripMenuItem,
this.toolStripSeparator,
this.saveToolStripMenuItem,
this.toolStripSeparator1,
this.printToolStripMenuItem,
this.printPreviewToolStripMenuItem,
this.toolStripSeparator2,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(40, 22);
this.fileToolStripMenuItem.Text = "&File";
//
// newToolStripMenuItem
//
this.newToolStripMenuItem.Enabled = false;
this.newToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripMenuItem.Image")));
this.newToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.newToolStripMenuItem.Name = "newToolStripMenuItem";
this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.newToolStripMenuItem.Size = new System.Drawing.Size(177, 22);
this.newToolStripMenuItem.Text = "&New";
this.newToolStripMenuItem.ToolTipText = "New is not yet implemented. Enter data into dialog boxes.";
this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click);
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Enabled = false;
this.openToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripMenuItem.Image")));
this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.openToolStripMenuItem.Size = new System.Drawing.Size(177, 22);
this.openToolStripMenuItem.Text = "&Open";
this.openToolStripMenuItem.ToolTipText = "Open is not yet implemented. Enter data into dialog boxes.";
this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click);
//
// toolStripSeparator
//
this.toolStripSeparator.Name = "toolStripSeparator";
this.toolStripSeparator.Size = new System.Drawing.Size(174, 6);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image")));
this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.saveToolStripMenuItem.Size = new System.Drawing.Size(177, 22);
this.saveToolStripMenuItem.Text = "&Save";
this.saveToolStripMenuItem.ToolTipText = "Save all values, input and output, to a file.";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(174, 6);
//
// printToolStripMenuItem
//
this.printToolStripMenuItem.Enabled = false;
this.printToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripMenuItem.Image")));
this.printToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.printToolStripMenuItem.Name = "printToolStripMenuItem";
this.printToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P)));
this.printToolStripMenuItem.Size = new System.Drawing.Size(177, 22);
this.printToolStripMenuItem.Text = "&Print";
this.printToolStripMenuItem.ToolTipText = "Printing not yet available. Output to a file and print that instead.";
this.printToolStripMenuItem.Click += new System.EventHandler(this.printToolStripMenuItem_Click);
//
// printPreviewToolStripMenuItem
//
this.printPreviewToolStripMenuItem.Enabled = false;
this.printPreviewToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printPreviewToolStripMenuItem.Image")));
this.printPreviewToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.printPreviewToolStripMenuItem.Name = "printPreviewToolStripMenuItem";
this.printPreviewToolStripMenuItem.Size = new System.Drawing.Size(177, 22);
this.printPreviewToolStripMenuItem.Text = "Print Pre&view";
this.printPreviewToolStripMenuItem.ToolTipText = "Printing not yet available. Output to a file and print that instead.";
this.printPreviewToolStripMenuItem.Visible = false;
this.printPreviewToolStripMenuItem.Click += new System.EventHandler(this.printPreviewToolStripMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(174, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.AutoToolTip = true;
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(177, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.redoToolStripMenuItem,
this.toolStripSeparator3,
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.toolStripSeparator4,
this.selectAllToolStripMenuItem});
this.editToolStripMenuItem.Enabled = false;
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(43, 22);
this.editToolStripMenuItem.Text = "&Edit";
this.editToolStripMenuItem.Visible = false;
//
// undoToolStripMenuItem
//
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z)));
this.undoToolStripMenuItem.Size = new System.Drawing.Size(176, 22);
this.undoToolStripMenuItem.Text = "&Undo";
//
// redoToolStripMenuItem
//
this.redoToolStripMenuItem.Name = "redoToolStripMenuItem";
this.redoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Y)));
this.redoToolStripMenuItem.Size = new System.Drawing.Size(176, 22);
this.redoToolStripMenuItem.Text = "&Redo";
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(173, 6);
//
// cutToolStripMenuItem
//
this.cutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripMenuItem.Image")));
this.cutToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X)));
this.cutToolStripMenuItem.Size = new System.Drawing.Size(176, 22);
this.cutToolStripMenuItem.Text = "Cu&t";
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripMenuItem.Image")));
this.copyToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.copyToolStripMenuItem.Size = new System.Drawing.Size(176, 22);
this.copyToolStripMenuItem.Text = "&Copy";
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripMenuItem.Image")));
this.pasteToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(176, 22);
this.pasteToolStripMenuItem.Text = "&Paste";
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(173, 6);
//
// selectAllToolStripMenuItem
//
this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(176, 22);
this.selectAllToolStripMenuItem.Text = "Select &All";
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.contentsToolStripMenuItem,
this.toolStripSeparator5,
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(48, 22);
this.helpToolStripMenuItem.Text = "&Help";
//
// contentsToolStripMenuItem
//
this.contentsToolStripMenuItem.AutoToolTip = true;
this.contentsToolStripMenuItem.Name = "contentsToolStripMenuItem";
this.contentsToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.contentsToolStripMenuItem.Text = "&Contents";
this.contentsToolStripMenuItem.Click += new System.EventHandler(this.contentsToolStripMenuItem_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(146, 6);
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.aboutToolStripMenuItem.Text = "&About...";
this.aboutToolStripMenuItem.ToolTipText = "About this program";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// customizeToolStripMenuItem
//
this.customizeToolStripMenuItem.Name = "customizeToolStripMenuItem";
this.customizeToolStripMenuItem.Size = new System.Drawing.Size(32, 19);
this.customizeToolStripMenuItem.Text = "&Customize";
//
// saveFileDialog
//
this.saveFileDialog.FileOk += new System.ComponentModel.CancelEventHandler(this.saveFileDialog1_FileOk);
//
// DistexForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 17F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ControlLight;
this.ClientSize = new System.Drawing.Size(642, 611);
this.Controls.Add(this.propertiesTab);
this.Controls.Add(this.menuStrip1);
this.Font = new System.Drawing.Font("Tahoma", 8.400001F);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.Margin = new System.Windows.Forms.Padding(4);
this.MaximizeBox = false;
this.MinimumSize = new System.Drawing.Size(650, 645);
this.Name = "DistexForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Statistical Distribution Explorer";
this.toolTip1.SetToolTip(this, "Statistical Distribution Explorer main form");
this.Activated += new System.EventHandler(this.DistexForm_Activated);
this.Load += new System.EventHandler(this.Form_Load);
this.propertiesTab.ResumeLayout(false);
this.DistributionTab.ResumeLayout(false);
this.DistributionTab.PerformLayout();
this.PropertiesTabPage.ResumeLayout(false);
this.PropertiesTabPage.PerformLayout();
this.cdfTabPage.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.CDF_data)).EndInit();
this.QuantileTabPage.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.QuantileData)).EndInit();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TabControl propertiesTab;
private System.Windows.Forms.TabPage DistributionTab;
private System.Windows.Forms.TabPage PropertiesTabPage;
private System.Windows.Forms.Label distributionNameLabel;
private System.Windows.Forms.Label parameter2Label;
private System.Windows.Forms.Label parameter1Label;
private System.Windows.Forms.TextBox parameter2;
private System.Windows.Forms.TextBox parameter1;
private System.Windows.Forms.ComboBox distribution;
private System.Windows.Forms.Label standard_deviation;
private System.Windows.Forms.Label stddevLabel;
private System.Windows.Forms.Label variance;
private System.Windows.Forms.Label varianceLabel;
private System.Windows.Forms.Label medianLabel;
private System.Windows.Forms.Label mode;
private System.Windows.Forms.Label mean;
private System.Windows.Forms.Label meanLabel;
private System.Windows.Forms.TabPage cdfTabPage;
private System.Windows.Forms.DataGridView CDF_data;
private System.Windows.Forms.DataGridViewTextBoxColumn RandomVariable;
private System.Windows.Forms.DataGridViewTextBoxColumn PDF;
private System.Windows.Forms.DataGridViewTextBoxColumn CDF;
private System.Windows.Forms.DataGridViewTextBoxColumn CCDF;
private System.Windows.Forms.TabPage QuantileTabPage;
private System.Windows.Forms.DataGridView QuantileData;
private System.Windows.Forms.DataGridViewTextBoxColumn RiskLevel;
private System.Windows.Forms.DataGridViewTextBoxColumn LowerCriticalValue;
private System.Windows.Forms.DataGridViewTextBoxColumn UpperCriticalValue;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem printPreviewToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem customizeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem contentsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.Label median;
private System.Windows.Forms.Label skewness;
private System.Windows.Forms.Label skewnessLabel;
private System.Windows.Forms.Label kurtosis;
private System.Windows.Forms.Label kurtosisLabel;
private System.Windows.Forms.Label kurtosis_excess;
private System.Windows.Forms.Label kurtosisExcessLabel;
private System.Windows.Forms.Label modeLabel;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.Label CVlabel;
private System.Windows.Forms.Label coefficient_of_variation;
private System.Windows.Forms.Label parameter3Label;
private System.Windows.Forms.TextBox parameter3;
private System.Windows.Forms.Label parameterLabel3;
private System.Windows.Forms.Label parameterLabel2;
private System.Windows.Forms.Label parameterLabel1;
private System.Windows.Forms.Label DistributionLabel;
private System.Windows.Forms.Label parameter3ValueLabel;
private System.Windows.Forms.Label parameter2ValueLabel;
private System.Windows.Forms.Label parameter1ValueLabel;
private System.Windows.Forms.Label distributionValueLabel;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
private System.Windows.Forms.Label supportLabel;
private System.Windows.Forms.Label rangeGreatestLabel;
private System.Windows.Forms.Label rangeLowestLabel;
private System.Windows.Forms.Label rangeLabel;
private System.Windows.Forms.Label supportUpperLabel;
private System.Windows.Forms.Label supportLowerLabel;
private System.Windows.Forms.Label toLabel2;
private System.Windows.Forms.Label toLabel1;
}
}
| |
/*
* TestString.cs - Tests for the "System.String" class.
*
* Copyright (C) 2002 Free Software Foundation, Inc.
*
* Authors : Stephen Compall, Gopal.V, & Richard Baumann
*
* 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
*/
using CSUnit;
using System;
public class TestString : TestCase
{
// Constructor.
public TestString(String name)
: base(name)
{
// Nothing to do here.
}
// Set up for the tests.
protected override void Setup()
{
// Nothing to do here.
}
// Clean up after the tests.
protected override void Cleanup()
{
// Nothing to do here.
}
//Methods
public void TestStringClone()
{
String fubar = "Foo Bar";
AssertEquals("fubar.Clone() as String",fubar,(String)fubar.Clone());
AssertEquals("fubar.Clone() as Object",(Object)fubar,fubar.Clone());
AssertEquals("((ICloneable) fubar).Clone() as String",fubar,(String)((ICloneable) fubar).Clone());
AssertEquals("((ICloneable) fubar).Clone() as Object",(Object)fubar,((ICloneable) fubar).Clone());
}
public void TestStringCompare()
{
/* String lesser = "abc";
String medium = "abcd";
String greater = "xyz";
String caps = "ABC";*/
AssertEquals("String.Compare(null,null))",0,String.Compare(null,null));
AssertEquals("String.Compare(\"abc\",null)",1,
String.Compare("abc", null));
Assert("String.Compare(null,\"abc\")",
String.Compare(null,"abc") < 0);
Assert("String.Compare(\"abc\",\"xyz\")",
String.Compare("abc","xyz") < 0);
Assert("String.Compare(\"abc\",\"abcd\")",
String.Compare("abc","abcd") < 0);
Assert("String.Compare(\"xyz\",\"abc\")",
String.Compare("xyz","abc") > 0);
Assert("String.Compare(\"abc\",\"ABC\",true)",
String.Compare("abc","ABC",true) == 0);
Assert("String.Compare(\"abc\",\"ABC\",true)",
String.Compare("abc","ABC",true) == 0);
Assert("String.Compare(\"abc\",\"ABC\",false)",
String.Compare("abc","ABC",false) != 0);
Assert("String.Compare(\"a\",\"A\")",String.Compare("a","A") < 0);
Assert("String.Compare(\"A\",\"a\")",String.Compare("A","a") > 0);
AssertEquals("String.Compare(\"\",\"\")",String.Compare("",""),0);
AssertEquals("String.Compare(\"abc\",0,\"xyz\",0,0)",
String.Compare("abc",0,"xyz",0,0),0);
AssertEquals("String.Compare(\"abcdabcd\",0,\"ab\",0,2)",
String.Compare("abcdabcd",0,"ab",0,2),0);
AssertEquals("String.Compare(\"abcdabcd\",4,\"ab\",0,2)",
String.Compare("abcdabcd",4,"ab",0,2),0);
Assert("String.Compare(\"abcdabcd\",1,\"ab\",0,2)",
String.Compare("abcdabcd",1,"ab",0,2) > 0 );
Assert("String.Compare(\"abcdabcd\",0,\"xyz\",0,2)",
String.Compare("abcdabcd",0,"xyz",0,2) < 0 );
AssertEquals("String.Compare(\"abcdabcd\",0,\"abd\",0,2)",
String.Compare("abcdabcd",0,"abd",0,2),0);
try
{
String.Compare("ab",3,"abc",1,7);
Fail(" String.Compare(\"ab\",3,\"abc\",1,7) did not throw ArgumentOutOfRangeException");
}
catch(ArgumentOutOfRangeException err)
{
//Ok, that worked :)
//move on folks
}
Assert("String.Compare(\"ABCDC\",1,\"bcd\",0,3,false)",
String.Compare("ABCDC",1,"bcd",0,3,false) !=0);
Assert("String.Compare(\"ABCDC\",1,\"bcd\",0,3,true)",
String.Compare("ABCDC",1,"bcd",0,3,true) !=1);
try
{
String.Compare("ab",3,"abc",1,7,true);
Fail(" String.Compare(\"ab\",3,\"abc\",1,7,true) did not throw ArgumentOutOfRangeException");
}
catch(ArgumentOutOfRangeException err)
{
//Ok, that worked :)
//move on folks
}
try
{
AssertEquals("String.Compare(\"ab\",1,\"abd\",1,7)",
-1 , String.Compare("ab",1,"abd",1,7));
#if ECMA_COMPAT
Fail(" String.Compare(\"ab\",1,\"abc\",1,7,true) did not throw ArgumentOutOfRangeException");
#endif
}
catch(ArgumentOutOfRangeException err)
{
#if !ECMA_COMPAT
Fail(" String.Compare(\"ab\",1,\"abc\",1,7,true) should NOT throw an ArgumentOutOfRangeException");
#endif
}
try
{
AssertEquals("String.Compare(\"ab\",1,\"abc\",3,7,true)",
1 , String.Compare("ab",1,"abc",3,7,true));
#if ECMA_COMPAT
Fail(" String.Compare(\"ab\",1,\"abc\",3,7,true) did not throw ArgumentOutOfRangeException");
#endif
}
catch(ArgumentOutOfRangeException err)
{
#if !ECMA_COMPAT
Fail(" String.Compare(\"ab\",1,\"abc\",3,7,true) should NOT throw an ArgumentOutOfRangeException");
#endif
}
/*
TODO: put in a looped check for Compare ()
*/
}
public void TestStringCompareOrdinal()
{
/*
TODO: doesn't this need checks for all the I18n infos ?
what's the sense in doing it for English , which is
what Compare() does.
*/
}
public void TestStringCompareTo()
{
/*
NOTE: doesn't this actually call the Compare(this,a) func ?
*/
String str="abc";
Assert("str.CompareTo(\"xyz\")", str.CompareTo("xyz") < 0);
Assert("str.CompareTo(\"abc\")", str.CompareTo("abc") == 0);
Assert("str.CompareTo(\"0\")", str.CompareTo("0") > 0);
}
public void TestStringConcat()
{
//String str1="Fu";
//String str2="Bar";
AssertEquals("String.Concat(\"Fu\",\"Bar\")",
String.Concat("Fu","Bar"),"FuBar");
AssertEquals("String.Concat(\"Foo\",\" \",\"Bar\")",
String.Concat("Foo"," ","Bar"),"Foo Bar");
// yup , F Up Beyond All Recognition
}
public void TestStringCopy()
{
String str1="Foo";
String str2= String.Copy(str1);
AssertEquals("String.Copy(str1)==str1",str2,str1);
Assert("String.Copy(str1) as Object != str1 as Object",(Object)str2 != (Object)str1);
try
{
String s = String.Copy(null);
Fail(" String.Copy(null) should throw an ArgumentNullException");
}
catch(ArgumentNullException err)
{
//ummm... looks good
}
}
public void TestStringCopyTo()
{
/*TODO*/
String str1 = "FuBar";
try
{
str1.CopyTo(0,(char[])null,0,0);
Fail("str1.CopyTo(0,(char[])null,0,0) should have throws a ArgumentNullException");
}
catch(ArgumentNullException err)
{
//worked !
}
char[] c = new char[str1.Length];
for (int i = 0; i < str1.Length ; i++)
str1.CopyTo(i, c, i, 1); // copy 1 char at a time
String str2 = new String(c);
AssertEquals("str1.CopyTo() char by char",str1,str2);
// must find a better error message :)
}
public void TestStringEndsWith()
{
/*TODO*/
String str = "Foo Bar";
try
{
bool check = str.EndsWith(null);
Fail("String.EndsWith(null) should throw an ArgumentNullException");
}
catch (ArgumentNullException)
{
//OK move on
}
Assert("str.EndsWith(\"r\")", str.EndsWith("r"));
Assert("str.EndsWith(\"Bar\")", str.EndsWith("Bar"));
Assert("str.EndsWith(\"Foo Bar\")", str.EndsWith("Foo Bar"));
Assert("!str.EndsWith(\"Foo\")", !str.EndsWith("Foo"));
}
public void TestStringEquals()
{
/*
TODO: really need to see how to I18n here
*/
String foobar = "FooBar";
String fubar = "FooBar";
String good_copy = foobar;
String bad_copy = "I'm bad";
String bad = null;
try
{
bool q=bad.Equals("nothing");
Fail("bad.Equals(\"nothing\") should have thrown a NullReferenceException");
}
catch(NullReferenceException err)
{
//great !
}
Assert("!foobar.Equals(null)", !foobar.Equals(null));
Assert("foobar.Equals(fubar)", foobar.Equals(fubar));
Assert("foobar.Equals(good_copy)", foobar.Equals(good_copy));
Assert("!foobar.Equals(bad_copy)", !foobar.Equals(bad_copy));
Assert("String.Equals(null,null)", String.Equals(null, null));
Assert("String.Equals(foobar,fubar)", String.Equals(foobar, fubar));
Assert("!String.Equals(foobar,bad_copy)", !String.Equals(foobar, bad_copy));
}
public void TestStringFormat()
{
/*TODO*/
AssertEquals ("String.Format(\"\",0)", "", String.Format ("", 0));
AssertEquals ("String.Format(\"{0}\",\"FooBar\")",
"FooBar", String.Format ("{0}","FooBar"));
AssertEquals ("String.Format(\"{0}\",111)",
"111", String.Format ("{0}",111));
try
{
String.Format(null,12);
Fail("String.Format(null,12) should throw an ArgumentNullException");
}
catch(ArgumentNullException err)
{
// all's well
}
try
{
String.Format("Er..",null);
// all's well
}
catch(ArgumentNullException err)
{
Fail("String.Format(\"Er...\",null) should not throw an ArgumentNullException");
}
try
{
String.Format("{-1}",12);
Fail("String.Format(\"{-1}\",12) should throw an FormatException");
}
catch(FormatException err)
{
// all's well
}
try
{
String.Format("{3}",12);
Fail("String.Format(\"{3}\",12) should throw an FormatException");
}
catch(FormatException err)
{
// all's well
}
try
{
String.Format("{}",12);
Fail("String.Format(\"{}\",12) should throw an FormatException");
}
catch(FormatException err)
{
// all's well
}
AssertEquals("String.Format (\"<{0,5}>\", 12)",
"< 12>",String.Format ("<{0,5}>", 12));
AssertEquals("String.Format (\"<{0,-5}>\", 12)",
"<12 >",String.Format ("<{0,-5}>", 12));
AssertEquals("String.Format (\"<{0,10}>\", 42)",
"< 42>",String.Format ("<{0,10}>", 42));
AssertEquals("String.Format (\"<{0,-10}>\", 42)",
"<42 >",String.Format ("<{0,-10}>", 42));
AssertEquals ("String.Format(\"The {1} of {1}\",\"Church\",\"Emacs\")",
"The Church of Emacs",
String.Format ("The {0} of {1}", "Church", "Emacs"));
AssertEquals(
"String.Format(\"G{0} N{1} U{2}\",\"nu's\",\"ot\",\"nix\")",
"Gnu's Not Unix",
String.Format ("G{0} N{1} U{2}", "nu's", "ot", "nix"));
AssertEquals ("String.Format (\"{0:x8}\", 0xcafebabe),\"cafebabe\")",
"cafebabe", String.Format ("{0:x8}", 0xcafebabe));
AssertEquals ("String.Format (\"{0:X8}\", 0xcafebabe),\"CAFEBABE\")",
"CAFEBABE", String.Format ("{0:X8}", 0xcafebabe));
AssertEquals ("String.Format (\"<{0,5:x3}>\", 0x55)",
"< 055>", String.Format ("<{0,5:x3}>", 0x55));
AssertEquals ("String.Format (\"<{0,-5:x3}>\", 0x55)",
"<055 >", String.Format ("<{0,-5:x3}>", 0x55));
AssertEquals ("String.Format (\"if({0}==0){{ .... }}\",\"i\")",
"if(i==0){ .... }", String.Format ("if({0}==0){{ .... }}", "i"));
/* Some tests inspired by the mailing list */
AssertEquals ("String.Format (\"0x{0:X2}\", (byte)255)",
"0xFF", String.Format("0x{0:X2}", (byte)255));
AssertEquals ("String.Format (\"0x{0:X2}\", (byte)14)",
"0x0E", String.Format("0x{0:X2}", (byte)14));
AssertEquals ("String.Format (\"{0:D2}\", 9)",
"09", String.Format("{0:D2}", 9));
// Can't use these any more since cultures mess them up -- Rhys.
#if false
#if CONFIG_EXTENDED_NUMERICS
AssertEquals ("String.Format (\"{0:F2}\", 1234567.89)",
"1234567.89", String.Format("{0:F2}", 1234567.89));
AssertEquals ("String.Format (\"{0:C2}\", 1234567)",
"\u00a4"+"1,234,567.00", String.Format("{0:C2}", 1234567));
AssertEquals ("String.Format (\"{0:E}\", 1234568)",
"1.234568E+006", String.Format("{0:E}", 1234568));
AssertEquals ("String.Format (\"{0:e}\", 0.325)",
"3.25e-001", String.Format("{0:e}", 0.325));
/* Custom Format tests... */
AssertEquals ("String.Format(\"{0:#,###,##0.00}\", 1234567.81)",
"1,234,567.81", String.Format("{0:#,###,##0.00}", 1234567.81));
AssertEquals ("String.Format(\"{0:#,##0,}M\", 1234000)",
"1,234M", String.Format("{0:#,###,}M", 1234000));
AssertEquals("String.Format(\"{0:####.##}\", 0)",
".", String.Format("{0:####.##}", 0));
AssertEquals("String.Format(\"{0:###0.0#}\", 0)",
"0.0", String.Format("{0:###0.0#}", 0));
#endif
#endif
}
public void TestStringGetEnumerator()
{
String str = "foobar";
char[] c = new char[str.Length];
CharEnumerator en = str.GetEnumerator();
AssertNotNull("CharEnumerator en!=null", en);
for (int i = 0; i < str.Length; i++)
{
en.MoveNext();
c[i] = en.Current;
}
String copy = new String(c);
AssertEquals("Copy by enumerator for string", str, copy);
}
public void TestStringGetHashCode()
{
/*
TODO: what do I do here ?. (determinicity check ?)
s.GetHashCode() == s.GetHashCode() ?.
*/
String str1 = "foobar";
String str2 = String.Copy(str1);
AssertEquals("str1.GetHashCode() == str1.GetHashCode()",
str1.GetHashCode(),str1.GetHashCode());
AssertEquals("str1.GetHashCode() == str2.GetHashCode()",
str1.GetHashCode(),str2.GetHashCode());
}
public void TestStringIndexOf()
{
String fubar = "Foo Bar";
try
{
fubar.IndexOf(null);
Fail("fubar.IndexOf(null) should throw an ArgumentNullException");
fubar.IndexOf(null,0);
Fail("fubar.IndexOf(null,0) should throw an ArgumentNullException");
fubar.IndexOf(null,0,1);
Fail("fubar.IndexOf(null,0,1) should throw an ArgumentNullException");
}
catch(ArgumentNullException err)
{
//all's well
}
try
{
fubar.IndexOf('f',fubar.Length+1);
Fail("fubar.IndexOf('f',fubar.Length+1) should throw an ArgumentOutOfRangeException");
fubar.IndexOf('f',fubar.Length+1,1);
Fail("fubar.IndexOf('f',fubar.Length+1,1) should throw an ArgumentOutOfRangeException");
fubar.IndexOf("foo",fubar.Length+1);
Fail("fubar.IndexOf(\"foo\",fubar.Length+1) should throw an ArgumentOutOfRangeException");
fubar.IndexOf("foo",fubar.Length+1,1);
Fail("fubar.IndexOf(\"foo\",fubar.Length+1,1) should throw an ArgumentOutOfRangeException");
}
catch(ArgumentOutOfRangeException err)
{
//all's well
}
AssertEquals("fubar.IndexOf('o')", fubar.IndexOf('o'),1);
AssertEquals("fubar.IndexOf('F')", fubar.IndexOf('F'),0);
AssertEquals("fubar.IndexOf('z')", fubar.IndexOf('z'),-1);
AssertEquals("fubar.IndexOf(\"oo\")", fubar.IndexOf("oo"),1);
AssertEquals("fubar.IndexOf(\"Bar\")", fubar.IndexOf("Bar"),4);
AssertEquals("fubar.IndexOf(\"qwaz\")", fubar.IndexOf("qwaz"),-1);
AssertEquals("fubar.IndexOf('o',1)", fubar.IndexOf('o',1),1);
AssertEquals("fubar.IndexOf('o',3)", fubar.IndexOf('o',3),-1);
AssertEquals("fubar.IndexOf('z',4)", fubar.IndexOf('z',4),-1);
AssertEquals("fubar.IndexOf(\"oo\",1)", fubar.IndexOf("oo",1),1);
AssertEquals("fubar.IndexOf(\"oo\",2)", fubar.IndexOf("oo",2),-1);
AssertEquals("fubar.IndexOf('o',1,2)", fubar.IndexOf('o',1,1),1);
AssertEquals("fubar.IndexOf('o',0,1)", fubar.IndexOf('o',0,1),-1);
AssertEquals("fubar.IndexOf(' ',1,5)", fubar.IndexOf(' ',1,5),3);
try
{
fubar.IndexOf('h', fubar.Length); // shouldn't throw per ECMA
}
catch (ArgumentOutOfRangeException)
{
Fail("IndexOf(char, int) should not throw when passed Length as the int");
}
/*
TODO: I don't know any more test ideas , do you have one ?
*/
}
public void TestStringIndexOfAny()
{
String fubar="mary had a little lamb ....";
try
{
fubar.IndexOfAny(null);
Fail("fubar.IndexOfAny(null) should throw an ArgumentNullException");
fubar.IndexOfAny(null,0);
Fail("fubar.IndexOfAny(null,0) should throw an ArgumentNullException");
fubar.IndexOfAny(null,0,1);
Fail("fubar.IndexOfAny(null,0,1) should throw an ArgumentNullException");
}
catch(ArgumentNullException err)
{
//all's A-OK !
}
char[] c={'a','e','i','o','u'};
try
{
fubar.IndexOfAny(c,fubar.Length+1);
Fail("fubar.IndexOfAny(c,fubar.Length+1) should throw an ArgumentOutOfRangeException");
fubar.IndexOfAny(c,fubar.Length+1,1);
Fail("fubar.IndexOfAny(c,fubar.Length+1,1) should throw an ArgumentOutOfRangeException");
fubar.IndexOfAny(c,fubar.Length-3,5);
Fail("fubar.IndexOfAny(c,fubar.Length-3,5) should throw an ArgumentOutOfRangeException");
}
catch(ArgumentOutOfRangeException)
{
//all's well in code and data :)
}
AssertEquals("fubar.IndexOfAny(c)",fubar.IndexOfAny(c),1); //m`a'
AssertEquals("fubar.IndexOfAny(c,2)",fubar.IndexOfAny(c,2),6);//h`a
AssertEquals("fubar.IndexOfAny(c,21)",fubar.IndexOfAny(c,21),-1);
AssertEquals("fubar.IndexOfAny(c,2,5)",fubar.IndexOfAny(c,2,5),6);
AssertEquals("fubar.IndexOfAny(c,2,3)",fubar.IndexOfAny(c,2,3),-1);
}
public void TestStringInsert()
{
String fubar = "FooBar";
AssertEquals("fubar.Insert(3,\" \")","Foo Bar",fubar.Insert(3," "));
AssertEquals("fubar.Insert(0,\" \")"," FooBar",fubar.Insert(0," "));
AssertEquals("fubar.Insert(fubar.Length,\" \")","FooBar ",fubar.Insert(fubar.Length," "));
try
{
fubar.Insert(0,null);
Fail("fubar.Insert(0,null) should throw an ArgumentNullException");
}
catch(ArgumentNullException)
{
// checks out ok
}
try
{
fubar.Insert(fubar.Length+1," ");
Fail("fubar.Insert(fubar.Length+1,\" \") should throw an ArgumentOutOfRangeException");
}
catch(ArgumentOutOfRangeException)
{
// this works too
}
}
public void TestStringIntern()
{
String foobar = "if the sun refused to shine, I don't mind, I don't mind... if the mountains fell in the sea, let it be, it aint me - hendrix";
String fubar = foobar.Substring(0,10);
fubar += foobar.Substring(10,foobar.Length-10);
fubar = String.Intern(fubar);
AssertEquals("String.Intern(fubar)",(Object)foobar,(Object)fubar);
try
{
String.Intern(null);
Fail("String.Intern(null) should throw an ArgumentNullException");
}
catch (ArgumentNullException)
{
// this works
}
}
public void TestStringIsInterned()
{
// I can't imagine anyone using a string like this in pnetlib or the unit tests, so this should work
char[] fu = new char[13] { 'q','w','e','r','t','y','u','i','o','p','\t','\0','\n' };
String foobar = new String(fu);
String fubar = String.IsInterned(foobar);
Assert("String.IsInterned(foobar)",fubar == null);
try
{
String.IsInterned(null);
Fail("String.IsInterned(null) should throw an ArgumentNullException");
}
catch (ArgumentNullException)
{
// all is good
}
}
public void TestStringJoin()
{
String fu = " fu ";
String fu2 = "";
String[] foo = new String[6] { "foo","ofo","oof","FOO","OFO","OOF" };
String[] foo2 = new String[3] { "","","" };
String[] foo3 = new String[0] { };
AssertEquals("String.Join(fu,foo)","foo fu ofo fu oof fu FOO fu OFO fu OOF",String.Join(fu,foo));
AssertEquals("String.Join(fu,foo,0,foo.Length)","foo fu ofo fu oof fu FOO fu OFO fu OOF",String.Join(fu,foo,0,foo.Length));
AssertEquals("String.Join(fu,foo,0,1)","foo",String.Join(fu,foo,0,1));
AssertEquals("String.Join(fu,foo,1,1)","ofo",String.Join(fu,foo,1,1));
AssertEquals("String.Join(fu,foo,2,1)","oof",String.Join(fu,foo,2,1));
AssertEquals("String.Join(fu,foo,3,1)","FOO",String.Join(fu,foo,3,1));
AssertEquals("String.Join(fu,foo,4,1)","OFO",String.Join(fu,foo,4,1));
AssertEquals("String.Join(fu,foo,5,1)","OOF",String.Join(fu,foo,5,1));
AssertEquals("String.Join(fu,foo,0,2)","foo fu ofo",String.Join(fu,foo,0,2));
AssertEquals("String.Join(fu,foo,1,2)","ofo fu oof",String.Join(fu,foo,1,2));
AssertEquals("String.Join(fu,foo,2,2)","oof fu FOO",String.Join(fu,foo,2,2));
AssertEquals("String.Join(fu,foo,3,2)","FOO fu OFO",String.Join(fu,foo,3,2));
AssertEquals("String.Join(fu,foo,4,2)","OFO fu OOF",String.Join(fu,foo,4,2));
AssertEquals("String.Join(fu,foo,0,3)","foo fu ofo fu oof",String.Join(fu,foo,0,3));
AssertEquals("String.Join(fu,foo,1,3)","ofo fu oof fu FOO",String.Join(fu,foo,1,3));
AssertEquals("String.Join(fu,foo,2,3)","oof fu FOO fu OFO",String.Join(fu,foo,2,3));
AssertEquals("String.Join(fu,foo,3,3)","FOO fu OFO fu OOF",String.Join(fu,foo,3,3));
AssertEquals("String.Join(fu,foo,0,4)","foo fu ofo fu oof fu FOO",String.Join(fu,foo,0,4));
AssertEquals("String.Join(fu,foo,1,4)","ofo fu oof fu FOO fu OFO",String.Join(fu,foo,1,4));
AssertEquals("String.Join(fu,foo,2,4)","oof fu FOO fu OFO fu OOF",String.Join(fu,foo,2,4));
AssertEquals("String.Join(fu,foo,0,5)","foo fu ofo fu oof fu FOO fu OFO",String.Join(fu,foo,0,5));
AssertEquals("String.Join(fu,foo,1,5)","ofo fu oof fu FOO fu OFO fu OOF",String.Join(fu,foo,1,5));
AssertEquals("String.Join(fu,foo,0,0)","",String.Join(fu,foo,0,0));
AssertEquals("String.Join(fu2,foo2,0,foo2.Length)","",String.Join(fu2,foo2,0,foo2.Length));
AssertEquals("String.Join(fu,foo3,0,foo3.Length)","",String.Join(fu,foo3,0,foo3.Length));
try
{
String.Join(fu,null);
Fail("String.Join(fu,null) should throw an ArgumentNullException");
}
catch (ArgumentNullException)
{
// works
}
try
{
String.Join(fu,foo,0,foo.Length+1);
Fail("String.Join(fu,foo,0,foo.Length+1) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// works
}
}
public void TestStringLastIndexOf()
{
String foo = "Foo Bar foo bar fu bar Fu Bar";
/* String.LastIndexOf(char) */
AssertEquals("foo.LastIndexOf('r')",28,foo.LastIndexOf('r'));
AssertEquals("foo.LastIndexOf('a')",27,foo.LastIndexOf('a'));
AssertEquals("foo.LastIndexOf('B')",26,foo.LastIndexOf('B'));
AssertEquals("foo.LastIndexOf(' ')",25,foo.LastIndexOf(' '));
AssertEquals("foo.LastIndexOf('u')",24,foo.LastIndexOf('u'));
AssertEquals("foo.LastIndexOf('F')",23,foo.LastIndexOf('F'));
AssertEquals("foo.LastIndexOf('b')",19,foo.LastIndexOf('b'));
AssertEquals("foo.LastIndexOf('f')",16,foo.LastIndexOf('f'));
AssertEquals("foo.LastIndexOf('o')",10,foo.LastIndexOf('o'));
AssertEquals("foo.LastIndexOf('c')",-1,foo.LastIndexOf('c'));
/* String.LastIndexOf(char,int) */
AssertEquals("foo.LastIndexOf('f',16)",16,foo.LastIndexOf('f',16));
AssertEquals("foo.LastIndexOf('f',15)",8,foo.LastIndexOf('f',15));
AssertEquals("foo.LastIndexOf('f',7)",-1,foo.LastIndexOf('f',7));
AssertEquals("foo.LastIndexOf('f',foo.Length-1)",16,foo.LastIndexOf('f',foo.Length-1));
try
{
AssertEquals("foo.LastIndexOf('f',foo.Length)",16,foo.LastIndexOf('f',foo.Length)); // don't ask me
}
catch (ArgumentOutOfRangeException)
{
// This looks like brain damage in the spec, but it's easy enough to implement.
Fail("foo.LastIndexOf('f',foo.Length) should NOT throw an ArgumentOutOfRangeException");
}
try
{
foo.LastIndexOf('f',-1);
Fail("foo.LastIndexOf('f',-1) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// nothing wrong here
}
try
{
foo.LastIndexOf('f',foo.Length+1);
Fail("foo.LastIndexOf('f',foo.Length+1) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// or here
}
/* String.LastIndexOf(char,int,int) */
AssertEquals("foo.LastIndexOf('f',16,17)",16,foo.LastIndexOf('f',16,17));
AssertEquals("foo.LastIndexOf('f',15,16)",8,foo.LastIndexOf('f',15,16));
AssertEquals("foo.LastIndexOf('f',15,7)",-1,foo.LastIndexOf('f',15,7));
AssertEquals("foo.LastIndexOf('f',foo.Length-1,1)",-1,foo.LastIndexOf('f',foo.Length-1,1));
AssertEquals("foo.LastIndexOf('r',foo.Length-1,1)",-1,foo.LastIndexOf('r',foo.Length-1,0));
AssertEquals("foo.LastIndexOf('r',foo.Length-1,1)",28,foo.LastIndexOf('r',foo.Length-1,1));
AssertEquals("foo.LastIndexOf('F',0,1)",0,foo.LastIndexOf('F',0,1));
AssertEquals("foo.LastIndexOf('F',1,1)",-1,foo.LastIndexOf('F',1,1));
try
{
AssertEquals("foo.LastIndexOf('r',foo.Length,0)",-1,foo.LastIndexOf('r',foo.Length,0)); // ask the ECMA
}
catch (ArgumentOutOfRangeException)
{
Fail("foo.LastIndexOf('r',foo.Length,0) should NOT throw an ArgumentOutOfRangeException");
}
try
{
AssertEquals("foo.LastIndexOf('r',foo.Length,1)",-1,foo.LastIndexOf('r',foo.Length,1)); // b/c these are
}
catch (ArgumentOutOfRangeException)
{
Fail("foo.LastIndexOf('r',foo.Length,1) should NOT throw an ArgumentOutOfRangeException");
}
try
{
AssertEquals("foo.LastIndexOf('r',foo.Length,2)",28,foo.LastIndexOf('r',foo.Length,2)); // all valid,
}
catch (ArgumentOutOfRangeException)
{
Fail("foo.LastIndexOf('r',foo.Length,2) should NOT throw an ArgumentOutOfRangeException");
}
try
{
AssertEquals("foo.LastIndexOf('f',foo.Length+10,0)",-1,foo.LastIndexOf('f',foo.Length+10,0)); // believe
}
catch (ArgumentOutOfRangeException)
{
Fail("foo.LastIndexOf('f',foo.Length+10,0) should NOT throw an ArgumentOutOfRangeException");
}
try
{
AssertEquals("foo.LastIndexOf('f',foo.Length+10,1)",-1,foo.LastIndexOf('f',foo.Length+10,1)); // it or not.
}
catch (ArgumentOutOfRangeException)
{
Fail("foo.LastIndexOf('f',foo.Length+10,1) should NOT throw an ArgumentOutOfRangeException");
}
try
{
AssertEquals("foo.LastIndexOf('f',foo.Length+10,11)",-1,foo.LastIndexOf('f',foo.Length+10,11)); // amazing,
}
catch (ArgumentOutOfRangeException)
{
Fail("foo.LastIndexOf('f',foo.Length+10,11) should NOT throw an ArgumentOutOfRangeException");
}
try
{
AssertEquals("foo.LastIndexOf('r',foo.Length+10,12)",28,foo.LastIndexOf('r',foo.Length+10,12)); // isn't it?
}
catch (ArgumentOutOfRangeException)
{
Fail("foo.LastIndexOf('r',foo.Length+10,12) should NOT throw an ArgumentOutOfRangeException");
}
try
{
foo.LastIndexOf('f',-1,0);
Fail("foo.LastIndexOf('f',-1,0) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// a-ok
}
try
{
foo.LastIndexOf('f',0,-1);
Fail("foo.LastIndexOf('f',0,-1) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// no problems here
}
try
{
foo.LastIndexOf('f',0,2);
Fail("foo.LastIndexOf('f',0,2) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// blah
}
/* String.LastIndexOf(String) */
AssertEquals("foo.LastIndexOf(\"Bar\")",26,foo.LastIndexOf("Bar"));
AssertEquals("foo.LastIndexOf(\"Fu\")",23,foo.LastIndexOf("Fu"));
AssertEquals("foo.LastIndexOf(\"bar\")",19,foo.LastIndexOf("bar"));
AssertEquals("foo.LastIndexOf(\"fu\")",16,foo.LastIndexOf("fu"));
AssertEquals("foo.LastIndexOf(\"foo\")",8,foo.LastIndexOf("foo"));
AssertEquals("foo.LastIndexOf(\"Foo\")",0,foo.LastIndexOf("Foo"));
AssertEquals("foo.LastIndexOf(\"blah\")",-1,foo.LastIndexOf("blah"));
AssertEquals("foo.LastIndexOf(\"\")",0,foo.LastIndexOf(""));
try
{
foo.LastIndexOf((String)null);
Fail("foo.LastIndexOf((String)null) should throw an ArgumentNullException");
}
catch (ArgumentNullException)
{
// looks good so far
}
/* String.LastIndexOf(String,int) */
AssertEquals("foo.LastIndexOf(\"Bar\",foo.Length-1)",26,foo.LastIndexOf("Bar",foo.Length-1));
AssertEquals("foo.LastIndexOf(\"Bar\",foo.Length-2)",4,foo.LastIndexOf("Bar",foo.Length-2));
AssertEquals("foo.LastIndexOf(\"Fu\",foo.Length-3)",23,foo.LastIndexOf("Fu",foo.Length-3));
AssertEquals("foo.LastIndexOf(\"Fu\",foo.Length-6)",-1,foo.LastIndexOf("Fu",foo.Length-6));
try
{
AssertEquals("foo.LastIndexOf(\"\",0)",0,foo.LastIndexOf("",0)); // this is absurd,
}
catch (ArgumentOutOfRangeException)
{
Fail("foo.LastIndexOf(\"\",0) should NOT throw an ArgumentOutOfRangeException");
}
try
{
AssertEquals("foo.LastIndexOf(\"\",1)",0,foo.LastIndexOf("",1)); // as is this
}
catch (ArgumentOutOfRangeException)
{
Fail("foo.LastIndexOf(\"\",1) should NOT throw an ArgumentOutOfRangeException");
}
try
{
foo.LastIndexOf((String)null,0);
Fail("foo.LastIndexOf((String)null,0) should throw an ArgumentNullException");
}
catch (ArgumentNullException)
{
// move along, nothing to see here
}
try
{
foo.LastIndexOf("foo",-1);
Fail("foo.LastIndexOf(\"foo\",-1) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// this works
}
try
{
foo.LastIndexOf("foo",foo.Length);
Fail("foo.LastIndexOf(\"foo\",foo.Length) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// this checks out
}
try
{
foo.LastIndexOf("foo",foo.Length+1);
Fail("foo.LastIndexOf(\"foo\",foo.Length+1) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// this checks out
}
/* String.LastIndexOf(String,int,int) */
AssertEquals("foo.LastIndexOf(\"Bar\",foo.Length-1,foo.Length)",26,foo.LastIndexOf("Bar",foo.Length-1,foo.Length));
AssertEquals("foo.LastIndexOf(\"Bar\",foo.Length-2,foo.Length-1)",4,foo.LastIndexOf("Bar",foo.Length-2,foo.Length-1));
AssertEquals("foo.LastIndexOf(\"Bar\",foo.Length-1,3)",26,foo.LastIndexOf("Bar",foo.Length-1,3));
AssertEquals("foo.LastIndexOf(\"Bar\",foo.Length-2,3)",-1,foo.LastIndexOf("Bar",foo.Length-2,3));
AssertEquals("foo.LastIndexOf(\"Bar\",foo.Length-1,2)",-1,foo.LastIndexOf("Bar",foo.Length-1,2));
AssertEquals("foo.LastIndexOf(\"Fu\",foo.Length-4,foo.Length-3)",23,foo.LastIndexOf("Fu",foo.Length-4,foo.Length-3));
AssertEquals("foo.LastIndexOf(\"Fu\",foo.Length-6,foo.Length-5)",-1,foo.LastIndexOf("Fu",foo.Length-6,foo.Length-5));
AssertEquals("foo.LastIndexOf(\"Fu\",foo.Length-4,3)",23,foo.LastIndexOf("Fu",foo.Length-4,3));
AssertEquals("foo.LastIndexOf(\"Fu\",foo.Length-6,3)",-1,foo.LastIndexOf("Fu",foo.Length-6,3));
try
{
AssertEquals("foo.LastIndexOf(\"\",0,0)",0,foo.LastIndexOf("",0,0)); // and the absurdity continues
}
catch (ArgumentOutOfRangeException)
{
Fail("foo.LastIndexOf(\"\",0,0) should NOT throw an ArgumentOutOfRangeException");
}
try
{
AssertEquals("foo.LastIndexOf(\"\",0,1)",0,foo.LastIndexOf("",0,1)); // need I say more?
}
catch (ArgumentOutOfRangeException)
{
Fail("foo.LastIndexOf(\"\",0,1) should NOT throw an ArgumentOutOfRangeException");
}
try
{
AssertEquals("foo.LastIndexOf(\"\",1,0)",0,foo.LastIndexOf("",1,0)); // ok, "more"
}
catch (ArgumentOutOfRangeException)
{
Fail("foo.LastIndexOf(\"\",1,0) should NOT throw an ArgumentOutOfRangeException");
}
try
{
AssertEquals("foo.LastIndexOf(\"\",1,1)",0,foo.LastIndexOf("",1,1)); // and more
}
catch (ArgumentOutOfRangeException)
{
Fail("foo.LastIndexOf(\"\",1,1) should NOT throw an ArgumentOutOfRangeException");
}
try
{
foo.LastIndexOf((String)null,0,0);
Fail("foo.LastIndexOf((String)null,0,0) should throw an ArgumentNullException");
}
catch (ArgumentNullException)
{
// doing good
}
try
{
foo.LastIndexOf("foo",-1,0);
Fail("foo.LastIndexOf(\"foo\",-1,0) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// even better
}
try
{
foo.LastIndexOf("foo",0,-1);
Fail("foo.LastIndexOf(\"foo\",0,-1) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// doing great, so far
}
try
{
foo.LastIndexOf("foo",0,2);
Fail("foo.LastIndexOf(\"foo\",0,2) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// yay! we made it
}
}
public void TestStringLastIndexOfAny()
{
// 00000000001111111111222222222
// 01234567890123456789012345678
String foo = "Foo Bar foo bar fu bar Fu Bar";
/* String.LastIndexOfAny(char[]) */
AssertEquals("foo.LastIndexOfAny(new char[] {'r','a','B'})",28,foo.LastIndexOfAny(new char[] {'r','a','B'}));
AssertEquals("foo.LastIndexOfAny(new char[] {'f','a','B'})",27,foo.LastIndexOfAny(new char[] {'f','a','B'}));
AssertEquals("foo.LastIndexOfAny(new char[] {'r'})",28,foo.LastIndexOfAny(new char[] {'r'}));
AssertEquals("foo.LastIndexOfAny(new char[] {'B'})",26,foo.LastIndexOfAny(new char[] {'B'}));
AssertEquals("foo.LastIndexOfAny(new char[] {'B','B'})",26,foo.LastIndexOfAny(new char[] {'B','B'}));
AssertEquals("foo.LastIndexOfAny(new char[] {'B','u'})",26,foo.LastIndexOfAny(new char[] {'B','u'}));
AssertEquals("foo.LastIndexOfAny(new char[] {'u','B'})",26,foo.LastIndexOfAny(new char[] {'u','B'}));
AssertEquals("foo.LastIndexOfAny(new char[] {'u','f'})",24,foo.LastIndexOfAny(new char[] {'u','f'}));
AssertEquals("foo.LastIndexOfAny(new char[] {'F','f'})",23,foo.LastIndexOfAny(new char[] {'F','f'}));
AssertEquals("foo.LastIndexOfAny(new char[] {'F','q'})",23,foo.LastIndexOfAny(new char[] {'F','q'}));
AssertEquals("foo.LastIndexOfAny(new char[] {'p','q'})",-1,foo.LastIndexOfAny(new char[] {'p','q'}));
try
{
foo.LastIndexOfAny((char[])null);
Fail("foo.LastIndexOfAny((char[])null) should throw an ArgumentNullException");
}
catch (ArgumentNullException)
{
// this is good
}
/* String.LastIndexOfAny(char[],int) */
AssertEquals("foo.LastIndexOfAny(new char[] {'r','a','B'},foo.Length-1)",28,foo.LastIndexOfAny(new char[] {'r','a','B'},foo.Length-1));
AssertEquals("foo.LastIndexOfAny(new char[] {'r','a','B'},foo.Length-2)",27,foo.LastIndexOfAny(new char[] {'r','a','B'},foo.Length-2));
AssertEquals("foo.LastIndexOfAny(new char[] {'r','a','B'},4)",4,foo.LastIndexOfAny(new char[] {'r','a','B'},4));
AssertEquals("foo.LastIndexOfAny(new char[] {'r','a','B'},5)",5,foo.LastIndexOfAny(new char[] {'r','a','B'},5));
AssertEquals("foo.LastIndexOfAny(new char[] {'r','a','B'},6)",6,foo.LastIndexOfAny(new char[] {'r','a','B'},6));
AssertEquals("foo.LastIndexOfAny(new char[] {'r','a','B'},1)",-1,foo.LastIndexOfAny(new char[] {'r','a','B'},1));
AssertEquals("foo.LastIndexOfAny(new char[] {'r','a','B'},0)",-1,foo.LastIndexOfAny(new char[] {'r','a','B'},0));
AssertEquals("foo.LastIndexOfAny(new char[] {'r','a','B'},3)",-1,foo.LastIndexOfAny(new char[] {'r','a','B'},3));
try
{
foo.LastIndexOfAny((char[])null,0);
Fail("foo.LastIndexOfAny((char[])null,0) should throw an ArgumentNullException");
}
catch (ArgumentNullException)
{
// caught it
}
try
{
foo.LastIndexOfAny(new char[] {'r','a','B'},-1);
Fail("foo.LastIndexOfAny(new char[] {'r','a','B'},-1); should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// caught another one
}
try
{
foo.LastIndexOfAny(new char[] {'r','a','B'},foo.Length);
Fail("foo.LastIndexOfAny(new char[] {'r','a','B'},foo.Length); should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// caught this one too
}
try
{
foo.LastIndexOfAny(new char[] {'r','a','B'},foo.Length+1);
Fail("foo.LastIndexOfAny(new char[] {'r','a','B'},foo.Length+1); should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// and this one
}
/* String.LastIndexOfAny(char[],int,int) */
AssertEquals("foo.LastIndexOfAny(new char[] {'r','a','B'},foo.Length-1,1)",28,foo.LastIndexOfAny(new char[] {'r','a','B'},foo.Length-1,1));
AssertEquals("foo.LastIndexOfAny(new char[] {'r','a','B'},foo.Length-2,2)",27,foo.LastIndexOfAny(new char[] {'r','a','B'},foo.Length-2,2));
AssertEquals("foo.LastIndexOfAny(new char[] {'B'},foo.Length-1,foo.Length)",26,foo.LastIndexOfAny(new char[] {'B'},foo.Length-1,foo.Length));
try
{
AssertEquals("foo.LastIndexOfAny(new char[] {'F'},foo.Length,foo.Length)",23, foo.LastIndexOfAny(new char[] {'F'},foo.Length,foo.Length));
}
catch (ArgumentOutOfRangeException)
{
Fail("foo.LastIndexOfAny(new char[] {'F'},foo.Length,foo.Length) should NOT throw an ArgumentOutOfRangeException");
// flashing some leather
}
AssertEquals("foo.LastIndexOfAny(new char[] {'F'},foo.Length-11,foo.Length-10)",0,foo.LastIndexOfAny(new char[] {'F'},foo.Length-11,foo.Length-10));
AssertEquals("foo.LastIndexOfAny(new char[] {'F'},foo.Length-10,foo.Length-10)",-1,foo.LastIndexOfAny(new char[] {'F'},foo.Length-10,foo.Length-10));
AssertEquals("foo.LastIndexOfAny(new char[] {'F'},foo.Length+10,foo.Length)",23,foo.LastIndexOfAny(new char[] {'F'},foo.Length+10,foo.Length));
AssertEquals("foo.LastIndexOfAny(new char[] {'F','o','B','a','r','f','b','u'},foo.Length+10,10)",-1,
foo.LastIndexOfAny(new char[] {'F','o','B','a','r','f','b','u'},foo.Length+10,10));
try
{
foo.LastIndexOfAny((char[])null,0,0);
Fail("foo.LastIndexOfAny((char[])null,0,0) should throw an ArgumentNullException");
}
catch (ArgumentNullException)
{
// all good here
}
try
{
foo.LastIndexOfAny(new char[] {'r','a','B'},-1,0);
Fail("foo.LastIndexOfAny(new char[] {'r','a','B'},-1,0); should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// and here
}
try
{
foo.LastIndexOfAny(new char[] {'r','a','B'},0,-1);
Fail("foo.LastIndexOfAny(new char[] {'r','a','B'},0,-1); should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// and here too
}
try
{
foo.LastIndexOfAny(new char[] {'r','a','B'},0,2);
Fail("foo.LastIndexOfAny(new char[] {'r','a','B'},0,2); should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// and here as well
}
}
public void TestStringPadLeft()
{
String foo = "FooBar";
/* String.PadLeft(int) */
AssertEquals("foo.PadLeft(foo.Length)",foo,foo.PadLeft(foo.Length));
AssertEquals("foo.PadLeft(foo.Length+1)",(" FooBar"),foo.PadLeft(foo.Length+1));
AssertEquals("foo.PadLeft(foo.Length-1)",foo,foo.PadLeft(foo.Length-1));
AssertEquals("foo.PadLeft(0)",foo,foo.PadLeft(0));
try
{
foo.PadLeft(-1);
Fail("foo.PadLeft(-1) should throw an ArgumentException");
}
catch (ArgumentException)
{
// range check works
}
/* String.PadLeft(int,char) */
AssertEquals("foo.PadLeft(foo.Length,'_')",foo,foo.PadLeft(foo.Length,'_'));
AssertEquals("foo.PadLeft(foo.Length+1,'_')",("_FooBar"),foo.PadLeft(foo.Length+1,'_'));
AssertEquals("foo.PadLeft(foo.Length-1,'_')",foo,foo.PadLeft(foo.Length-1,'_'));
AssertEquals("foo.PadLeft(0,'_')",foo,foo.PadLeft(0,'_'));
try
{
foo.PadLeft(-1,'_');
Fail("foo.PadLeft(-1,'_') should throw an ArgumentException");
}
catch (ArgumentException)
{
// range check works here too
}
}
public void TestStringPadRight()
{
String foo = "FooBar";
/* String.PadRight(int) */
AssertEquals("foo.PadRight(foo.Length)",foo,foo.PadRight(foo.Length));
AssertEquals("foo.PadRight(foo.Length+1)",("FooBar "),foo.PadRight(foo.Length+1));
AssertEquals("foo.PadRight(foo.Length-1)",foo,foo.PadRight(foo.Length-1));
AssertEquals("foo.PadRight(0)",foo,foo.PadRight(0));
try
{
foo.PadRight(-1);
Fail("foo.PadRight(-1) should throw an ArgumentException");
}
catch (ArgumentException)
{
// range check works
}
/* String.PadRight(int,char) */
AssertEquals("foo.PadRight(foo.Length,'_')",foo,foo.PadRight(foo.Length,'_'));
AssertEquals("foo.PadRight(foo.Length+1,'_')",("FooBar_"),foo.PadRight(foo.Length+1,'_'));
AssertEquals("foo.PadRight(foo.Length-1,'_')",foo,foo.PadRight(foo.Length-1,'_'));
AssertEquals("foo.PadRight(0,'_')",foo,foo.PadRight(0,'_'));
try
{
foo.PadRight(-1,'_');
Fail("foo.PadRight(-1,'_') should throw an ArgumentException");
}
catch (ArgumentException)
{
// range check works here too
}
}
public void TestStringRemove()
{
String foo = "Foo Bar";
AssertEquals("foo.Remove(0,foo.Length)","",foo.Remove(0,foo.Length));
AssertEquals("foo.Remove(1,foo.Length-1)","F",foo.Remove(1,foo.Length-1));
AssertEquals("foo.Remove(0,1)","oo Bar",foo.Remove(0,1));
AssertEquals("foo.Remove(0,0)",foo,foo.Remove(0,0));
AssertEquals("foo.Remove(foo.Length,0)",foo,foo.Remove(foo.Length,0));
AssertEquals("foo.Remove(3,1)","FooBar",foo.Remove(3,1));
AssertEquals("foo.Remove(foo.Length-1,1)","Foo Ba",foo.Remove(foo.Length-1,1));
try
{
foo.Remove(-1,0);
Fail("foo.Remove(-1,0) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// blah
}
try
{
foo.Remove(0,-1);
Fail("foo.Remove(0,-1) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// blah blah
}
try
{
foo.Remove(0,foo.Length+1);
Fail("foo.Remove(0,foo.Length+1) should throw an ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException)
{
// blah blah blah
}
}
public void TestStringReplace()
{
String foo = "Foo Bar";
/* String.Replace(char,char) */
AssertEquals("foo.Replace('F','f')","foo Bar",foo.Replace('F','f'));
AssertEquals("foo.Replace(' ','_')","Foo_Bar",foo.Replace(' ','_'));
AssertEquals("foo.Replace('r','R')","Foo BaR",foo.Replace('r','R'));
AssertEquals("foo.Replace('_',' ')",foo,foo.Replace('_',' '));
/* String.Replace(String,String) */
AssertEquals("foo.Replace(\"Foo\",\"Fu\")","Fu Bar",foo.Replace("Foo","Fu"));
AssertEquals("foo.Replace(\"Fu\",\"Foo\")",foo,foo.Replace("Fu","Foo"));
AssertEquals("foo.Replace(\"Foo Bar\",\"\")","",foo.Replace("Foo Bar",""));
AssertEquals("foo.Replace(\"Foo Bar\",null)","",foo.Replace("Foo Bar",null));
// Behavior changed by MS in 2.0 (Rich: they want to keep us busy)
try
{
foo.Replace(null,"Foo Bar");
Fail("foo.Replace(null,\"Foo Bar\") should have thrown an ArgumentNullException");
}
catch(ArgumentNullException)
{
// SUCCESS
}
}
public void TestStringSubstring()
{
// if you pass Length, SHOULD NOT THROW!
// per ECMA spec
try
{
"x".Substring(1, 0);
"x".Substring(1);
}
catch (ArgumentOutOfRangeException)
{
Fail("Substring should not throw when passed Length as the startIndex!");
}
}
public void TestStringop_Equality()
{
String foo = "Foo Bar";
String fu = "Fu Bar";
Assert("!(foo == fu)",!(foo == fu));
Assert("foo == foo",foo == foo);
Assert("fu == fu",fu == fu);
Assert("foo == String.Copy(foo)",foo == String.Copy(foo));
Assert("fu == String.Copy(fu)",fu == String.Copy(fu));
}
public void TestStringop_Inequality()
{
String foo = "Foo Bar";
String fu = "Fu Bar";
Assert("foo != fu",foo != fu);
Assert("!(foo != foo)",!(foo != foo));
Assert("!(fu != fu)",!(fu != fu));
Assert("!(foo != String.Copy(foo))",!(foo != String.Copy(foo)));
Assert("!(fu != String.Copy(fu))",!(fu != String.Copy(fu)));
}
public void TestStringChars()
{
char[] fu = new char[] { 'F', 'o', 'o', ' ', 'B', 'a', 'r' };
String foo = new String(fu);
for (int i = 0; i < foo.Length; i++)
{
Assert("foo["+i+"] == fu["+i+"]",foo[i] == fu[i]);
}
try
{
int i = foo[-1];
Fail("foo[-1] should throw an IndexOutOfRangeException");
}
catch (IndexOutOfRangeException)
{
// works here
}
try
{
int i = foo[foo.Length];
Fail("foo[foo.Length] should throw an IndexOutOfRangeException");
}
catch (IndexOutOfRangeException)
{
// and here
}
try
{
int i = foo[foo.Length+1];
Fail("foo[foo.Length+1] should throw an IndexOutOfRangeException");
}
catch (IndexOutOfRangeException)
{
// and here
}
}
public void TestStringLength()
{
AssertEquals("\"Foo Bar\".Length","Foo Bar".Length,7);
AssertEquals("\"\".Length","".Length,0);
}
}; // class TestString
| |
namespace Microsoft.Protocols.TestSuites.MS_ASCAL
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Request = Microsoft.Protocols.TestSuites.Common.Request;
using Response = Microsoft.Protocols.TestSuites.Common.Response;
using SyncItem = Microsoft.Protocols.TestSuites.Common.DataStructures.Sync;
using SyncStore = Microsoft.Protocols.TestSuites.Common.DataStructures.SyncStore;
/// <summary>
/// This scenario is to test Calendar class elements, which are attached in a Meeting request, when meeting is either accepted, tentative accepted, cancelled or declined.
/// </summary>
[TestClass]
public class S02_MeetingElement : TestSuiteBase
{
#region Test Class initialize and clean up
/// <summary>
/// Initialize the class.
/// </summary>
/// <param name="testContext">VSTS test context.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Clear the class.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test Cases
#region MSASCAL_S02_TC01_MeetingAccepted
/// <summary>
/// This case is designed to verify ResponseType, AttendeeStatus, Name, Email, AppointmentReplyTime , BusyStatus, MeetingStatus and AttendeeType when recipient accepts the meeting.
/// </summary>
[TestCategory("MSASCAL"), TestMethod()]
public void MSASCAL_S02_TC01_MeetingAccepted()
{
#region Organizer calls Sync command to add a calendar to the server, and sync calendars from the server.
Dictionary<Request.ItemsChoiceType8, object> calendarItem = new Dictionary<Request.ItemsChoiceType8, object>
{
{
Request.ItemsChoiceType8.BusyStatus, (byte)0
},
{
Request.ItemsChoiceType8.MeetingStatus, (byte)1
},
{
Request.ItemsChoiceType8.Attendees,
TestSuiteHelper.CreateAttendeesRequired(
new string[]
{
Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain)
},
new string[]
{
this.User2Information.UserName
})
}
};
string subject = Common.GenerateResourceName(Site, "subject");
calendarItem.Add(Request.ItemsChoiceType8.Subject, subject);
this.AddSyncCalendar(calendarItem);
SyncItem calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
this.RecordCaseRelativeItems(this.User1Information.UserName, this.User1Information.CalendarCollectionId, subject);
#endregion
#region Organizer sends the meeting request to attendee.
this.SendMimeMeeting(calendarOnOrganizer.Calendar, subject, Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain), Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain), "REQUEST", null);
// Sync command to do an initialization Sync, and get the organizer calendars changes before attendee accepting the meeting
calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R11311");
// Verify MS-ASCAL requirement: MS-ASCAL_R11311
Site.CaptureRequirementIfIsTrue(
calendarOnOrganizer.Calendar.Attendees.Attendee[0].AttendeeStatusSpecified,
11311,
@"[In AttendeeStatus] The AttendeeStatus element specifies the attendee's acceptance status.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R568");
// Verify MS-ASCAL requirement: MS-ASCAL_R568
Site.CaptureRequirementIfAreEqual<byte>(
0,
calendarOnOrganizer.Calendar.Attendees.Attendee[0].AttendeeStatus,
568,
@"[In AttendeeStatus] [The value is] 0 [meaning] Response unknown.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R11911");
// Verify MS-ASCAL requirement: MS-ASCAL_R11911
Site.CaptureRequirementIfIsTrue(
calendarOnOrganizer.Calendar.Attendees.Attendee[0].AttendeeTypeSpecified,
11911,
@"[In AttendeeType] The AttendeeType element specifies whether the attendee is required, optional, or a resource.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R573");
// Verify MS-ASCAL requirement: MS-ASCAL_R573
Site.CaptureRequirementIfAreEqual<byte>(
1,
calendarOnOrganizer.Calendar.Attendees.Attendee[0].AttendeeType,
573,
@"[In AttendeeType] [The value is] 1 [meaning] Required.");
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar.BusyStatus, "The BusyStatus element should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R13811");
// Verify MS-ASCAL requirement: MS-ASCAL_R13811
Site.CaptureRequirementIfAreEqual<byte>(
0,
calendarOnOrganizer.Calendar.BusyStatus.Value,
13811,
@"[In BusyStatus] [The value is] 0 [meaning] Free.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R13311");
// Verify MS-ASCAL requirement: MS-ASCAL_R13311
// MS-ASCAL_R13811 can be captured. Along with the logic, MS-ASCAL_R13311 can be captured also.
Site.CaptureRequirement(
13311,
@"[In BusyStatus] The BusyStatus element specifies the busy status of the meeting organizer.");
if (!this.IsActiveSyncProtocolVersion121)
{
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar.ResponseType, "The ResponseType element should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R40111");
// Verify MS-ASCAL requirement: MS-ASCAL_R40111
// If Calendar.ResponseType is not null, it means the server returns the type of response made by the user to a meeting request
Site.CaptureRequirementIfIsNotNull(
calendarOnOrganizer.Calendar.ResponseType.Value,
40111,
@"[In ResponseType] As a top-level element of the Calendar class, the ResponseType<17> element specifies the type of response made by the user to a meeting request.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R410");
// Verify MS-ASCAL requirement: MS-ASCAL_R410
Site.CaptureRequirementIfAreEqual<uint>(
1,
calendarOnOrganizer.Calendar.ResponseType.Value,
410,
@"[In ResponseType] [The value 1 means]Organizer. The current user is the organizer of the meeting and, therefore, no reply is required.");
}
#endregion
#region Switch to attendee to accept the meeting request, and sync calendars from the server.
// Switch to attendee
this.SwitchUser(this.User2Information, true);
// Call Sync command to do an initialization Sync, and get the attendee inbox changes
SyncItem emailItem = GetChangeItem(this.User2Information.InboxCollectionId, subject);
Site.Assert.AreEqual<string>(
subject,
emailItem.Email.Subject,
"The attendee should have received the meeting request.");
// Call Sync command to do an initialization Sync, and get the attendee calendars changes before accepting the meeting
SyncItem calendarOnAttendee = this.GetChangeItem(this.User2Information.CalendarCollectionId, subject);
if (calendarOnAttendee.Calendar != null)
{
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.CalendarCollectionId, subject);
}
else
{
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.InboxCollectionId, subject);
Site.Assert.IsNotNull(calendarOnAttendee.Calendar, "The calendar with subject {0} should exist in server.", subject);
}
// Accept the meeting request and send the respond to organizer
bool isSuccess = this.MeetingResponse(byte.Parse("1"), this.User2Information.InboxCollectionId, emailItem.ServerId, null);
if (isSuccess)
{
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.DeletedItemsCollectionId, subject);
}
else
{
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.InboxCollectionId, subject);
Site.Assert.Fail("MeetingResponse command failed.");
}
this.SendMimeMeeting(calendarOnAttendee.Calendar, subject, Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain), Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain), "REPLY", "ACCEPTED");
// Call Sync command to do an initialization Sync, and get the attendee calendars changes after accepting the meeting
calendarOnAttendee = this.GetChangeItem(this.User2Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnAttendee.Calendar, "The calendar with subject {0} should exist in server.", subject);
if (!this.IsActiveSyncProtocolVersion121)
{
Site.Assert.IsNotNull(calendarOnAttendee.Calendar.ResponseType, "The ResponseType element should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R414");
// Verify MS-ASCAL requirement: MS-ASCAL_R414
Site.CaptureRequirementIfAreEqual<uint>(
3,
calendarOnAttendee.Calendar.ResponseType.Value,
414,
@"[In ResponseType] [The value 3 means] Accepted. The user has accepted the meeting request.");
Site.Assert.IsNotNull(calendarOnAttendee.Calendar.AppointmentReplyTime, "The value of AppointmentReplyTime element should not be null since the attendee has replied this meeting request.");
// Update Location value
SyncStore syncResponse = this.SyncChanges(this.User2Information.CalendarCollectionId);
Dictionary<Request.ItemsChoiceType7, object> changeItem = new Dictionary<Request.ItemsChoiceType7, object>();
string newLocation = Common.GenerateResourceName(Site, "newLocation");
changeItem.Add(Request.ItemsChoiceType7.Location1, newLocation);
changeItem.Add(Request.ItemsChoiceType7.Subject, subject);
this.UpdateCalendarProperty(calendarOnAttendee.ServerId, this.User2Information.CalendarCollectionId, syncResponse.SyncKey, changeItem);
SyncItem newCalendar = this.GetChangeItem(this.User2Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(newCalendar.Calendar, "The updated calendar should be found.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R96");
// Verify MS-ASCAL requirement: MS-ASCAL_R96
Site.CaptureRequirementIfAreEqual<string>(
calendarOnAttendee.Calendar.AppointmentReplyTime.Value.ToString("yyyyMMddTHHmmssZ"),
newCalendar.Calendar.AppointmentReplyTime.Value.ToString("yyyyMMddTHHmmssZ"),
96,
@"[In AppointmentReplyTime] The top-level AppointmentReplyTime element can be ghosted.");
}
#endregion
#region Switch to organizer to call Sync command to sync calendars from the server.
// Switch to organizer
this.SwitchUser(this.User1Information, true);
// Call Sync command to do an initialization Sync, and get the organizer inbox changes
emailItem = this.GetChangeItem(this.User1Information.InboxCollectionId, subject);
Site.Assert.AreEqual<string>(
subject,
emailItem.Email.Subject,
"The organizer should have received the response.");
this.RecordCaseRelativeItems(this.User1Information.UserName, this.User1Information.InboxCollectionId, subject);
// Sync command to do an initialization Sync, and get the organizer calendars changes after attendee accepted the meeting
calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
#endregion
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R570");
// Verify MS-ASCAL requirement: MS-ASCAL_R570
Site.CaptureRequirementIfIsTrue(
calendarOnOrganizer.Calendar.Attendees.Attendee[0].AttendeeStatusSpecified && calendarOnOrganizer.Calendar.Attendees.Attendee[0].AttendeeStatus == 3,
570,
@"[In AttendeeStatus] [The value is] 3 [meaning]Accept.");
}
#endregion
#region MSASCAL_S02_TC02_MeetingDeclined
/// <summary>
/// This test case is designed to verify ResponseType, AttendeeStatus, Name, Email, AppointmentReplyTime , BusyStatus, MeetingStatus and AttendeeType when recipient declines the meeting.
/// </summary>
[TestCategory("MSASCAL"), TestMethod()]
public void MSASCAL_S02_TC02_MeetingDeclined()
{
#region Organizer calls Sync command to add a calendar to the server, and sync calendars from the server.
Dictionary<Request.ItemsChoiceType8, object> calendarItem = new Dictionary<Request.ItemsChoiceType8, object>
{
{
Request.ItemsChoiceType8.BusyStatus, (byte)2
},
{
Request.ItemsChoiceType8.MeetingStatus, (byte)1
}
};
Request.Attendees attendees = TestSuiteHelper.CreateAttendeesRequired(new string[] { Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain) }, new string[] { this.User2Information.UserName });
attendees.Attendee[0].AttendeeType = 2;
attendees.Attendee[0].AttendeeTypeSpecified = true;
calendarItem.Add(Request.ItemsChoiceType8.Attendees, attendees);
if (!this.IsActiveSyncProtocolVersion121)
{
calendarItem.Add(Request.ItemsChoiceType8.ResponseRequested, true);
}
string subject = Common.GenerateResourceName(Site, "subject");
calendarItem.Add(Request.ItemsChoiceType8.Subject, subject);
this.AddSyncCalendar(calendarItem);
SyncItem calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
this.RecordCaseRelativeItems(this.User1Information.UserName, this.User1Information.CalendarCollectionId, subject);
#endregion
#region Organizer sends the meeting request to attendee.
this.SendMimeMeeting(calendarOnOrganizer.Calendar, subject, Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain), Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain), "REQUEST", null);
// Sync command to do an initialization Sync, and get the organizer calendars changes before attendee declining the meeting
calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar.BusyStatus, "The BusyStatus element should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R13813");
// Verify MS-ASCAL requirement: MS-ASCAL_R13813
Site.CaptureRequirementIfAreEqual<byte>(
2,
calendarOnOrganizer.Calendar.BusyStatus.Value,
13813,
@"[In BusyStatus] [The value is] 2 [meaning] Busy.");
if (!this.IsActiveSyncProtocolVersion121)
{
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar.ResponseRequested, "The ResponseRequested element should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R39611");
// Verify MS-ASCAL requirement: MS-ASCAL_R39611
Site.CaptureRequirementIfIsNotNull(
calendarOnOrganizer.Calendar.ResponseRequested.Value,
39611,
@"[In ResponseRequested] The ResponseRequested<16> element specifies whether a response to the meeting request is required.");
}
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R574");
// Verify MS-ASCAL requirement: MS-ASCAL_R574
Site.CaptureRequirementIfAreEqual<byte>(
2,
calendarOnOrganizer.Calendar.Attendees.Attendee[0].AttendeeType,
574,
@"[In AttendeeType] [The value is] 2 [meaning] Optional.");
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar.MeetingStatus, "The MeetingStatus element should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R311");
// Verify MS-ASCAL requirement: MS-ASCAL_R311
Site.CaptureRequirementIfAreEqual<byte>(
1,
calendarOnOrganizer.Calendar.MeetingStatus.Value,
311,
@"[In MeetingStatus][The value 1 means] The event is a meeting and the user is the meeting organizer.");
#endregion
#region Switch to attendee to decline the meeting request, and sync calendars from the server.
// Switch to attendee
this.SwitchUser(this.User2Information, true);
// Call Sync command to do an initialization Sync, and get the attendee inbox changes
SyncItem emailItem = GetChangeItem(this.User2Information.InboxCollectionId, subject);
Site.Assert.AreEqual<string>(
subject,
emailItem.Email.Subject,
"The attendee should have received the meeting request.");
// Call Sync command to do an initialization Sync, and get the attendee calendars changes before declining the meeting
SyncItem calendarOnAttendee = this.GetChangeItem(this.User2Information.CalendarCollectionId, subject);
if (calendarOnAttendee.Calendar == null)
{
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.InboxCollectionId, subject);
Site.Assert.IsNotNull(calendarOnAttendee.Calendar, "The calendar with subject {0} should exist in server.", subject);
}
// Decline the meeting request and send the response to organizer
bool isSuccess = this.MeetingResponse(byte.Parse("3"), this.User2Information.InboxCollectionId, emailItem.ServerId, null);
if (!isSuccess)
{
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.InboxCollectionId, subject);
Site.Assert.Fail("MeetingResponse command failed.");
}
this.SendMimeMeeting(calendarOnAttendee.Calendar, subject, Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain), Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain), "REPLY", "DECLINED");
// Use EmptyFolderContents to empty the Deleted Items folder
this.DeleteAllItems(this.User2Information.DeletedItemsCollectionId);
#endregion
#region Switch to organizer to call Sync command to Sync calendars from the server.
// Switch to organizer
this.SwitchUser(this.User1Information, true);
// Call Sync command to do an initialization Sync, and get the organizer inbox changes
emailItem = this.GetChangeItem(this.User1Information.InboxCollectionId, subject);
Site.Assert.AreEqual<string>(
subject,
emailItem.Email.Subject,
"The organizer should have received the response.");
this.RecordCaseRelativeItems(this.User1Information.UserName, this.User1Information.InboxCollectionId, subject);
// Sync command to do an initialization Sync, and get the organizer calendars changes
calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
#endregion
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R571");
// Verify MS-ASCAL requirement: MS-ASCAL_R571
Site.CaptureRequirementIfIsTrue(
calendarOnOrganizer.Calendar.Attendees.Attendee[0].AttendeeStatusSpecified = true && calendarOnOrganizer.Calendar.Attendees.Attendee[0].AttendeeStatus == 4,
571,
@"[In AttendeeStatus] [The value is] 4 [meaning] Decline.");
}
#endregion
#region MSASCAL_S02_TC03_MeetingTentative
/// <summary>
/// This test case is designed to verify ResponseType, AttendeeStatus, Name, Email, AppointmentReplyTime , BusyStatus, MeetingStatus and AttendeeType when the meeting is tentative.
/// </summary>
[TestCategory("MSASCAL"), TestMethod()]
public void MSASCAL_S02_TC03_MeetingTentative()
{
#region Organizer calls Sync command to add a calendar to the server, and sync calendars from the server.
Dictionary<Request.ItemsChoiceType8, object> calendarItem = new Dictionary<Request.ItemsChoiceType8, object>
{
{
Request.ItemsChoiceType8.BusyStatus, (byte)1
},
{
Request.ItemsChoiceType8.MeetingStatus, (byte)1
}
};
Request.Attendees attendees = TestSuiteHelper.CreateAttendeesRequired(new string[] { Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain) }, new string[] { this.User2Information.UserName });
calendarItem.Add(Request.ItemsChoiceType8.Attendees, attendees);
if (!this.IsActiveSyncProtocolVersion121)
{
calendarItem.Add(Request.ItemsChoiceType8.ResponseRequested, true);
}
string subject = Common.GenerateResourceName(Site, "subject");
calendarItem.Add(Request.ItemsChoiceType8.Subject, subject);
this.AddSyncCalendar(calendarItem);
SyncItem calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
this.RecordCaseRelativeItems(this.User1Information.UserName, this.User1Information.CalendarCollectionId, subject);
#endregion
#region Organizer sends the meeting request to attendee.
this.SendMimeMeeting(calendarOnOrganizer.Calendar, subject, Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain), Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain), "REQUEST", null);
// Sync command to do an initialization Sync, and get the organizer calendars changes before attendee tentative the meeting
calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar.BusyStatus, "The BusyStatus element should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R13812");
// Verify MS-ASCAL requirement: MS-ASCAL_R13812
Site.CaptureRequirementIfAreEqual<byte>(
1,
calendarOnOrganizer.Calendar.BusyStatus.Value,
13812,
@"[In BusyStatus] [The value is] 1 [meaning] Tentative.");
#endregion
#region Switch to attendee to tentative the meeting request, and sync calendars from the server.
// Switch to attendee
this.SwitchUser(this.User2Information, true);
// Call Sync command to do an initialization Sync, and get the attendee inbox changes
SyncItem emailItem = GetChangeItem(this.User2Information.InboxCollectionId, subject);
Site.Assert.AreEqual<string>(
subject,
emailItem.Email.Subject,
"The attendee should have received the meeting request.");
// Call Sync command to do an initialization Sync, and get the attendee calendars changes before the meeting is tentative
SyncItem calendarOnAttendee = this.GetChangeItem(this.User2Information.CalendarCollectionId, subject);
if (calendarOnAttendee.Calendar != null)
{
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.CalendarCollectionId, subject);
}
else
{
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.InboxCollectionId, subject);
Site.Assert.IsNotNull(calendarOnAttendee.Calendar, "The calendar with subject {0} should exist in server.", subject);
}
// Tentatively accept the meeting request and send the response to organizer
bool isSuccess = this.MeetingResponse(byte.Parse("2"), this.User2Information.InboxCollectionId, emailItem.ServerId, null);
if (isSuccess)
{
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.DeletedItemsCollectionId, subject);
}
else
{
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.InboxCollectionId, subject);
Site.Assert.Fail("MeetingResponse command failed.");
}
this.SendMimeMeeting(calendarOnAttendee.Calendar, subject, Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain), Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain), "REPLY", "TENTATIVE");
// Call Sync command to do an initialization Sync, and get the attendee calendars changes after the meeting is tentative
calendarOnAttendee = this.GetChangeItem(this.User2Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnAttendee.Calendar, "The calendar with subject {0} should exist in server.", subject);
Site.Assert.IsNotNull(calendarOnAttendee.Calendar.MeetingStatus, "The MeetingStatus element should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R312");
// Verify MS-ASCAL requirement: MS-ASCAL_R312
Site.CaptureRequirementIfAreEqual<byte>(
3,
calendarOnAttendee.Calendar.MeetingStatus.Value,
312,
@"[In MeetingStatus][The value 3 means] This event is a meeting and the user is not the meeting organizer; the meeting was received from someone else.");
if (!this.IsActiveSyncProtocolVersion121)
{
Site.Assert.IsNotNull(calendarOnAttendee.Calendar.ResponseType, "The ResponseType element should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R412");
// Verify MS-ASCAL requirement: MS-ASCAL_R412
Site.CaptureRequirementIfAreEqual<uint>(
2,
calendarOnAttendee.Calendar.ResponseType.Value,
412,
@"[In ResponseType] [The value 2 means] Tentative. The user is unsure whether he or she will attend.");
}
#endregion
#region Switch to organizer to call Sync command to sync calendars from the server.
// Switch to organizer
this.SwitchUser(this.User1Information, true);
// Call Sync command to do an initialization Sync, and get the organizer inbox changes
emailItem = this.GetChangeItem(this.User1Information.InboxCollectionId, subject);
Site.Assert.AreEqual<string>(
subject,
emailItem.Email.Subject,
"The organizer should have received the response.");
this.RecordCaseRelativeItems(this.User1Information.UserName, this.User1Information.InboxCollectionId, subject);
// Sync command to do an initialization Sync, and get the organizer calendars changes
calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
#endregion
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R569");
// Verify MS-ASCAL requirement: MS-ASCAL_R569
Site.CaptureRequirementIfIsTrue(
calendarOnOrganizer.Calendar.Attendees.Attendee[0].AttendeeStatusSpecified && calendarOnOrganizer.Calendar.Attendees.Attendee[0].AttendeeStatus == 2,
569,
@"[In AttendeeStatus] [The value is] 2 [meaning]Tentative.");
}
#endregion
#region MSASCAL_S02_TC04_MeetingNotResponded
/// <summary>
/// This test case is designed to verify ResponseType, ResponseRequested, AttendeeStatus, Name, Email, AppointmentReplyTime, BusyStatus, MeetingStatus and AttendeeType when recipient respond the meeting with no action.
/// </summary>
[TestCategory("MSASCAL"), TestMethod()]
public void MSASCAL_S02_TC04_MeetingNotResponded()
{
#region Organizer calls Sync command to add a calendar to the server, and sync calendars from the server.
Dictionary<Request.ItemsChoiceType8, object> calendarItem = new Dictionary<Request.ItemsChoiceType8, object>
{
{
Request.ItemsChoiceType8.BusyStatus, (byte)3
},
{
Request.ItemsChoiceType8.MeetingStatus, (byte)1
}
};
Request.Attendees attendees = TestSuiteHelper.CreateAttendeesRequired(new string[] { Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain) }, new string[] { this.User2Information.UserName });
attendees.Attendee[0].AttendeeType = 3;
attendees.Attendee[0].AttendeeTypeSpecified = true;
if (this.IsActiveSyncProtocolVersion121
|| this.IsActiveSyncProtocolVersion140
|| this.IsActiveSyncProtocolVersion141)
{
attendees.Attendee[0].AttendeeStatusSpecified = true;
attendees.Attendee[0].AttendeeStatus = 5;
}
calendarItem.Add(Request.ItemsChoiceType8.Attendees, attendees);
if (!this.IsActiveSyncProtocolVersion121)
{
calendarItem.Add(Request.ItemsChoiceType8.ResponseRequested, true);
}
string subject = Common.GenerateResourceName(Site, "subject");
calendarItem.Add(Request.ItemsChoiceType8.Subject, subject);
this.AddSyncCalendar(calendarItem);
SyncItem calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
this.RecordCaseRelativeItems(this.User1Information.UserName, this.User1Information.CalendarCollectionId, subject);
#endregion
#region Organizer sends the meeting request to attendee.
this.SendMimeMeeting(calendarOnOrganizer.Calendar, subject, Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain), Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain), "REQUEST", null);
// Sync command to do an initialization Sync, and get the organizer calendars changes after the meeting request sent
calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R575");
// Verify MS-ASCAL requirement: MS-ASCAL_R575
Site.CaptureRequirementIfAreEqual<byte>(
3,
calendarOnOrganizer.Calendar.Attendees.Attendee[0].AttendeeType,
575,
@"[In AttendeeType] [The value is] 3 [meaning] Resource.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R13814");
// Verify MS-ASCAL requirement: MS-ASCAL_R13814
Site.CaptureRequirementIfAreEqual<byte>(
3,
calendarOnOrganizer.Calendar.BusyStatus.Value,
13814,
@"[In BusyStatus] [The value is] 3 [meaning] OutofOffice.");
#endregion
#region Switch to attendee to Sync calendars from the server
// Switch to attendee
this.SwitchUser(this.User2Information, true);
// Call Sync command to do an initialization Sync, and get the attendee inbox changes
SyncItem emailItem = GetChangeItem(this.User2Information.InboxCollectionId, subject);
Site.Assert.AreEqual<string>(
subject,
emailItem.Email.Subject,
"The attendee should have received the meeting request.");
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.InboxCollectionId, subject);
// Respond the meeting with no action, only call Sync command to do an initialization Sync, and get the attendee calendars changes
SyncItem calendarOnAttendee = this.GetChangeItem(this.User2Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnAttendee.Calendar, "The calendar with subject {0} should exist in server.", subject);
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.CalendarCollectionId, subject);
if (!this.IsActiveSyncProtocolVersion121)
{
Site.Assert.IsNotNull(calendarOnAttendee.Calendar.ResponseType, "The ResponseType element should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R418");
// Verify MS-ASCAL requirement: MS-ASCAL_R418
Site.CaptureRequirementIfAreEqual<uint>(
5,
calendarOnAttendee.Calendar.ResponseType.Value,
418,
@"[In ResponseType] [The value 5 means] Not Responded. The user has not yet responded to the meeting request.");
}
#endregion
#region Switch to organizer to call Sync command to sync calendars from the server.
// Switch to organizer
this.SwitchUser(this.User1Information, true);
// Sync command to do an initialization Sync, and get the organizer calendars changes
calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
#endregion
if (!this.IsActiveSyncProtocolVersion121)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R52522");
// Verify MS-ASCAL requirement: MS-ASCAL_R52522
// If AppointmentReplyTime is null, it means the server does not return the date and time that the current user responded to the meeting request
Site.CaptureRequirementIfIsNull(
calendarOnOrganizer.Calendar.AppointmentReplyTime,
52522,
@"[In Message Processing Events and Sequencing Rules][The following information pertains to all command responses:] If no action has been taken on a meeting request, the server MUST NOT include the AppointmentReplyTime element as a top-level element in a command response.");
}
if (this.IsActiveSyncProtocolVersion121
|| this.IsActiveSyncProtocolVersion140
|| this.IsActiveSyncProtocolVersion141)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R572");
// Verify MS-ASCAL requirement: MS-ASCAL_R572
Site.CaptureRequirementIfAreEqual<byte>(
5,
calendarOnOrganizer.Calendar.Attendees.Attendee[0].AttendeeStatus,
572,
@"[In AttendeeStatus] [The value is] 5 [meaning] Not responded.");
}
}
#endregion
#region MSASCAL_S02_TC05_MeetingCancellation
/// <summary>
/// This test case is designed to verify element MeetingStatus when meeting is cancelled.
/// </summary>
[TestCategory("MSASCAL"), TestMethod()]
public void MSASCAL_S02_TC05_MeetingCancellation()
{
#region Organizer calls Sync command to add a calendar to the server, and sync calendars from the server.
Dictionary<Request.ItemsChoiceType8, object> calendarItem = new Dictionary<Request.ItemsChoiceType8, object>
{
{
Request.ItemsChoiceType8.MeetingStatus, (byte)5
},
{
Request.ItemsChoiceType8.Attendees,
TestSuiteHelper.CreateAttendeesRequired(
new string[]
{
Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain)
},
new string[]
{
this.User2Information.UserName
})
}
};
if (!this.IsActiveSyncProtocolVersion121)
{
calendarItem.Add(Request.ItemsChoiceType8.ResponseRequested, true);
}
string subject = Common.GenerateResourceName(Site, "subject");
calendarItem.Add(Request.ItemsChoiceType8.Subject, subject);
this.AddSyncCalendar(calendarItem);
SyncItem calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
this.RecordCaseRelativeItems(this.User1Information.UserName, this.User1Information.CalendarCollectionId, subject);
#endregion
#region Organizer sends the meeting request to attendee.
this.SendMimeMeeting(calendarOnOrganizer.Calendar, subject, Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain), Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain), "REQUEST", null);
#endregion
#region Switch to attendee to sync mail and calendars from the server.
// Switch to attendee
this.SwitchUser(this.User2Information, true);
// Call Sync command to do an initialization Sync, and get the attendee inbox changes
SyncItem emailItem = GetChangeItem(this.User2Information.InboxCollectionId, subject);
Site.Assert.AreEqual<string>(
subject,
emailItem.Email.Subject,
"The attendee should have received the meeting request.");
// Respond the meeting with no action, only call Sync command to do an initialization Sync, and get the attendee calendars changes
SyncItem calendarOnAttendee = this.GetChangeItem(this.User2Information.CalendarCollectionId, subject);
if (calendarOnAttendee.Calendar == null)
{
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.InboxCollectionId, subject);
Site.Assert.IsNotNull(calendarOnAttendee.Calendar, "The calendar with subject {0} should exist in server.", subject);
}
#endregion
#region Switch to organizer to send a cancel meeting request.
// Switch to organizer
this.SwitchUser(this.User1Information, true);
this.SendMimeMeeting(calendarOnOrganizer.Calendar, "CANCELLED:" + subject, Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain), Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain), "CANCEL", null);
#endregion
#region Switch to attendee to sync calendars from the server.
// Switch to attendee
this.SwitchUser(this.User2Information, true);
// Call Sync command to do an initialization Sync, and get the attendee inbox changes
emailItem = this.GetChangeItem(this.User2Information.InboxCollectionId, "CANCELLED:" + subject);
Site.Assert.AreEqual<string>(
"CANCELLED:" + subject,
emailItem.Email.Subject,
"The attendee should have received the cancel response.");
// Sync command to do an initialization Sync, and get the attendee calendars changes after organizer cancelled meeting
calendarOnAttendee = this.GetChangeItem(this.User2Information.CalendarCollectionId, "CANCELLED:" + subject);
if (calendarOnAttendee.Calendar != null)
{
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.CalendarCollectionId, "CANCELLED:" + subject);
}
else
{
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.InboxCollectionId, "CANCELLED:" + subject);
Site.Assert.IsNotNull(calendarOnAttendee.Calendar, "The calendar with subject {0} should exist in server.", "CANCELLED:" + subject);
}
// Use EmptyFolderContents to empty the attendee's Inbox folder
this.DeleteAllItems(this.User2Information.InboxCollectionId);
#endregion
Site.Assert.IsNotNull(calendarOnAttendee.Calendar.MeetingStatus, "The MeetingStatus element should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R314");
// Verify MS-ASCAL requirement: MS-ASCAL_R314
Site.CaptureRequirementIfAreEqual<byte>(
7,
calendarOnAttendee.Calendar.MeetingStatus.Value,
314,
@"[In MeetingStatus][The value 7 means] The meeting has been canceled. The user was not the meeting organizer, the meeting was received from someone else.");
#region Switch to organizer to call Sync command to sync calendars from the server.
// Switch to organizer
this.SwitchUser(this.User1Information, true);
// Sync command to do an initialization Sync, and get the organizer calendars changes
calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
#endregion
if (Common.IsRequirementEnabled(313, this.Site))
{
if (this.IsActiveSyncProtocolVersion121
|| this.IsActiveSyncProtocolVersion140
|| this.IsActiveSyncProtocolVersion141
|| this.IsActiveSyncProtocolVersion160
|| this.IsActiveSyncProtocolVersion161)
{
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar.MeetingStatus, "The MeetingStatus element should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R313");
// Verify MS-ASCAL requirement: MS-ASCAL_R313
Site.CaptureRequirementIfAreEqual<byte>(
5,
calendarOnOrganizer.Calendar.MeetingStatus.Value,
313,
@"[In MeetingStatus][The value 5 means] The meeting has been canceled and the user was the meeting organizer.");
}
}
}
#endregion
#region MSASCAL_S02_TC06_ExceptionElements
/// <summary>
/// This test case is designed to verify all elements in Exception.
/// </summary>
[TestCategory("MSASCAL"), TestMethod()]
public void MSASCAL_S02_TC06_ExceptionElements()
{
#region Organizer calls Sync command to add a calendar to the server, and sync calendars from the server.
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The InstanceId element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The InstanceId element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
Site.Assume.AreNotEqual<string>("16.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The recurring calendar item cannot be created when protocol version is set to 16.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
Site.Assume.AreNotEqual<string>("16.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The recurring calendar item cannot be created when protocol version is set to 16.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
Dictionary<Request.ItemsChoiceType8, object> calendarItem = new Dictionary<Request.ItemsChoiceType8, object>();
DateTime exceptionStartTime = this.StartTime.AddDays(2);
DateTime startTimeInException = exceptionStartTime.AddMinutes(15);
DateTime endTimeInException = startTimeInException.AddHours(2);
// Set Calendar StartTime, EndTime elements
calendarItem.Add(Request.ItemsChoiceType8.StartTime, this.StartTime.ToString("yyyyMMddTHHmmssZ"));
calendarItem.Add(Request.ItemsChoiceType8.EndTime, this.EndTime.ToString("yyyyMMddTHHmmssZ"));
// Set Calendar BusyStatus element
calendarItem.Add(Request.ItemsChoiceType8.BusyStatus, (byte)1);
// Set Calendar Attendees element with required sub-element
calendarItem.Add(Request.ItemsChoiceType8.Attendees, TestSuiteHelper.CreateAttendeesRequired(new string[] { Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain) }, new string[] { this.User2Information.UserName }));
// Set Calendar Recurrence element including Occurrence sub-element
byte recurrenceType = byte.Parse("0");
calendarItem.Add(Request.ItemsChoiceType8.Recurrence, this.CreateCalendarRecurrence(recurrenceType, 6, 1));
// Set Calendar Exceptions element
Request.Exceptions exceptions = new Request.Exceptions { Exception = new Request.ExceptionsException[] { } };
List<Request.ExceptionsException> exceptionList = new List<Request.ExceptionsException>();
// Set ExceptionStartTime element in exception
Request.ExceptionsException exception1 = TestSuiteHelper.CreateExceptionRequired(exceptionStartTime.ToString("yyyyMMddTHHmmssZ"));
exception1.StartTime = startTimeInException.ToString("yyyyMMddTHHmmssZ");
exception1.EndTime = endTimeInException.ToString("yyyyMMddTHHmmssZ");
exception1.Attendees = TestSuiteHelper.CreateAttendeesRequired(new string[] { Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain), "[email protected]" }, new string[] { this.User2Information.UserName, "test" }).Attendee;
exception1.Subject = "Calendar Exception";
exception1.Body = TestSuiteHelper.CreateCalendarBody(2, this.Content + "InException");
exception1.BusyStatusSpecified = true;
exception1.BusyStatus = 2;
exception1.Location = "Room 666";
exception1.Reminder = 10;
exceptionList.Add(exception1);
exceptions.Exception = exceptionList.ToArray();
calendarItem.Add(Request.ItemsChoiceType8.Exceptions, exceptions);
string subject = Common.GenerateResourceName(Site, "subject");
calendarItem.Add(Request.ItemsChoiceType8.Subject, subject);
this.AddSyncCalendar(calendarItem);
SyncItem calendar = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendar.Calendar, "The calendar with subject {0} should exist in server.", subject);
this.RecordCaseRelativeItems(this.User1Information.UserName, this.User1Information.CalendarCollectionId, subject);
#endregion
#region Organizer sends the meeting request to attendee.
this.SendMimeMeeting(calendar.Calendar, subject, Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain), Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain), "REQUEST", null);
// Sync command to do an initialization Sync, and get the organizer calendars changes after the meeting request sent
SyncItem calendarOnOrganizer = this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnOrganizer.Calendar, "The calendar with subject {0} should exist in server.", subject);
#endregion
if (!this.IsActiveSyncProtocolVersion121)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R10611");
// Verify MS-ASCAL requirement: MS-ASCAL_R10611
Site.CaptureRequirementIfIsTrue(
calendarOnOrganizer.Calendar.Exceptions.Exception[0].Attendees != null,
10611,
@"[In Attendees] The Attendees element specifies the collection of attendees for the calendar item exception.<2>");
}
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R39211");
// Verify MS-ASCAL requirement: MS-ASCAL_R39211
Site.CaptureRequirementIfIsTrue(
string.IsNullOrEmpty(calendarOnOrganizer.Calendar.Exceptions.Exception[0].Reminder.ToString()) == false,
39211,
@"[In Reminder] The Reminder element specifies the number of minutes before a calendar item exception's start time to display a reminder notice.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R12611");
// Verify MS-ASCAL requirement: MS-ASCAL_R12611
// If Exception.Body is not null, it means the server returns the body text of the calendar item exception
Site.CaptureRequirementIfIsNotNull(
calendarOnOrganizer.Calendar.Exceptions.Exception[0].Body,
12611,
@"[In Body (AirSyncBase Namespace)] The airsyncbase:Body element specifies the body text of the calendar item exception.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R13411");
// Verify MS-ASCAL requirement: MS-ASCAL_R13411
this.Site.CaptureRequirementIfAreEqual<byte?>(
calendar.Calendar.BusyStatus,
calendarOnOrganizer.Calendar.BusyStatus,
13411,
@"[In BusyStatus] A command response has a maximum of one BusyStatus child element per Exception element.");
#region Switch to attendee to accept the meeting request, and sync calendars from the server.
// Switch to attendee
this.SwitchUser(this.User2Information, true);
// Call Sync command to do an initialization Sync, and get the attendee inbox changes
SyncItem emailItem = GetChangeItem(this.User2Information.InboxCollectionId, subject);
Site.Assert.AreEqual<string>(
subject,
emailItem.Email.Subject,
"The attendee should have received the meeting request.");
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.InboxCollectionId, subject);
// Call Sync command to do an initialization Sync, and get the attendee calendars changes before accepting the meeting
SyncItem calendarOnAttendee = this.GetChangeItem(this.User2Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnAttendee.Calendar, "The calendar with subject {0} should exist in server.", subject);
this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.CalendarCollectionId, subject);
// Respond the meeting request
#region Accept the fourth occurrence
this.MeetingResponse(byte.Parse("1"), this.User2Information.CalendarCollectionId, calendarOnAttendee.ServerId, startTimeInException.ToString("yyyy-MM-ddThh:mm:ss.000Z"));
// Call Sync command to do an initialization Sync, and get the attendee calendars changes after accepting the meeting
calendarOnAttendee = this.GetChangeItem(this.User2Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnAttendee.Calendar, "The calendar with subject {0} should exist in server.", subject);
if (!this.IsActiveSyncProtocolVersion121)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R89011");
// Verify MS-ASCAL requirement: MS-ASCAL_R89011
// If Exception.AppointmentReplyTime is not null, it means the server returns the date and time that the user responded to the meeting request exception
Site.CaptureRequirementIfIsNotNull(
calendarOnAttendee.Calendar.Exceptions.Exception[0].AppointmentReplyTime,
89011,
@"[In AppointmentReplyTime] The AppointmentReplyTime element specifies the date and time that the user responded to the meeting request exception.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R40211");
// Verify MS-ASCAL requirement: MS-ASCAL_R40211
Site.CaptureRequirementIfIsTrue(
calendarOnAttendee.Calendar.Exceptions.Exception[0].ResponseTypeSpecified,
40211,
@"[In ResponseType] The ResponseType<18> element specifies the type of response made by the user to a recurring meeting exception.");
}
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R23611");
// Verify MS-ASCAL requirement: MS-ASCAL_R23611
// If Exception.EndTime is not null, it means the server returns the end time of the calendar item exception
Site.CaptureRequirementIfIsNotNull(
calendarOnAttendee.Calendar.Exceptions.Exception[0].EndTime,
23611,
@"[In EndTime] The EndTime element specifies the end time of the calendar item exception.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R29611");
// Verify MS-ASCAL requirement: MS-ASCAL_R29611
// If Exception.Location is not null, it means the server returns the place where the event specified by the calendar item exception occurs
Site.CaptureRequirementIfIsNotNull(
calendarOnAttendee.Calendar.Exceptions.Exception[0].Location,
29611,
@"[In Location] The Location element specifies the place where the event specified by the calendar item exception occurs.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R43511");
// Verify MS-ASCAL requirement: MS-ASCAL_R43511
// If Exception.StartTime is not null, it means the server returns the start time of the calendar item exception
Site.CaptureRequirementIfIsNotNull(
calendarOnAttendee.Calendar.Exceptions.Exception[0].StartTime,
43511,
@"[In StartTime] The StartTime element specifies the start time of the calendar item exception.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R44111");
// Verify MS-ASCAL requirement: MS-ASCAL_R44111
// If Exception.Subject is not null, it means the server returns the subject of the calendar item exception
Site.CaptureRequirementIfAreEqual<string>(
"Calendar Exception".ToLower(CultureInfo.CurrentCulture),
calendarOnAttendee.Calendar.Exceptions.Exception[0].Subject.ToLower(CultureInfo.CurrentCulture),
44111,
@"[In Subject] The Subject element specifies the subject of the calendar item exception.");
if (!this.IsActiveSyncProtocolVersion121 && !this.IsActiveSyncProtocolVersion140)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R30511");
// Verify MS-ASCAL requirement: MS-ASCAL_R30511
Site.CaptureRequirementIfIsTrue(
calendarOnAttendee.Calendar.Exceptions.Exception[0].MeetingStatusSpecified,
30511,
@"[In MeetingStatus] The MeetingStatus element specifies the status of the calendar item exception.");
}
#endregion
#region Decline the fifth occurrence
this.MeetingResponse(byte.Parse("3"), this.User2Information.CalendarCollectionId, calendarOnAttendee.ServerId, startTimeInException.AddDays(1).ToString("yyyy-MM-ddThh:mm:ss.000Z"));
// Call Sync command to do an initialization Sync, and get the attendee calendars changes after accepting the meeting
calendarOnAttendee = this.GetChangeItem(this.User2Information.CalendarCollectionId, subject);
Site.Assert.IsNotNull(calendarOnAttendee.Calendar, "The calendar with subject {0} should exist in server.", subject);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R26111");
// Verify MS-ASCAL requirement: MS-ASCAL_R26111
// If Exceptions element is not null, it means the server returns a collection of exceptions to the recurrence pattern of the calendar item
Site.CaptureRequirementIfIsNotNull(
calendarOnAttendee.Calendar.Exceptions,
26111,
@"[In Exceptions] The Exceptions element specifies a collection of exceptions to the recurrence pattern of the calendar item.");
foreach (Response.ExceptionsException exception in calendarOnAttendee.Calendar.Exceptions.Exception)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R24111");
// Verify MS-ASCAL requirement: MS-ASCAL_R24111
// If Exceptions.Exception is not null, it means the server returns an exception to the calendar item's recurrence pattern
Site.CaptureRequirementIfIsNotNull(
exception,
24111,
@"[In Exception] The Exception element specifies an exception to the calendar item's recurrence pattern.");
}
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R20611");
// Verify MS-ASCAL requirement: MS-ASCAL_R20611
Site.CaptureRequirementIfIsTrue(
calendarOnAttendee.Calendar.Exceptions.Exception[0].DeletedSpecified,
20611,
@"[In Deleted] The Deleted element specifies whether the exception to the calendar item has been deleted.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R20811");
// Verify MS-ASCAL requirement: MS-ASCAL_R20811
Site.CaptureRequirementIfIsTrue(
calendarOnAttendee.Calendar.Exceptions.Exception[0].DeletedSpecified,
20811,
@"[In Deleted] A command response has a maximum of one Deleted child element per Exception element.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R210");
// Verify MS-ASCAL requirement: MS-ASCAL_R210
Site.CaptureRequirementIfAreEqual<byte>(
1,
calendarOnAttendee.Calendar.Exceptions.Exception[0].Deleted,
210,
@"[In Deleted] An exception will be deleted when the Deleted element is included as a child element of the Exception element with a value of 1.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R525221");
// Verify MS-ASCAL requirement: MS-ASCAL_R525221
// If Exception.AppointmentReplyTime is null, it means the server does not return the date and time that the user responded to the meeting request exception
Site.CaptureRequirementIfIsNull(
calendarOnAttendee.Calendar.Exceptions.Exception[0].AppointmentReplyTime,
525221,
@"[In Message Processing Events and Sequencing Rules][The following information pertains to all command responses:] If a meeting request exception has not been accepted, the server MUST NOT include the AppointmentReplyTime element as a child element of the Exception element in a command response.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCAL_R52522111");
// Verify MS-ASCAL requirement: MS-ASCAL_R52522111
// If Exception.AppointmentReplyTime is null, it means the server does not return the date and time that the user responded to the meeting request exception
Site.CaptureRequirementIfIsNull(
calendarOnAttendee.Calendar.Exceptions.Exception[0].AppointmentReplyTime,
52522111,
@"[In Message Processing Events and Sequencing Rules][The following information pertains to all command responses:] If a meeting request exception has not been tentatively accepted, the server MUST NOT include the AppointmentReplyTime element as a child element of the Exception element in a command response.");
#endregion
#endregion
#region Switch to organizer to call Sync command to sync calendars from the server.
// Switch to organizer
this.SwitchUser(this.User1Information, false);
// Sync command to do an initialization Sync, and get the organizer calendars changes
this.GetChangeItem(this.User1Information.CalendarCollectionId, subject);
#endregion
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall.Instructions.Reflection;
using System.Reflection;
#if !FRB_MDX
using System.Linq;
#endif
namespace FlatRedBall.Instructions
{
#region XML Docs
/// <summary>
/// Provides an interface for objects which can store Instructions.
/// </summary>
#endregion
public interface IInstructable
{
#region XML Docs
/// <summary>
/// The list of Instructions that this instance owns. These instructions usually
/// will execute on this instance; however, this is not a requirement.
/// </summary>
#endregion
InstructionList Instructions
{
get;
}
}
internal struct SetHolder<T> : ISet, ITo, IAfter where T : IInstructable
{
enum SetOrCall
{
Set,
Call
}
SetOrCall mSetOrCall;
internal T Caller;
internal string MemberToSet;
internal object ValueToSet;
internal Action Action;
internal Action<T> ActionT;
internal Type type;
public IAfter Call(Action Action)
{
this.Action = Action;
mSetOrCall = SetOrCall.Call;
return this;
}
public IAfter Call(Action<T> Action)
{
this.ActionT = Action;
mSetOrCall = SetOrCall.Call;
return this;
}
public ITo Set(string memberToSet)
{
MemberToSet = memberToSet;
mSetOrCall = SetOrCall.Set;
return this;
}
public IAfter To(object value)
{
// Assigning a float value to
// an int (like passing 0 instead
// of 0.0f) is a common problem. We
// should do some checks here to let the
// user know that something is wrong before
// the instruction fires and throws an error.
// that makes the bug easier to fix.
#if DEBUG && !FRB_MDX && !WINDOWS_8 && !UWP
var fields = typeof(T).GetFields();
var properties = typeof(T).GetProperties();
string memberToSet = this.MemberToSet;
var foundField = fields.FirstOrDefault(field => field.Name == memberToSet);
var foundProperty = properties.FirstOrDefault(property => property.Name == memberToSet);
if (foundField == null && foundProperty == null)
{
throw new Exception("The type " + typeof(T) + " does not have a public field or property named " + memberToSet);
}
else
{
Type type;
if (foundField != null)
{
type = foundField.FieldType;
}
else
{
type = foundProperty.PropertyType;
}
if (value != null && !type.IsAssignableFrom(value.GetType()))
{
// let's handle special cases and be more informative
if (value is int && type == typeof(float))
{
throw new Exception("You must set a float value. For example use 0.0f instead of 0.");
}
else
{
throw new Exception("The type " + value + " is invalid");
}
}
}
#endif
this.ValueToSet = value;
return this;
}
public Instruction After(double time)
{
Instruction toReturn;
if (mSetOrCall == SetOrCall.Set)
{
Type memberType = GetMemberType(MemberToSet);
Type instructionType = typeof(Instruction<,>).MakeGenericType(typeof(T), memberType);
GenericInstruction instruction = (GenericInstruction)Activator.CreateInstance(instructionType);
instruction.TimeToExecute = TimeManager.CurrentTime + time;
instruction.SetTarget(Caller);
instruction.Member = MemberToSet;
instruction.MemberValueAsObject = ValueToSet;
toReturn = instruction;
}
else if (ActionT != null)
{
DelegateInstruction<T> delegateInstruction = new DelegateInstruction<T>(ActionT, Caller);
delegateInstruction.TimeToExecute = TimeManager.CurrentTime + time;
toReturn = delegateInstruction;
}
else
{
DelegateInstruction delegateInstruction = new DelegateInstruction(Action);
delegateInstruction.TimeToExecute = TimeManager.CurrentTime + time;
toReturn = delegateInstruction;
}
Caller.Instructions.Add(toReturn);
return toReturn;
}
Type GetMemberType(string memberName)
{
FieldInfo fieldInfo = typeof(T).GetField(memberName);
if (fieldInfo != null)
{
return fieldInfo.FieldType;
}
else
{
PropertyInfo propertyInfo = typeof(T).GetProperty(memberName);
if (propertyInfo != null)
{
return propertyInfo.PropertyType;
}
}
throw new Exception("The value " + memberName + " is an invalid member");
}
}
public interface ISet
{
ITo Set(string memberToSet);
}
public interface ITo
{
IAfter To(object value);
}
public interface IAfter
{
Instruction After(double time);
}
public static class InstructionExtensionMethods
{
public static IAfter Call<T>(this T caller, Action action) where T : IInstructable
{
SetHolder<T> holder = new SetHolder<T>();
holder.Caller = caller;
return holder.Call(action);
}
public static IAfter Call<T>(this T caller, Action<T> action) where T : IInstructable
{
SetHolder<T> holder = new SetHolder<T>();
holder.Caller = caller;
return holder.Call(action);
}
public static ITo Set<T>(this T caller, string value) where T : IInstructable
{
SetHolder<T> holder = new SetHolder<T>();
holder.Caller = caller;
return holder.Set(value);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Text;
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
//
// Property Default Description
// PositiveSign '+' Character used to indicate positive values.
// NegativeSign '-' Character used to indicate negative values.
// NumberDecimalSeparator '.' The character used as the decimal separator.
// NumberGroupSeparator ',' The character used to separate groups of
// digits to the left of the decimal point.
// NumberDecimalDigits 2 The default number of decimal places.
// NumberGroupSizes 3 The number of digits in each group to the
// left of the decimal point.
// NaNSymbol "NaN" The string used to represent NaN values.
// PositiveInfinitySymbol"Infinity" The string used to represent positive
// infinities.
// NegativeInfinitySymbol"-Infinity" The string used to represent negative
// infinities.
//
//
//
// Property Default Description
// CurrencyDecimalSeparator '.' The character used as the decimal
// separator.
// CurrencyGroupSeparator ',' The character used to separate groups
// of digits to the left of the decimal
// point.
// CurrencyDecimalDigits 2 The default number of decimal places.
// CurrencyGroupSizes 3 The number of digits in each group to
// the left of the decimal point.
// CurrencyPositivePattern 0 The format of positive values.
// CurrencyNegativePattern 0 The format of negative values.
// CurrencySymbol "$" String used as local monetary symbol.
//
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class NumberFormatInfo : IFormatProvider
{
// invariantInfo is constant irrespective of your current culture.
private static volatile NumberFormatInfo invariantInfo;
// READTHIS READTHIS READTHIS
// This class has an exact mapping onto a native structure defined in COMNumber.cpp
// DO NOT UPDATE THIS WITHOUT UPDATING THAT STRUCTURE. IF YOU ADD BOOL, ADD THEM AT THE END.
// ALSO MAKE SURE TO UPDATE mscorlib.h in the VM directory to check field offsets.
// READTHIS READTHIS READTHIS
internal int[] numberGroupSizes = new int[] { 3 };
internal int[] currencyGroupSizes = new int[] { 3 };
internal int[] percentGroupSizes = new int[] { 3 };
internal String positiveSign = "+";
internal String negativeSign = "-";
internal String numberDecimalSeparator = ".";
internal String numberGroupSeparator = ",";
internal String currencyGroupSeparator = ",";
internal String currencyDecimalSeparator = ".";
internal String currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund.
internal String nanSymbol = "NaN";
internal String positiveInfinitySymbol = "Infinity";
internal String negativeInfinitySymbol = "-Infinity";
internal String percentDecimalSeparator = ".";
internal String percentGroupSeparator = ",";
internal String percentSymbol = "%";
internal String perMilleSymbol = "\u2030";
internal String[] nativeDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
internal int numberDecimalDigits = 2;
internal int currencyDecimalDigits = 2;
internal int currencyPositivePattern = 0;
internal int currencyNegativePattern = 0;
internal int numberNegativePattern = 1;
internal int percentPositivePattern = 0;
internal int percentNegativePattern = 0;
internal int percentDecimalDigits = 2;
internal bool isReadOnly = false;
// Is this NumberFormatInfo for invariant culture?
internal bool m_isInvariant = false;
public NumberFormatInfo() : this(null)
{
}
static private void VerifyDecimalSeparator(String decSep, String propertyName)
{
if (decSep == null)
{
throw new ArgumentNullException(propertyName,
SR.ArgumentNull_String);
}
if (decSep.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyDecString);
}
Contract.EndContractBlock();
}
static private void VerifyGroupSeparator(String groupSep, String propertyName)
{
if (groupSep == null)
{
throw new ArgumentNullException(propertyName,
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
}
[System.Security.SecuritySafeCritical] // auto-generated
internal NumberFormatInfo(CultureData cultureData)
{
if (cultureData != null)
{
// We directly use fields here since these data is coming from data table or Win32, so we
// don't need to verify their values (except for invalid parsing situations).
cultureData.GetNFIValues(this);
if (cultureData.IsInvariantCulture)
{
// For invariant culture
this.m_isInvariant = true;
}
}
}
[Pure]
private void VerifyWritable()
{
if (isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
Contract.EndContractBlock();
}
// Returns a default NumberFormatInfo that will be universally
// supported and constant irrespective of the current culture.
// Used by FromString methods.
//
public static NumberFormatInfo InvariantInfo
{
get
{
if (invariantInfo == null)
{
// Lazy create the invariant info. This cannot be done in a .cctor because exceptions can
// be thrown out of a .cctor stack that will need this.
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.m_isInvariant = true;
invariantInfo = ReadOnly(nfi);
}
return invariantInfo;
}
}
public static NumberFormatInfo GetInstance(IFormatProvider formatProvider)
{
// Fast case for a regular CultureInfo
NumberFormatInfo info;
CultureInfo cultureProvider = formatProvider as CultureInfo;
if (cultureProvider != null && !cultureProvider.m_isInherited)
{
info = cultureProvider.numInfo;
if (info != null)
{
return info;
}
else
{
return cultureProvider.NumberFormat;
}
}
// Fast case for an NFI;
info = formatProvider as NumberFormatInfo;
if (info != null)
{
return info;
}
if (formatProvider != null)
{
info = formatProvider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo;
if (info != null)
{
return info;
}
}
return CurrentInfo;
}
public Object Clone()
{
NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone();
n.isReadOnly = false;
return n;
}
public int CurrencyDecimalDigits
{
get { return currencyDecimalDigits; }
set
{
if (value < 0 || value > 99)
{
throw new ArgumentOutOfRangeException(
"CurrencyDecimalDigits",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
currencyDecimalDigits = value;
}
}
public String CurrencyDecimalSeparator
{
get { return currencyDecimalSeparator; }
set
{
VerifyWritable();
VerifyDecimalSeparator(value, "CurrencyDecimalSeparator");
currencyDecimalSeparator = value;
}
}
public bool IsReadOnly
{
get
{
return isReadOnly;
}
}
//
// Check the values of the groupSize array.
//
// Every element in the groupSize array should be between 1 and 9
// excpet the last element could be zero.
//
static internal void CheckGroupSize(String propName, int[] groupSize)
{
for (int i = 0; i < groupSize.Length; i++)
{
if (groupSize[i] < 1)
{
if (i == groupSize.Length - 1 && groupSize[i] == 0)
return;
throw new ArgumentException(SR.Argument_InvalidGroupSize, propName);
}
else if (groupSize[i] > 9)
{
throw new ArgumentException(SR.Argument_InvalidGroupSize, propName);
}
}
}
public int[] CurrencyGroupSizes
{
get
{
return ((int[])currencyGroupSizes.Clone());
}
set
{
if (value == null)
{
throw new ArgumentNullException("CurrencyGroupSizes",
SR.ArgumentNull_Obj);
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize("CurrencyGroupSizes", inputSizes);
currencyGroupSizes = inputSizes;
}
}
public int[] NumberGroupSizes
{
get
{
return ((int[])numberGroupSizes.Clone());
}
set
{
if (value == null)
{
throw new ArgumentNullException("NumberGroupSizes",
SR.ArgumentNull_Obj);
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize("NumberGroupSizes", inputSizes);
numberGroupSizes = inputSizes;
}
}
public int[] PercentGroupSizes
{
get
{
return ((int[])percentGroupSizes.Clone());
}
set
{
if (value == null)
{
throw new ArgumentNullException("PercentGroupSizes",
SR.ArgumentNull_Obj);
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize("PercentGroupSizes", inputSizes);
percentGroupSizes = inputSizes;
}
}
public String CurrencyGroupSeparator
{
get { return currencyGroupSeparator; }
set
{
VerifyWritable();
VerifyGroupSeparator(value, "CurrencyGroupSeparator");
currencyGroupSeparator = value;
}
}
public String CurrencySymbol
{
get { return currencySymbol; }
set
{
if (value == null)
{
throw new ArgumentNullException("CurrencySymbol",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
currencySymbol = value;
}
}
// Returns the current culture's NumberFormatInfo. Used by Parse methods.
//
public static NumberFormatInfo CurrentInfo
{
get
{
System.Globalization.CultureInfo culture = CultureInfo.CurrentCulture;
if (!culture.m_isInherited)
{
NumberFormatInfo info = culture.numInfo;
if (info != null)
{
return info;
}
}
return ((NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo)));
}
}
public String NaNSymbol
{
get
{
return nanSymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException("NaNSymbol",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
nanSymbol = value;
}
}
public int CurrencyNegativePattern
{
get { return currencyNegativePattern; }
set
{
if (value < 0 || value > 15)
{
throw new ArgumentOutOfRangeException(
"CurrencyNegativePattern",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
15));
}
Contract.EndContractBlock();
VerifyWritable();
currencyNegativePattern = value;
}
}
public int NumberNegativePattern
{
get { return numberNegativePattern; }
set
{
//
// NOTENOTE: the range of value should correspond to negNumberFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 4)
{
throw new ArgumentOutOfRangeException(
"NumberNegativePattern",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
4));
}
Contract.EndContractBlock();
VerifyWritable();
numberNegativePattern = value;
}
}
public int PercentPositivePattern
{
get { return percentPositivePattern; }
set
{
//
// NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 3)
{
throw new ArgumentOutOfRangeException(
"PercentPositivePattern",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
3));
}
Contract.EndContractBlock();
VerifyWritable();
percentPositivePattern = value;
}
}
public int PercentNegativePattern
{
get { return percentNegativePattern; }
set
{
//
// NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 11)
{
throw new ArgumentOutOfRangeException(
"PercentNegativePattern",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
11));
}
Contract.EndContractBlock();
VerifyWritable();
percentNegativePattern = value;
}
}
public String NegativeInfinitySymbol
{
get
{
return negativeInfinitySymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException("NegativeInfinitySymbol",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
negativeInfinitySymbol = value;
}
}
public String NegativeSign
{
get { return negativeSign; }
set
{
if (value == null)
{
throw new ArgumentNullException("NegativeSign",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
negativeSign = value;
}
}
public int NumberDecimalDigits
{
get { return numberDecimalDigits; }
set
{
if (value < 0 || value > 99)
{
throw new ArgumentOutOfRangeException(
"NumberDecimalDigits",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
numberDecimalDigits = value;
}
}
public String NumberDecimalSeparator
{
get { return numberDecimalSeparator; }
set
{
VerifyWritable();
VerifyDecimalSeparator(value, "NumberDecimalSeparator");
numberDecimalSeparator = value;
}
}
public String NumberGroupSeparator
{
get { return numberGroupSeparator; }
set
{
VerifyWritable();
VerifyGroupSeparator(value, "NumberGroupSeparator");
numberGroupSeparator = value;
}
}
public int CurrencyPositivePattern
{
get { return currencyPositivePattern; }
set
{
if (value < 0 || value > 3)
{
throw new ArgumentOutOfRangeException(
"CurrencyPositivePattern",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
3));
}
Contract.EndContractBlock();
VerifyWritable();
currencyPositivePattern = value;
}
}
public String PositiveInfinitySymbol
{
get
{
return positiveInfinitySymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException("PositiveInfinitySymbol",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
positiveInfinitySymbol = value;
}
}
public String PositiveSign
{
get { return positiveSign; }
set
{
if (value == null)
{
throw new ArgumentNullException("PositiveSign",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
positiveSign = value;
}
}
public int PercentDecimalDigits
{
get { return percentDecimalDigits; }
set
{
if (value < 0 || value > 99)
{
throw new ArgumentOutOfRangeException(
"PercentDecimalDigits",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
percentDecimalDigits = value;
}
}
public String PercentDecimalSeparator
{
get { return percentDecimalSeparator; }
set
{
VerifyWritable();
VerifyDecimalSeparator(value, "PercentDecimalSeparator");
percentDecimalSeparator = value;
}
}
public String PercentGroupSeparator
{
get { return percentGroupSeparator; }
set
{
VerifyWritable();
VerifyGroupSeparator(value, "PercentGroupSeparator");
percentGroupSeparator = value;
}
}
public String PercentSymbol
{
get
{
return percentSymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException("PercentSymbol",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
percentSymbol = value;
}
}
public String PerMilleSymbol
{
get { return perMilleSymbol; }
set
{
if (value == null)
{
throw new ArgumentNullException("PerMilleSymbol",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
perMilleSymbol = value;
}
}
public Object GetFormat(Type formatType)
{
return formatType == typeof(NumberFormatInfo) ? this : null;
}
public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi)
{
if (nfi == null)
{
throw new ArgumentNullException("nfi");
}
Contract.EndContractBlock();
if (nfi.IsReadOnly)
{
return (nfi);
}
NumberFormatInfo info = (NumberFormatInfo)(nfi.MemberwiseClone());
info.isReadOnly = true;
return info;
}
// private const NumberStyles InvalidNumberStyles = unchecked((NumberStyles) 0xFFFFFC00);
private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
| NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign
| NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint
| NumberStyles.AllowThousands | NumberStyles.AllowExponent
| NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier);
internal static void ValidateParseStyleInteger(NumberStyles style)
{
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0)
{
throw new ArgumentException(SR.Argument_InvalidNumberStyles, "style");
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // Check for hex number
if ((style & ~NumberStyles.HexNumber) != 0)
{
throw new ArgumentException(SR.Arg_InvalidHexStyle);
}
}
}
internal static void ValidateParseStyleFloatingPoint(NumberStyles style)
{
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0)
{
throw new ArgumentException(SR.Argument_InvalidNumberStyles, "style");
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // Check for hex number
throw new ArgumentException(SR.Arg_HexStyleNotSupported);
}
}
} // NumberFormatInfo
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Globalization;
using Microsoft.Win32;
namespace WinConsole
{
/// <summary>
/// Extended console for both Windows and Console Applications.
/// </summary>
public class WinConsole
{
#region Construction
private WinConsole()
{
Initialize();
}
#endregion
#region Windows API
[DllImport("user32")]
static extern void FlashWindowEx(ref FlashWInfo info);
[DllImport("user32")]
static extern void MessageBeep(int type);
[DllImport("user32")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int newValue);
[DllImport("user32")]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("kernel32")]
static extern bool AllocConsole();
[DllImport("kernel32")]
static extern bool FreeConsole();
[DllImport("kernel32")]
static extern bool GetConsoleScreenBufferInfo(IntPtr consoleOutput, out ConsoleScreenBufferInfo info);
[DllImport("kernel32")]
static extern bool GetConsoleTitle(StringBuilder text, int size);
[DllImport("kernel32")]
static extern IntPtr GetConsoleWindow();
[DllImport("kernel32")]
static extern IntPtr GetStdHandle(int handle);
[DllImport("kernel32")]
static extern int SetConsoleCursorPosition(IntPtr buffer, Coord position);
[DllImport("kernel32")]
static extern int FillConsoleOutputCharacter(IntPtr buffer, char character, int length, Coord position, out int written);
[DllImport("kernel32")]
static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, ConsoleColor wAttributes);
[DllImport("kernel32")]
static extern bool SetConsoleTitle(string lpConsoleTitle);
[DllImport("kernel32")]
static extern bool SetConsoleCtrlHandler(HandlerRoutine routine, bool add);
[DllImport("user32")]
static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
[DllImport("user32")]
static extern bool IsWindowVisible(IntPtr hwnd);
[DllImport("kernel32")]
static extern IntPtr CreateConsoleScreenBuffer(int access, int share, IntPtr security, int flags, IntPtr reserved);
[DllImport("kernel32")]
static extern bool SetConsoleActiveScreenBuffer(IntPtr handle);
[DllImport("kernel32")]
static extern bool WriteConsole(IntPtr handle, string s, int length, out int written, IntPtr reserved);
[DllImport("kernel32")]
static extern int GetConsoleCP();
[DllImport("kernel32")]
static extern int GetConsoleOutputCP();
[DllImport("kernel32")]
static extern bool GetConsoleMode(IntPtr handle, out int flags);
[DllImport("kernel32")]
static extern bool SetStdHandle(int handle1, IntPtr handle2);
[DllImport("user32")]
static extern IntPtr SetParent(IntPtr hwnd, IntPtr hwnd2);
[DllImport("user32")]
static extern IntPtr GetParent(IntPtr hwnd);
[DllImport("user32")]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
int x, int y, int cx, int cy, int flags);
[DllImport("user32")]
static extern bool GetClientRect(IntPtr hWnd, ref RECT rect);
#endregion
#region Constants
const int WS_POPUP = unchecked((int) 0x80000000);
const int WS_OVERLAPPED = 0x0;
const int WS_CHILD = 0x40000000;
const int WS_MINIMIZE = 0x20000000;
const int WS_VISIBLE = 0x10000000;
const int WS_DISABLED = 0x8000000;
const int WS_CLIPSIBLINGS = 0x4000000;
const int WS_CLIPCHILDREN = 0x2000000;
const int WS_MAXIMIZE = 0x1000000;
const int WS_CAPTION = 0xC00000; // WS_BORDER | WS_DLGFRAME
const int WS_BORDER = 0x800000;
const int WS_DLGFRAME = 0x400000;
const int WS_VSCROLL = 0x200000;
const int WS_HSCROLL = 0x100000;
const int WS_SYSMENU = 0x80000;
const int WS_THICKFRAME = 0x40000;
const int WS_GROUP = 0x20000;
const int WS_TABSTOP = 0x10000;
const int WS_MINIMIZEBOX = 0x20000;
const int WS_MAXIMIZEBOX = 0x10000;
const int WS_TILED = WS_OVERLAPPED;
const int WS_ICONIC = WS_MINIMIZE;
const int WS_SIZEBOX = WS_THICKFRAME;
const int WS_OVERLAPPEDWINDOW = (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX);
const int WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW;
const int GWL_STYLE = (-16);
const int SW_HIDE = 0;
const int SW_SHOWNORMAL = 1;
const int SW_NORMAL = 1;
const int SW_SHOWMINIMIZED = 2;
const int SW_SHOWMAXIMIZED = 3;
const int SW_MAXIMIZE = 3;
const int SW_SHOWNOACTIVATE = 4;
const int SW_SHOW = 5;
const int SW_MINIMIZE = 6;
const int SW_SHOWMINNOACTIVE = 7;
const int SW_SHOWNA = 8;
const int SW_RESTORE = 9;
const int SW_SHOWDEFAULT = 10;
const int SW_MAX = 10;
const int EMPTY = 32;
const int CONSOLE_TEXTMODE_BUFFER = 1;
const int FLASHW_STOP = 0;
const int FLASHW_CAPTION = 1;
const int FLASHW_TRAY = 2;
const int FLASHW_ALL = 3;
const int FLASHW_TIMER = 4;
const int FLASHW_TIMERNOFG = 0xc;
const int _DefaultConsoleBufferSize = 256;
const int FOREGROUND_BLUE = 0x1; // text color contains blue.
const int FOREGROUND_GREEN = 0x2; // text color contains green.
const int FOREGROUND_RED = 0x4; // text color contains red.
const int FOREGROUND_INTENSITY = 0x8; // text color is intensified.
const int BACKGROUND_BLUE = 0x10; // background color contains blue.
const int BACKGROUND_GREEN = 0x20; // background color contains green.
const int BACKGROUND_RED = 0x40; // background color contains red.
const int BACKGROUND_INTENSITY = 0x80; // background color is intensified.
const int COMMON_LVB_REVERSE_VIDEO = 0x4000;
const int COMMON_LVB_UNDERSCORE = 0x8000;
const int GENERIC_READ = unchecked((int) 0x80000000);
const int GENERIC_WRITE = 0x40000000;
const int FILE_SHARE_READ = 0x1;
const int FILE_SHARE_WRITE = 0x2;
const int STD_INPUT_HANDLE = -10;
const int STD_OUTPUT_HANDLE = -11;
const int STD_ERROR_HANDLE = -12;
const int SWP_NOSIZE = 0x1;
const int SWP_NOMOVE = 0x2;
const int SWP_NOZORDER = 0x4;
const int SWP_NOREDRAW = 0x8;
const int SWP_NOACTIVATE = 0x10;
#endregion
#region Structures
public delegate bool HandlerRoutine(int type);
struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
} ;
struct ConsoleScreenBufferInfo
{
public Coord Size;
public Coord CursorPosition;
public ConsoleColor Attributes;
public SmallRect Window;
public Coord MaximumWindowSize;
}
public struct ConsoleSelectionInfo
{
public int Flags;
public Coord SelectionAnchor;
public SmallRect Selection;
}
public struct SmallRect
{
public short Left;
public short Top;
public short Right;
public short Bottom;
}
struct FlashWInfo
{
public int Size;
public IntPtr Hwnd;
public int Flags;
public int Count;
public int Timeout;
}
#endregion
#region Variables
static IntPtr buffer;
static bool initialized;
static bool breakHit;
public static event HandlerRoutine Break;
#endregion
#region Properties
/// <summary>
/// Specifies whether the console window should be visible or hidden
/// </summary>
public static bool Visible
{
get
{
IntPtr hwnd = GetConsoleWindow();
return hwnd != IntPtr.Zero && IsWindowVisible(hwnd);
}
set
{
Initialize();
IntPtr hwnd = GetConsoleWindow();
if (hwnd != IntPtr.Zero)
ShowWindow(hwnd, value ? SW_SHOW : SW_HIDE);
}
}
/// <summary>
/// Initializes WinConsole -- should be called at the start of the program using it
/// </summary>
public static void Initialize()
{
if (initialized)
return;
IntPtr hwnd = GetConsoleWindow();
initialized = true;
SetConsoleCtrlHandler(new HandlerRoutine(HandleBreak), true);
// Console app
if (hwnd != IntPtr.Zero)
{
buffer = GetStdHandle(STD_OUTPUT_HANDLE);
return;
}
// Windows app
bool success = AllocConsole();
if (!success)
return;
buffer = CreateConsoleScreenBuffer(GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE, IntPtr.Zero, CONSOLE_TEXTMODE_BUFFER, IntPtr.Zero);
bool result = SetConsoleActiveScreenBuffer(buffer);
SetStdHandle(STD_OUTPUT_HANDLE, buffer);
SetStdHandle(STD_ERROR_HANDLE, buffer);
Title = "Console";
Stream s = Console.OpenStandardInput(_DefaultConsoleBufferSize);
StreamReader reader = null;
if (s==Stream.Null)
reader = StreamReader.Null;
else
reader = new StreamReader(s, Encoding.GetEncoding(GetConsoleCP()),
false, _DefaultConsoleBufferSize);
Console.SetIn(reader);
// Set up Console.Out
StreamWriter writer = null;
s = Console.OpenStandardOutput(_DefaultConsoleBufferSize);
if (s == Stream.Null)
writer = StreamWriter.Null;
else
{
writer = new StreamWriter(s, Encoding.GetEncoding(GetConsoleOutputCP()),
_DefaultConsoleBufferSize);
writer.AutoFlush = true;
}
Console.SetOut(writer);
s = Console.OpenStandardError(_DefaultConsoleBufferSize);
if (s == Stream.Null)
writer = StreamWriter.Null;
else
{
writer = new StreamWriter(s, Encoding.GetEncoding(GetConsoleOutputCP()),
_DefaultConsoleBufferSize);
writer.AutoFlush = true;
}
Console.SetError(writer);
}
/// <summary>
/// Gets or sets the title of the console window
/// </summary>
public static string Title
{
get
{
StringBuilder sb = new StringBuilder(256);
GetConsoleTitle(sb, sb.Capacity);
return sb.ToString();
}
set
{
SetConsoleTitle(value);
}
}
/// <summary>
/// Get the HWND of the console window
/// </summary>
/// <returns></returns>
public static IntPtr Handle
{
get
{
Initialize();
return GetConsoleWindow();
}
}
/// <summary>
/// Gets and sets a new parent hwnd to the console window
/// </summary>
/// <param name="window"></param>
public static IntPtr ParentHandle
{
get
{
IntPtr hwnd = GetConsoleWindow();
return GetParent(hwnd);
}
set
{
IntPtr hwnd = Handle;
if (hwnd==IntPtr.Zero)
return;
SetParent(hwnd, value);
int style = GetWindowLong(hwnd, GWL_STYLE);
if (value==IntPtr.Zero)
SetWindowLong(hwnd, GWL_STYLE, (style &~ WS_CHILD) | WS_OVERLAPPEDWINDOW);
else
SetWindowLong(hwnd, GWL_STYLE, (style | WS_CHILD) &~ WS_OVERLAPPEDWINDOW);
SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
}
}
/// <summary>
/// Get the current Win32 buffer handle
/// </summary>
public static IntPtr Buffer
{
get
{
if (!initialized) Initialize();
return buffer;
}
}
/// <summary>
/// Produces a simple beep.
/// </summary>
public static void Beep()
{
MessageBeep(-1);
}
/// <summary>
/// Flashes the console window
/// </summary>
/// <param name="once">if off, flashes repeated until the user makes the console foreground</param>
public static void Flash(bool once)
{
IntPtr hwnd = GetConsoleWindow();
if (hwnd==IntPtr.Zero)
return;
int style = GetWindowLong(hwnd, GWL_STYLE);
if ((style & WS_CAPTION)==0)
return;
FlashWInfo info = new FlashWInfo();
info.Size = Marshal.SizeOf(typeof(FlashWInfo));
info.Flags = FLASHW_ALL;
if (!once) info.Flags |= FLASHW_TIMERNOFG;
FlashWindowEx(ref info);
}
/// <summary>
/// Clear the console window
/// </summary>
public static void Clear()
{
Initialize();
ConsoleScreenBufferInfo info;
int writtenChars;
GetConsoleScreenBufferInfo(buffer, out info);
FillConsoleOutputCharacter(buffer, ' ', info.Size.X * info.Size.Y, new Coord(), out writtenChars);
CursorPosition = new Coord();
}
/// <summary>
/// Get the current position of the cursor
/// </summary>
///
public static Coord CursorPosition
{
get { return Info.CursorPosition; }
set
{
Initialize();
SetConsoleCursorPosition(buffer, new Coord());
}
}
/// <summary>
/// Returns a coordinates of visible window of the buffer
/// </summary>
public static SmallRect ScreenSize
{
get { return Info.Window; }
}
/// <summary>
/// Returns the size of buffer
/// </summary>
public static Coord BufferSize
{
get { return Info.Size; }
}
/// <summary>
/// Returns the maximum size of the screen given the desktop dimensions
/// </summary>
public static Coord MaximumScreenSize
{
get { return Info.MaximumWindowSize; }
}
/// <summary>
/// Redirects debug output to the console
/// </summary>
/// <param name="clear">clear all other listeners first</param>
/// <param name="color">color to use for display debug output</param>
public void RedirectDebugOutput(bool clear, ConsoleColor color, bool beep)
{
if (clear)
{
Debug.Listeners.Clear();
// Debug.Listeners.Remove("Default");
}
Debug.Listeners.Add( new TextWriterTraceListener(new ConsoleWriter(Console.Error, color, ConsoleFlashMode.FlashUntilResponse, beep), "console") );
}
/// <summary>
/// Redirects trace output to the console
/// </summary>
/// <param name="clear">clear all other listeners first</param>
/// <param name="color">color to use for display trace output</param>
public void RedirectTraceOutput(bool clear, ConsoleColor color)
{
if (clear)
{
Trace.Listeners.Clear();
// Trace.Listeners.Remove("Default");
}
Trace.Listeners.Add( new TextWriterTraceListener(new ConsoleWriter(Console.Error, color, 0, false), "console") );
}
/// <summary>
/// Returns various information about the screen buffer
/// </summary>
static ConsoleScreenBufferInfo Info
{
get
{
ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo();
IntPtr buffer = Buffer;
if (buffer!=IntPtr.Zero)
GetConsoleScreenBufferInfo(buffer, out info);
return info;
}
}
/// <summary>
/// Gets or sets the current color and attributes of text
/// </summary>
public static ConsoleColor Color
{
get
{
return Info.Attributes;
}
set
{
IntPtr buffer = Buffer;
if (buffer != IntPtr.Zero)
WinConsole.SetConsoleTextAttribute(buffer, value);
}
}
/// <summary>
/// Returns true if Ctrl-C or Ctrl-Break was hit since the last time this property
/// was called. The value of this property is set to false after each request.
/// </summary>
public static bool CtrlBreakPressed
{
get
{
bool value = breakHit;
breakHit = false;
return value;
}
}
private static bool HandleBreak(int type)
{
breakHit = true;
if (Break != null)
Break(type);
return true;
}
#endregion
#region Location
/// <summary>
/// Gets the Console Window location and size in pixels
/// </summary>
public void GetWindowPosition(out int x, out int y, out int width, out int height)
{
RECT rect = new RECT();
GetClientRect(Handle, ref rect);
x = rect.top;
y = rect.left;
width = rect.right - rect.left;
height = rect.bottom - rect.top;
}
/// <summary>
/// Sets the console window location and size in pixels
/// </summary>
public void SetWindowPosition(int x, int y, int width, int height)
{
SetWindowPos(Handle, IntPtr.Zero, x, y, width, height, SWP_NOZORDER|SWP_NOACTIVATE);
}
#endregion
#region Console Replacements
/// <summary>
/// Returns the error stream (same as Console.Error)
/// </summary>
public static TextWriter Error
{
get
{
return Console.Error;
}
}
/// <summary>
/// Returns the input stream (same as Console.In)
/// </summary>
public static TextReader In
{
get { return Console.In; }
}
/// <summary>
/// Returns the output stream (same as Console.Out)
/// </summary>
public static TextWriter Out
{
get { return Console.Out; }
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static Stream OpenStandardInput()
{
return Console.OpenStandardInput();
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static Stream OpenStandardInput(int bufferSize)
{
return Console.OpenStandardInput(bufferSize);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static Stream OpenStandardError()
{
return Console.OpenStandardError();
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static Stream OpenStandardError(int bufferSize)
{
return Console.OpenStandardError(bufferSize);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static Stream OpenStandardOutput()
{
return Console.OpenStandardOutput();
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static Stream OpenStandardOutput(int bufferSize)
{
return Console.OpenStandardOutput(bufferSize);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void SetIn(TextReader newIn)
{
Console.SetIn(newIn);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void SetOut(TextWriter newOut)
{
Console.SetOut(newOut);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void SetError(TextWriter newError)
{
Console.SetError(newError);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static int Read()
{
return Console.Read();
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static String ReadLine()
{
return Console.ReadLine();
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine()
{
Console.WriteLine();
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(bool value)
{
Console.WriteLine(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(char value)
{
Console.WriteLine(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(char[] buffer)
{
Console.WriteLine(buffer);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(char[] buffer, int index, int count)
{
Console.WriteLine(buffer, index, count);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(decimal value)
{
Console.WriteLine(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(double value)
{
Console.WriteLine(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(float value)
{
Console.WriteLine(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(int value)
{
Console.WriteLine(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
//[CLSCompliant(false)]
public static void WriteLine(uint value)
{
Console.WriteLine(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(long value)
{
Console.WriteLine(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
//[CLSCompliant(false)]
public static void WriteLine(ulong value)
{
Console.WriteLine(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(Object value)
{
Console.WriteLine(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(String value)
{
Console.WriteLine(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(String format, Object arg0)
{
Console.WriteLine(format, arg0);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(String format, Object arg0, Object arg1)
{
Console.WriteLine(format, arg0, arg1);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(String format, Object arg0, Object arg1, Object arg2)
{
Console.WriteLine(format, arg0, arg1, arg2);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void WriteLine(String format, params Object[] arg)
{
Console.WriteLine(format, arg);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(String format, Object arg0)
{
Console.Write(format, arg0);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(String format, Object arg0, Object arg1)
{
Console.Write(format, arg0, arg1);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(String format, Object arg0, Object arg1, Object arg2)
{
Console.Write(format, arg0, arg1, arg2);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(String format, params Object[] arg)
{
Console.Write(format, arg);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(bool value)
{
Console.Write(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(char value)
{
Console.Write(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(char[] buffer)
{
Console.Write(buffer);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(char[] buffer, int index, int count)
{
Console.Write(buffer, index, count);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(double value)
{
Console.Write(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(decimal value)
{
Console.Write(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(float value)
{
Console.Write(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(int value)
{
Console.Write(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
//[CLSCompliant(false)]
public static void Write(uint value)
{
Console.Write(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(long value)
{
Console.Write(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(ulong value)
{
Console.Write(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(Object value)
{
Console.Write(value);
}
/// <summary>
/// Same as the Console counterpart
/// </summary>
public static void Write(String value)
{
Console.Write(value);
}
#endregion
}
[Flags]
public enum ConsoleColor : short
{
Black = 0x0000,
Blue = 0x0001,
Green = 0x0002,
Cyan = 0x0003,
Red = 0x0004,
Violet = 0x0005,
Yellow = 0x0006,
White = 0x0007,
Intensified = 0x0008,
Normal = White,
BlackBG = 0x0000,
BlueBG = 0x0010,
GreenBG = 0x0020,
CyanBG = 0x0030,
RedBG = 0x0040,
VioletBG = 0x0050,
YellowBG = 0x0060,
WhiteBG = 0x0070,
IntensifiedBG = 0x0080,
Underline = 0x4000,
ReverseVideo = unchecked((short)0x8000),
}
public struct Coord
{
public short X;
public short Y;
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Whitelog.Barak.Common.DataStructures.Dictionary;
using Whitelog.Barak.Common.Events;
using Whitelog.Core.Binary.Serializer;
namespace Whitelog.Core.Binary
{
public class StringComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return x == y;
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
public class ObjectReferanceEquals : IEqualityComparer<object>
{
bool IEqualityComparer<object>.Equals(object x, object y)
{
return object.ReferenceEquals(x, y);
}
int IEqualityComparer<object>.GetHashCode(object obj)
{
return RuntimeHelpers.GetHashCode(obj);
}
}
public interface IBinaryPackager
{
int GetCacheStringId(string value);
void Pack(object data, ISerializer serializer);
}
public class BinaryPackager : IBinaryPackager
{
public event EventHandler<EventArgs<RegisteredPackageDefinition>> PackageRegistered;
public event EventHandler<EventArgs<RegisteredPackageDefinition>> PackageUnregistered;
public event EventHandler<EventArgs<CacheString>> StringChached;
protected readonly ReadSafeDictionary<Type, RegisteredPackageDefinition> m_PackageDefinitions = new ReadSafeDictionary<Type, RegisteredPackageDefinition>(new TypeComparer());
protected readonly ReadSafeDictionary<object, int> m_stringCacheByObjectReferance = new ReadSafeDictionary<object, int>(new ObjectReferanceEquals());
protected readonly ReadSafeDictionary<string, int> m_stringCacheByString = new ReadSafeDictionary<string, int>(new StringComparer());
protected readonly object m_definitionSyncObjectLock = new object();
private int m_cacheStringIdentity = 1;
private int m_packegeId = 1;
protected virtual RegisteredPackageDefinition GetInheretancePackageDefinition(Type type, RegisteredPackageDefinition sourcePackageDefinition,object instance)
{
if (sourcePackageDefinition.DefinitionId == (int)KnownPackageDefinition.PropertyDefinitionDefinition)
{
m_PackageDefinitions.TryAdd(type, sourcePackageDefinition);
return sourcePackageDefinition;
}
else
{
IBinaryPackageDefinition packageDefinition = sourcePackageDefinition.Definition.Clone(type, instance);
RegisteredPackageDefinition registeredPackageDefinition;
RegisterDefinition(packageDefinition, sourcePackageDefinition.DefinitionId, out registeredPackageDefinition);
return registeredPackageDefinition;
}
}
public void Pack(object data, ISerializer serializer)
{
if (data == null)
{
serializer.SerializeVariant(0);
}
else
{
Type type = data.GetType();
RegisteredPackageDefinition packageDefinition;
if (!m_PackageDefinitions.TryGetValue(type, out packageDefinition))
{
lock (m_PackageDefinitions)
{
if (!m_PackageDefinitions.TryGetValue(type, out packageDefinition))
{
// Get the closest packageDefinition
packageDefinition = GetClosestPackageDefinition(type);
if (packageDefinition != null)
{
packageDefinition = GetInheretancePackageDefinition(type, packageDefinition, data);
}
}
}
}
if (packageDefinition == null)
{
throw new NoPackageFoundForTypeExceptin(type);
}
serializer.SerializeVariant(packageDefinition.DefinitionId + 1);
packageDefinition.Definition.PackData(this, serializer, data);
}
}
public int GetCacheStringId(string value)
{
int identityId;
if (!m_stringCacheByObjectReferance.TryGetValue(value, out identityId))
{
if (!m_stringCacheByString.TryGetValue(value, out identityId))
{
lock (m_definitionSyncObjectLock)
{
if (!m_stringCacheByObjectReferance.TryGetValue(value, out identityId))
{
if (!m_stringCacheByString.TryGetValue(value, out identityId))
{
var cacheString = new CacheString
{
Id = m_cacheStringIdentity++,
Value = value
};
this.RaiseEvent(StringChached, cacheString);
m_stringCacheByObjectReferance.TryAdd(value, cacheString.Id);
m_stringCacheByString.TryAdd(value, cacheString.Id);
identityId = cacheString.Id;
}
}
}
}
}
return identityId;
}
protected RegisteredPackageDefinition GetClosestPackageDefinition(Type currDataType)
{
int distance = int.MaxValue;
RegisteredPackageDefinition closestDefinition = null;
foreach (var logPackageDefinition in m_PackageDefinitions)
{
if (logPackageDefinition.Key.IsAssignableFrom(currDataType))
{
var currType = currDataType;
int currentDistance = 0;
while (currType != null && logPackageDefinition.Key.IsAssignableFrom(currType))
{
currentDistance++;
currType = currType.BaseType;
}
if (currentDistance < distance)
{
distance = currentDistance;
closestDefinition = logPackageDefinition.Value;
}
}
}
return closestDefinition;
}
public bool RegisterDefinition(IBinaryPackageDefinition packageDefinition, int packegeId,int basepackegeId, out RegisteredPackageDefinition registeredPackageDefinition)
{
lock (m_definitionSyncObjectLock)
{
registeredPackageDefinition = new RegisteredPackageDefinition(packageDefinition, packegeId,
basepackegeId);
if (m_PackageDefinitions.TryAdd(packageDefinition.GetTypeDefinition(), registeredPackageDefinition))
{
this.RaiseEvent(PackageRegistered, registeredPackageDefinition);
return true;
}
return false;
}
}
public bool RegisterDefinition(IBinaryPackageDefinition packageDefinition)
{
RegisteredPackageDefinition temp;
return RegisterDefinition(packageDefinition, out temp);
}
public bool RegisterDefinition(IBinaryPackageDefinition packageDefinition, out RegisteredPackageDefinition registeredPackageDefinition)
{
return RegisterDefinition(packageDefinition, m_packegeId++,(int)KnownPackageDefinition.NoDefinition, out registeredPackageDefinition);
}
protected bool RegisterDefinition(IBinaryPackageDefinition packageDefinition,int baseDefinitionId, out RegisteredPackageDefinition registeredPackageDefinition)
{
return RegisterDefinition(packageDefinition, m_packegeId++, baseDefinitionId, out registeredPackageDefinition);
}
/*public virtual bool UnregisterDefinition(IBinaryPackageDefinition packageDefinition)
{
bool removed = m_PackageDefinitions.TryRemove(packageDefinition.GetTypeDefinition(), out packageDefinition);
this.RaiseEvent(PackageUnregistered, packageDefinition);
return removed;
}*/
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Insights;
using Microsoft.Azure.Insights.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Insights
{
/// <summary>
/// Operations for log definitions.
/// </summary>
internal partial class LogDefinitionOperations : IServiceOperations<InsightsClient>, ILogDefinitionOperations
{
/// <summary>
/// Initializes a new instance of the LogDefinitionOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal LogDefinitionOperations(InsightsClient client)
{
this._client = client;
}
private InsightsClient _client;
/// <summary>
/// Gets a reference to the Microsoft.Azure.Insights.InsightsClient.
/// </summary>
public InsightsClient Client
{
get { return this._client; }
}
/// <summary>
/// The List Log Definitions operation lists the log definitions for
/// the resource.
/// </summary>
/// <param name='resourceUri'>
/// Required. The resource identifier of the target resource to get
/// logs for.
/// </param>
/// <param name='filterString'>
/// Optional. An OData $filter expression that supports querying by the
/// name of the log definition. For example, "name.value eq
/// 'Percentage CPU'". Name is optional, meaning the expression may be
/// "".
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Log Definitions operation response.
/// </returns>
public async Task<LogDefinitionListResponse> GetLogDefinitionsAsync(string resourceUri, string filterString, CancellationToken cancellationToken)
{
// Validate
if (resourceUri == null)
{
throw new ArgumentNullException("resourceUri");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
tracingParameters.Add("filterString", filterString);
TracingAdapter.Enter(invocationId, this, "GetLogDefinitionsAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(resourceUri);
url = url + "/providers/microsoft.insights/logDefinitions";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-07-01");
List<string> odataFilter = new List<string>();
if (filterString != null)
{
odataFilter.Add(Uri.EscapeDataString(filterString));
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-04-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LogDefinitionListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LogDefinitionListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
LogDefinitionCollection logDefinitionCollectionInstance = new LogDefinitionCollection();
result.LogDefinitionCollection = logDefinitionCollectionInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
LogDefinition logDefinitionInstance = new LogDefinition();
logDefinitionCollectionInstance.Value.Add(logDefinitionInstance);
JToken categoryValue = valueValue["category"];
if (categoryValue != null && categoryValue.Type != JTokenType.Null)
{
LocalizableString categoryInstance = new LocalizableString();
logDefinitionInstance.Category = categoryInstance;
JToken valueValue2 = categoryValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue2);
categoryInstance.Value = valueInstance;
}
JToken localizedValueValue = categoryValue["localizedValue"];
if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null)
{
string localizedValueInstance = ((string)localizedValueValue);
categoryInstance.LocalizedValue = localizedValueInstance;
}
}
JToken resourceIdValue = valueValue["resourceId"];
if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null)
{
string resourceIdInstance = ((string)resourceIdValue);
logDefinitionInstance.ResourceId = resourceIdInstance;
}
JToken retentionValue = valueValue["retention"];
if (retentionValue != null && retentionValue.Type != JTokenType.Null)
{
TimeSpan retentionInstance = TimeSpan.Parse(((string)retentionValue), CultureInfo.InvariantCulture);
logDefinitionInstance.Retention = retentionInstance;
}
JToken blobLocationValue = valueValue["blobLocation"];
if (blobLocationValue != null && blobLocationValue.Type != JTokenType.Null)
{
BlobLocation blobLocationInstance = new BlobLocation();
logDefinitionInstance.BlobLocation = blobLocationInstance;
JToken blobEndpointValue = blobLocationValue["blobEndpoint"];
if (blobEndpointValue != null && blobEndpointValue.Type != JTokenType.Null)
{
string blobEndpointInstance = ((string)blobEndpointValue);
blobLocationInstance.BlobEndpoint = blobEndpointInstance;
}
JToken blobInfoArray = blobLocationValue["blobInfo"];
if (blobInfoArray != null && blobInfoArray.Type != JTokenType.Null)
{
foreach (JToken blobInfoValue in ((JArray)blobInfoArray))
{
BlobInfo blobInfoInstance = new BlobInfo();
blobLocationInstance.BlobInfo.Add(blobInfoInstance);
JToken blobUriValue = blobInfoValue["blobUri"];
if (blobUriValue != null && blobUriValue.Type != JTokenType.Null)
{
string blobUriInstance = ((string)blobUriValue);
blobInfoInstance.BlobUri = blobUriInstance;
}
JToken startTimeValue = blobInfoValue["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTime startTimeInstance = ((DateTime)startTimeValue);
blobInfoInstance.StartTime = startTimeInstance;
}
JToken endTimeValue = blobInfoValue["endTime"];
if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
{
DateTime endTimeInstance = ((DateTime)endTimeValue);
blobInfoInstance.EndTime = endTimeInstance;
}
JToken sasTokenValue = blobInfoValue["sasToken"];
if (sasTokenValue != null && sasTokenValue.Type != JTokenType.Null)
{
string sasTokenInstance = ((string)sasTokenValue);
blobInfoInstance.SasToken = sasTokenInstance;
}
}
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Net.Mime;
using System.Collections.Generic;
namespace System.Net.Mail
{
//
// This class is responsible for parsing E-mail addresses as described in RFC 2822.
//
// Ideally, addresses are formatted as ("Display name" <username@domain>), but we still try to read several
// other formats, including common invalid formats like (Display name username@domain).
//
// To make the detection of invalid address formats simpler, all address parsing is done in reverse order,
// including lists. This way we know that the domain must be first, then the local-part, and then whatever
// remains must be the display-name.
//
internal static class MailAddressParser
{
// Parse a single MailAddress from the given string.
//
// Throws a FormatException if any part of the MailAddress is invalid.
internal static MailAddress ParseAddress(string data)
{
int index = data.Length - 1;
MailAddress parsedAddress = MailAddressParser.ParseAddress(data, false, ref index);
Debug.Assert(index == -1, "The index indicates that part of the address was not parsed: " + index);
return parsedAddress;
}
// Parse a comma separated list of MailAddress's
//
// Throws a FormatException if any MailAddress is invalid.
internal static List<MailAddress> ParseMultipleAddresses(string data)
{
List<MailAddress> results = new List<MailAddress>();
int index = data.Length - 1;
while (index >= 0)
{
// Because we're parsing in reverse, we must make an effort to preserve the order of the addresses.
results.Insert(0, MailAddressParser.ParseAddress(data, true, ref index));
Debug.Assert(index == -1 || data[index] == MailBnfHelper.Comma,
"separator not found while parsing multiple addresses");
index--;
}
return results;
}
//
// Parse a single MailAddress, potentially from a list.
//
// Preconditions:
// - Index must be within the bounds of the data string.
// - The data string must not be null or empty
//
// Postconditions:
// - Returns a valid MailAddress object parsed from the string
// - For a single MailAddress index is set to -1
// - For a list data[index] is the comma separator or -1 if the end of the data string was reached.
//
// Throws a FormatException if any part of the MailAddress is invalid.
private static MailAddress ParseAddress(string data, bool expectMultipleAddresses, ref int index)
{
Debug.Assert(!string.IsNullOrEmpty(data));
Debug.Assert(index >= 0 && index < data.Length, "Index out of range: " + index + ", " + data.Length);
// Parsed components to be assembled as a MailAddress later
string domain = null;
string localPart = null;
string displayName = null;
// Skip comments and whitespace
index = ReadCfwsAndThrowIfIncomplete(data, index);
// Do we expect angle brackets around the address?
// e.g. ("display name" <user@domain>)
bool expectAngleBracket = false;
if (data[index] == MailBnfHelper.EndAngleBracket)
{
expectAngleBracket = true;
index--;
}
domain = ParseDomain(data, ref index);
// The next character after the domain must be the '@' symbol
if (data[index] != MailBnfHelper.At)
{
throw new FormatException(SR.MailAddressInvalidFormat);
}
// Skip the '@' symbol
index--;
localPart = ParseLocalPart(data, ref index, expectAngleBracket, expectMultipleAddresses);
// Check for a matching angle bracket around the address
if (expectAngleBracket)
{
if (index >= 0 && data[index] == MailBnfHelper.StartAngleBracket)
{
index--; // Skip the angle bracket
// Skip whitespace, but leave comments, as they may be part of the display name.
index = WhitespaceReader.ReadFwsReverse(data, index);
}
else
{
// Mismatched angle brackets, throw
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter,
(index >= 0 ? data[index] : MailBnfHelper.EndAngleBracket)));
}
}
// Is there anything left to parse?
// There could still be a display name or another address
if (index >= 0 && !(expectMultipleAddresses && data[index] == MailBnfHelper.Comma))
{
displayName = ParseDisplayName(data, ref index, expectMultipleAddresses);
}
else
{
displayName = string.Empty;
}
return new MailAddress(displayName, localPart, domain);
}
// Read through a section of CFWS. If we reach the end of the data string then throw because not enough of the
// MailAddress components were found.
private static int ReadCfwsAndThrowIfIncomplete(string data, int index)
{
index = WhitespaceReader.ReadCfwsReverse(data, index);
if (index < 0)
{
// More components were expected. Incomplete address, invalid
throw new FormatException(SR.MailAddressInvalidFormat);
}
return index;
}
// Parses the domain section of an address. The domain may be in dot-atom format or surrounded by square
// brackets in domain-literal format.
// e.g. <[email protected]> or <user@[whatever I want]>
//
// Preconditions:
// - data[index] is just inside of the angle brackets (if any).
//
// Postconditions:
// - data[index] should refer to the '@' symbol
// - returns the parsed domain, including any square brackets for domain-literals
//
// Throws a FormatException:
// - For invalid un-escaped chars, including Unicode
// - If the start of the data string is reached
private static string ParseDomain(string data, ref int index)
{
// Skip comments and whitespace
index = ReadCfwsAndThrowIfIncomplete(data, index);
// Mark one end of the domain component
int startingIndex = index;
// Is the domain component in domain-literal format or dot-atom format?
if (data[index] == MailBnfHelper.EndSquareBracket)
{
index = DomainLiteralReader.ReadReverse(data, index);
}
else
{
index = DotAtomReader.ReadReverse(data, index);
}
string domain = data.Substring(index + 1, startingIndex - index);
// Skip comments and whitespace
index = ReadCfwsAndThrowIfIncomplete(data, index);
return NormalizeOrThrow(domain);
}
// Parses the local-part section of an address. The local-part may be in dot-atom format or
// quoted-string format. e.g. <user.name@domain> or <"user name"@domain>
// We do not support the obsolete formats of user."name"@domain, "user".name@domain, or "user"."name"@domain.
//
// Preconditions:
// - data[index + 1] is the '@' symbol
//
// Postconditions:
// - data[index] should refer to the '<', if any, otherwise the next non-CFWS char.
// - index == -1 if the beginning of the data string has been reached.
// - returns the parsed local-part, including any bounding quotes around quoted-strings
//
// Throws a FormatException:
// - For invalid un-escaped chars, including Unicode
// - If the final value of data[index] is not a valid character to precede the local-part
private static string ParseLocalPart(string data, ref int index, bool expectAngleBracket,
bool expectMultipleAddresses)
{
// Skip comments and whitespace
index = ReadCfwsAndThrowIfIncomplete(data, index);
// Mark the start of the local-part
int startingIndex = index;
// Is the local-part component in quoted-string format or dot-atom format?
if (data[index] == MailBnfHelper.Quote)
{
index = QuotedStringFormatReader.ReadReverseQuoted(data, index, true);
}
else
{
index = DotAtomReader.ReadReverse(data, index);
// Check that the local-part is properly separated from the next component. It may be separated by a
// comment, whitespace, an expected angle bracket, a quote for the display-name, or an expected comma
// before the next address.
if (index >= 0 &&
!(
MailBnfHelper.IsAllowedWhiteSpace(data[index]) // < local@domain >
|| data[index] == MailBnfHelper.EndComment // <(comment)local@domain>
|| (expectAngleBracket && data[index] == MailBnfHelper.StartAngleBracket) // <local@domain>
|| (expectMultipleAddresses && data[index] == MailBnfHelper.Comma) // local@dom,local@dom
// Note: The following condition is more lax than the RFC. This is done so we could support
// a common invalid formats as shown below.
|| data[index] == MailBnfHelper.Quote // "display"local@domain
)
)
{
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[index]));
}
}
string localPart = data.Substring(index + 1, startingIndex - index);
index = WhitespaceReader.ReadCfwsReverse(data, index);
return NormalizeOrThrow(localPart);
}
// Parses the display-name section of an address. In departure from the RFC, we attempt to read data in the
// quoted-string format even if the bounding quotes are omitted. We also permit Unicode, which the RFC does
// not allow for.
// e.g. ("display name" <user@domain>) or (display name <user@domain>)
//
// Preconditions:
//
// Postconditions:
// - data[index] should refer to the comma ',' separator, if any
// - index == -1 if the beginning of the data string has been reached.
// - returns the parsed display-name, excluding any bounding quotes around quoted-strings
//
// Throws a FormatException:
// - For invalid un-escaped chars, except Unicode
// - If the postconditions cannot be met.
private static string ParseDisplayName(string data, ref int index, bool expectMultipleAddresses)
{
string displayName;
// Whatever is left over must be the display name. The display name should be a single word/atom or a
// quoted string, but for robustness we allow the quotes to be omitted, so long as we can find the comma
// separator before the next address.
// Read the comment (if any). If the display name is contained in quotes, the surrounding comments are
// omitted. Otherwise, mark this end of the comment so we can include it as part of the display name.
int firstNonCommentIndex = WhitespaceReader.ReadCfwsReverse(data, index);
// Check to see if there's a quoted-string display name
if (firstNonCommentIndex >= 0 && data[firstNonCommentIndex] == MailBnfHelper.Quote)
{
// The preceding comment was not part of the display name. Read just the quoted string.
index = QuotedStringFormatReader.ReadReverseQuoted(data, firstNonCommentIndex, true);
Debug.Assert(data[index + 1] == MailBnfHelper.Quote, "Mis-aligned index: " + index);
// Do not include the bounding quotes on the display name
int leftIndex = index + 2;
displayName = data.Substring(leftIndex, firstNonCommentIndex - leftIndex);
// Skip any CFWS after the display name
index = WhitespaceReader.ReadCfwsReverse(data, index);
// Check for completion. We are valid if we hit the end of the data string or if the rest of the data
// belongs to another address.
if (index >= 0 && !(expectMultipleAddresses && data[index] == MailBnfHelper.Comma))
{
// If there was still data, only a comma could have been the next valid character
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[index]));
}
}
else
{
// The comment (if any) should be part of the display name.
int startingIndex = index;
// Read until the dividing comma or the end of the line.
index = QuotedStringFormatReader.ReadReverseUnQuoted(data, index, true, expectMultipleAddresses);
Debug.Assert(index < 0 || data[index] == MailBnfHelper.Comma, "Mis-aligned index: " + index);
// Do not include the Comma (if any), and because there were no bounding quotes,
// trim extra whitespace.
displayName = data.SubstringTrim(index + 1, startingIndex - index);
}
return NormalizeOrThrow(displayName);
}
internal static string NormalizeOrThrow(string input)
{
try
{
return input.Normalize(Text.NormalizationForm.FormC);
}
catch (ArgumentException e)
{
throw new FormatException(SR.MailAddressInvalidFormat, e);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using NSubstitute;
using Octokit.Helpers;
using Xunit;
namespace Octokit.Tests.Clients
{
public class StatisticsClientTests
{
public class TheCtor
{
[Fact]
public void EnsuresNonNullArguments()
{
Assert.Throws<ArgumentNullException>(() => new StatisticsClient(null));
}
}
public class TheGetContributorsMethod
{
[Fact]
public async Task RequestsCorrectUrl()
{
var expectedEndPoint = new Uri("repos/owner/name/stats/contributors", UriKind.Relative);
IReadOnlyList<Contributor> contributors = new ReadOnlyCollection<Contributor>(new[] { new Contributor() });
var connection = Substitute.For<IApiConnection>();
connection.GetQueuedOperation<Contributor>(expectedEndPoint, Args.CancellationToken)
.Returns(Task.FromResult(contributors));
var client = new StatisticsClient(connection);
var result = await client.GetContributors("owner", "name");
Assert.Equal(1, result.Count);
}
[Fact]
public async Task RequestsCorrectUrlWithRepositoryId()
{
var expectedEndPoint = new Uri("repositories/1/stats/contributors", UriKind.Relative);
IReadOnlyList<Contributor> contributors = new ReadOnlyCollection<Contributor>(new[] { new Contributor() });
var connection = Substitute.For<IApiConnection>();
connection.GetQueuedOperation<Contributor>(expectedEndPoint, Args.CancellationToken)
.Returns(Task.FromResult(contributors));
var client = new StatisticsClient(connection);
var result = await client.GetContributors(1);
Assert.Equal(1, result.Count);
}
[Fact]
public async Task RequestsCorrectUrlWithCancellactionToken()
{
var expectedEndPoint = new Uri("repos/owner/name/stats/contributors", UriKind.Relative);
IReadOnlyList<Contributor> contributors = new ReadOnlyCollection<Contributor>(new[] { new Contributor() });
var cancellationToken = new CancellationToken(true);
var connection = Substitute.For<IApiConnection>();
connection.GetQueuedOperation<Contributor>(expectedEndPoint, cancellationToken)
.Returns(Task.FromResult(contributors));
var client = new StatisticsClient(connection);
var result = await client.GetContributors("owner", "name", cancellationToken);
Assert.Equal(1, result.Count);
}
[Fact]
public async Task RequestsCorrectUrlWithRepositoryIdWithCancellactionToken()
{
var expectedEndPoint = new Uri("repositories/1/stats/contributors", UriKind.Relative);
IReadOnlyList<Contributor> contributors = new ReadOnlyCollection<Contributor>(new[] { new Contributor() });
var cancellationToken = new CancellationToken(true);
var connection = Substitute.For<IApiConnection>();
connection.GetQueuedOperation<Contributor>(expectedEndPoint, cancellationToken)
.Returns(Task.FromResult(contributors));
var client = new StatisticsClient(connection);
var result = await client.GetContributors(1, cancellationToken);
Assert.Equal(1, result.Count);
}
[Fact]
public async Task EnsureNonNullArguments()
{
var client = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetContributors(null, "name"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetContributors("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetContributors("", "name"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetContributors("owner", ""));
}
}
public class TheGetCommitActivityForTheLastYearMethod
{
[Fact]
public async Task RequestsCorrectUrl()
{
var expectedEndPoint = new Uri("repos/owner/name/stats/commit_activity", UriKind.Relative);
var data = new WeeklyCommitActivity(new[] { 1, 2 }, 100, 42);
IReadOnlyList<WeeklyCommitActivity> response = new ReadOnlyCollection<WeeklyCommitActivity>(new[] { data });
var client = Substitute.For<IApiConnection>();
client.GetQueuedOperation<WeeklyCommitActivity>(expectedEndPoint, Args.CancellationToken)
.Returns(Task.FromResult(response));
var statisticsClient = new StatisticsClient(client);
var result = await statisticsClient.GetCommitActivity("owner", "name");
Assert.Equal(2, result.Activity[0].Days.Count);
Assert.Equal(1, result.Activity[0].Days[0]);
Assert.Equal(2, result.Activity[0].Days[1]);
Assert.Equal(100, result.Activity[0].Total);
Assert.Equal(42, result.Activity[0].Week);
}
[Fact]
public async Task RequestsCorrectUrlWithRepositoryId()
{
var expectedEndPoint = new Uri("repositories/1/stats/commit_activity", UriKind.Relative);
var data = new WeeklyCommitActivity(new[] { 1, 2 }, 100, 42);
IReadOnlyList<WeeklyCommitActivity> response = new ReadOnlyCollection<WeeklyCommitActivity>(new[] { data });
var client = Substitute.For<IApiConnection>();
client.GetQueuedOperation<WeeklyCommitActivity>(expectedEndPoint, Args.CancellationToken)
.Returns(Task.FromResult(response));
var statisticsClient = new StatisticsClient(client);
var result = await statisticsClient.GetCommitActivity(1);
Assert.Equal(2, result.Activity[0].Days.Count);
Assert.Equal(1, result.Activity[0].Days[0]);
Assert.Equal(2, result.Activity[0].Days[1]);
Assert.Equal(100, result.Activity[0].Total);
Assert.Equal(42, result.Activity[0].Week);
}
[Fact]
public async Task RequestsCorrectUrlWithCancellationToken()
{
var expectedEndPoint = new Uri("repos/owner/name/stats/commit_activity", UriKind.Relative);
var cancellationToken = new CancellationToken();
var data = new WeeklyCommitActivity(new[] { 1, 2 }, 100, 42);
IReadOnlyList<WeeklyCommitActivity> response = new ReadOnlyCollection<WeeklyCommitActivity>(new[] { data });
var connection = Substitute.For<IApiConnection>();
connection.GetQueuedOperation<WeeklyCommitActivity>(expectedEndPoint, cancellationToken)
.Returns(Task.FromResult(response));
var client = new StatisticsClient(connection);
var result = await client.GetCommitActivity("owner", "name", cancellationToken);
Assert.Equal(2, result.Activity[0].Days.Count);
Assert.Equal(1, result.Activity[0].Days[0]);
Assert.Equal(2, result.Activity[0].Days[1]);
Assert.Equal(100, result.Activity[0].Total);
Assert.Equal(42, result.Activity[0].Week);
}
[Fact]
public async Task RequestsCorrectUrlWithRepositoryIdWithCancellationToken()
{
var expectedEndPoint = new Uri("repositories/1/stats/commit_activity", UriKind.Relative);
var cancellationToken = new CancellationToken();
var data = new WeeklyCommitActivity(new[] { 1, 2 }, 100, 42);
IReadOnlyList<WeeklyCommitActivity> response = new ReadOnlyCollection<WeeklyCommitActivity>(new[] { data });
var connection = Substitute.For<IApiConnection>();
connection.GetQueuedOperation<WeeklyCommitActivity>(expectedEndPoint, cancellationToken)
.Returns(Task.FromResult(response));
var client = new StatisticsClient(connection);
var result = await client.GetCommitActivity(1, cancellationToken);
Assert.Equal(2, result.Activity[0].Days.Count);
Assert.Equal(1, result.Activity[0].Days[0]);
Assert.Equal(2, result.Activity[0].Days[1]);
Assert.Equal(100, result.Activity[0].Total);
Assert.Equal(42, result.Activity[0].Week);
}
[Fact]
public async Task EnsureNonNullArguments()
{
var client = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetCommitActivity(null, "name"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetCommitActivity("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetCommitActivity("", "name"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetCommitActivity("owner", ""));
}
}
public class TheGetAdditionsAndDeletionsPerWeekMethod
{
[Fact]
public async Task RequestsCorrectUrl()
{
var expectedEndPoint = new Uri("repos/owner/name/stats/code_frequency", UriKind.Relative);
long firstTimestamp = 159670861;
long secondTimestamp = 0;
IReadOnlyList<long[]> data = new ReadOnlyCollection<long[]>(new[]
{
new[] { firstTimestamp, 10, 52 },
new[] { secondTimestamp, 0, 9 }
});
var client = Substitute.For<IApiConnection>();
client.GetQueuedOperation<long[]>(expectedEndPoint, Args.CancellationToken)
.Returns(Task.FromResult(data));
var statisticsClient = new StatisticsClient(client);
var codeFrequency = await statisticsClient.GetCodeFrequency("owner", "name");
Assert.Equal(2, codeFrequency.AdditionsAndDeletionsByWeek.Count);
Assert.Equal(firstTimestamp.FromUnixTime(), codeFrequency.AdditionsAndDeletionsByWeek[0].Timestamp);
Assert.Equal(10, codeFrequency.AdditionsAndDeletionsByWeek[0].Additions);
Assert.Equal(52, codeFrequency.AdditionsAndDeletionsByWeek[0].Deletions);
Assert.Equal(secondTimestamp.FromUnixTime(), codeFrequency.AdditionsAndDeletionsByWeek[1].Timestamp);
Assert.Equal(0, codeFrequency.AdditionsAndDeletionsByWeek[1].Additions);
Assert.Equal(9, codeFrequency.AdditionsAndDeletionsByWeek[1].Deletions);
}
[Fact]
public async Task RequestsCorrectUrlWithRepositoryId()
{
var expectedEndPoint = new Uri("repositories/1/stats/code_frequency", UriKind.Relative);
long firstTimestamp = 159670861;
long secondTimestamp = 0;
IReadOnlyList<long[]> data = new ReadOnlyCollection<long[]>(new[]
{
new[] { firstTimestamp, 10, 52 },
new[] { secondTimestamp, 0, 9 }
});
var client = Substitute.For<IApiConnection>();
client.GetQueuedOperation<long[]>(expectedEndPoint, Args.CancellationToken)
.Returns(Task.FromResult(data));
var statisticsClient = new StatisticsClient(client);
var codeFrequency = await statisticsClient.GetCodeFrequency(1);
Assert.Equal(2, codeFrequency.AdditionsAndDeletionsByWeek.Count);
Assert.Equal(firstTimestamp.FromUnixTime(), codeFrequency.AdditionsAndDeletionsByWeek[0].Timestamp);
Assert.Equal(10, codeFrequency.AdditionsAndDeletionsByWeek[0].Additions);
Assert.Equal(52, codeFrequency.AdditionsAndDeletionsByWeek[0].Deletions);
Assert.Equal(secondTimestamp.FromUnixTime(), codeFrequency.AdditionsAndDeletionsByWeek[1].Timestamp);
Assert.Equal(0, codeFrequency.AdditionsAndDeletionsByWeek[1].Additions);
Assert.Equal(9, codeFrequency.AdditionsAndDeletionsByWeek[1].Deletions);
}
[Fact]
public async Task RequestsCorrectUrlWithCancellationToken()
{
var expectedEndPoint = new Uri("repos/owner/name/stats/code_frequency", UriKind.Relative);
var cancellationToken = new CancellationToken();
long firstTimestamp = 159670861;
long secondTimestamp = 0;
IReadOnlyList<long[]> data = new ReadOnlyCollection<long[]>(new[]
{
new[] { firstTimestamp, 10, 52 },
new[] { secondTimestamp, 0, 9 }
});
var connection = Substitute.For<IApiConnection>();
connection.GetQueuedOperation<long[]>(expectedEndPoint, cancellationToken)
.Returns(Task.FromResult(data));
var client = new StatisticsClient(connection);
var codeFrequency = await client.GetCodeFrequency("owner", "name", cancellationToken);
Assert.Equal(2, codeFrequency.AdditionsAndDeletionsByWeek.Count);
Assert.Equal(firstTimestamp.FromUnixTime(), codeFrequency.AdditionsAndDeletionsByWeek[0].Timestamp);
Assert.Equal(10, codeFrequency.AdditionsAndDeletionsByWeek[0].Additions);
Assert.Equal(52, codeFrequency.AdditionsAndDeletionsByWeek[0].Deletions);
Assert.Equal(secondTimestamp.FromUnixTime(), codeFrequency.AdditionsAndDeletionsByWeek[1].Timestamp);
Assert.Equal(0, codeFrequency.AdditionsAndDeletionsByWeek[1].Additions);
Assert.Equal(9, codeFrequency.AdditionsAndDeletionsByWeek[1].Deletions);
}
[Fact]
public async Task RequestsCorrectUrlWithRepositoryIdWithCancellationToken()
{
var expectedEndPoint = new Uri("repositories/1/stats/code_frequency", UriKind.Relative);
var cancellationToken = new CancellationToken();
long firstTimestamp = 159670861;
long secondTimestamp = 0;
IReadOnlyList<long[]> data = new ReadOnlyCollection<long[]>(new[]
{
new[] { firstTimestamp, 10, 52 },
new[] { secondTimestamp, 0, 9 }
});
var connection = Substitute.For<IApiConnection>();
connection.GetQueuedOperation<long[]>(expectedEndPoint, cancellationToken)
.Returns(Task.FromResult(data));
var client = new StatisticsClient(connection);
var codeFrequency = await client.GetCodeFrequency(1, cancellationToken);
Assert.Equal(2, codeFrequency.AdditionsAndDeletionsByWeek.Count);
Assert.Equal(firstTimestamp.FromUnixTime(), codeFrequency.AdditionsAndDeletionsByWeek[0].Timestamp);
Assert.Equal(10, codeFrequency.AdditionsAndDeletionsByWeek[0].Additions);
Assert.Equal(52, codeFrequency.AdditionsAndDeletionsByWeek[0].Deletions);
Assert.Equal(secondTimestamp.FromUnixTime(), codeFrequency.AdditionsAndDeletionsByWeek[1].Timestamp);
Assert.Equal(0, codeFrequency.AdditionsAndDeletionsByWeek[1].Additions);
Assert.Equal(9, codeFrequency.AdditionsAndDeletionsByWeek[1].Deletions);
}
[Fact]
public async Task EnsureNonNullArguments()
{
var client = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetCodeFrequency(null, "name"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetCodeFrequency("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetCodeFrequency("", "name"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetCodeFrequency("owner", ""));
}
}
public class TheGetWeeklyCommitCountsMethod
{
[Fact]
public void RequestsCorrectUrl()
{
var expectedEndPoint = new Uri("repos/owner/name/stats/participation", UriKind.Relative);
var client = Substitute.For<IApiConnection>();
var statisticsClient = new StatisticsClient(client);
statisticsClient.GetParticipation("owner", "name");
client.Received().GetQueuedOperation<Participation>(expectedEndPoint, Args.CancellationToken);
}
[Fact]
public void RequestsCorrectUrlWithRepositoryId()
{
var expectedEndPoint = new Uri("repositories/1/stats/participation", UriKind.Relative);
var client = Substitute.For<IApiConnection>();
var statisticsClient = new StatisticsClient(client);
statisticsClient.GetParticipation(1);
client.Received().GetQueuedOperation<Participation>(expectedEndPoint, Args.CancellationToken);
}
[Fact]
public void RequestsCorrectUrlWithCancellationToken()
{
var expectedEndPoint = new Uri("repos/owner/name/stats/participation", UriKind.Relative);
var cancellationToken = new CancellationToken();
var client = Substitute.For<IApiConnection>();
var statisticsClient = new StatisticsClient(client);
statisticsClient.GetParticipation("owner", "name", cancellationToken);
client.Received().GetQueuedOperation<Participation>(expectedEndPoint, cancellationToken);
}
[Fact]
public void RequestsCorrectUrlWithRepositoryIdWithCancellationToken()
{
var expectedEndPoint = new Uri("repositories/1/stats/participation", UriKind.Relative);
var cancellationToken = new CancellationToken();
var client = Substitute.For<IApiConnection>();
var statisticsClient = new StatisticsClient(client);
statisticsClient.GetParticipation(1, cancellationToken);
client.Received().GetQueuedOperation<Participation>(expectedEndPoint, cancellationToken);
}
[Fact]
public async Task EnsureNonNullArguments()
{
var client = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetParticipation(null, "name"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetParticipation("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetParticipation("", "name"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetParticipation("owner", ""));
}
}
public class TheGetHourlyCommitCountsMethod
{
[Fact]
public async Task RequestsCorrectUrl()
{
var expectedEndPoint = new Uri("repos/owner/name/stats/punch_card", UriKind.Relative);
var client = Substitute.For<IApiConnection>();
IReadOnlyList<int[]> data = new ReadOnlyCollection<int[]>(new[] { new[] { 2, 8, 42 } });
client.GetQueuedOperation<int[]>(expectedEndPoint, Args.CancellationToken)
.Returns(Task.FromResult(data));
var statisticsClient = new StatisticsClient(client);
var result = await statisticsClient.GetPunchCard("owner", "name");
Assert.Equal(1, result.PunchPoints.Count);
Assert.Equal(DayOfWeek.Tuesday, result.PunchPoints[0].DayOfWeek);
Assert.Equal(8, result.PunchPoints[0].HourOfTheDay);
Assert.Equal(42, result.PunchPoints[0].CommitCount);
}
[Fact]
public async Task RequestsCorrectUrlWithRepositoryId()
{
var expectedEndPoint = new Uri("repositories/1/stats/punch_card", UriKind.Relative);
var client = Substitute.For<IApiConnection>();
IReadOnlyList<int[]> data = new ReadOnlyCollection<int[]>(new[] { new[] { 2, 8, 42 } });
client.GetQueuedOperation<int[]>(expectedEndPoint, Args.CancellationToken)
.Returns(Task.FromResult(data));
var statisticsClient = new StatisticsClient(client);
var result = await statisticsClient.GetPunchCard(1);
Assert.Equal(1, result.PunchPoints.Count);
Assert.Equal(DayOfWeek.Tuesday, result.PunchPoints[0].DayOfWeek);
Assert.Equal(8, result.PunchPoints[0].HourOfTheDay);
Assert.Equal(42, result.PunchPoints[0].CommitCount);
}
[Fact]
public async Task RequestsCorrectUrlWithCancellationToken()
{
var expectedEndPoint = new Uri("repos/owner/name/stats/punch_card", UriKind.Relative);
var cancellationToken = new CancellationToken();
var connection = Substitute.For<IApiConnection>();
IReadOnlyList<int[]> data = new ReadOnlyCollection<int[]>(new[] { new[] { 2, 8, 42 } });
connection.GetQueuedOperation<int[]>(expectedEndPoint, cancellationToken)
.Returns(Task.FromResult(data));
var client = new StatisticsClient(connection);
var result = await client.GetPunchCard("owner", "name", cancellationToken);
Assert.Equal(1, result.PunchPoints.Count);
Assert.Equal(DayOfWeek.Tuesday, result.PunchPoints[0].DayOfWeek);
Assert.Equal(8, result.PunchPoints[0].HourOfTheDay);
Assert.Equal(42, result.PunchPoints[0].CommitCount);
}
[Fact]
public async Task RequestsCorrectUrlWithRepositoryIdWithCancellationToken()
{
var expectedEndPoint = new Uri("repositories/1/stats/punch_card", UriKind.Relative);
var cancellationToken = new CancellationToken();
var connection = Substitute.For<IApiConnection>();
IReadOnlyList<int[]> data = new ReadOnlyCollection<int[]>(new[] { new[] { 2, 8, 42 } });
connection.GetQueuedOperation<int[]>(expectedEndPoint, cancellationToken)
.Returns(Task.FromResult(data));
var client = new StatisticsClient(connection);
var result = await client.GetPunchCard(1, cancellationToken);
Assert.Equal(1, result.PunchPoints.Count);
Assert.Equal(DayOfWeek.Tuesday, result.PunchPoints[0].DayOfWeek);
Assert.Equal(8, result.PunchPoints[0].HourOfTheDay);
Assert.Equal(42, result.PunchPoints[0].CommitCount);
}
[Fact]
public async Task EnsureNonNullArguments()
{
var client = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetPunchCard(null, "name"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetPunchCard("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetPunchCard("", "name"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetPunchCard("owner", ""));
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.