context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Magneto.Core; namespace Magneto.Tests.Core.OperationTests { public abstract class CheckingEquality : ScenarioFor<Operation> { #pragma warning disable CA1720 // Identifier contains type name protected object Object; #pragma warning restore CA1720 // Identifier contains type name bool _objectsAreEqual; bool _operationsAreEqual; bool _hashCodesAreEqual; protected void WhenCheckingEquality() { _objectsAreEqual = SUT.Equals(Object); _operationsAreEqual = SUT.Equals((Operation)Object); _hashCodesAreEqual = SUT.GetHashCode() == Object?.GetHashCode(); } protected void AssertEqual() { _objectsAreEqual.Should().BeTrue(); _operationsAreEqual.Should().BeTrue(); _hashCodesAreEqual.Should().BeTrue(); } protected void AssertNotEqual() { _objectsAreEqual.Should().BeFalse(); _operationsAreEqual.Should().BeFalse(); _hashCodesAreEqual.Should().BeFalse(); } public class WithNull : CheckingEquality { void GivenAOperationAndANullReference() { SUT = new OperationWithoutProperties1(); Object = null; } void ThenTheyAreNotEqual() => AssertNotEqual(); } public class WithItself : CheckingEquality { void GivenTwoReferencesToTheSameOperation() { SUT = new OperationWithoutProperties1(); Object = SUT; } void ThenTheyAreEqual() => AssertEqual(); } public abstract class SameType : CheckingEquality { public class WithoutProperties : SameType { void GivenTwoOperationsOfTheSameTypeWithoutProperties() { SUT = new OperationWithoutProperties1(); Object = new OperationWithoutProperties1(); } protected void ThenTheyAreEqual() => AssertEqual(); public class SyncQuery : WithoutProperties { void GivenTwoSyncQueriesOfTheSameTypeWithoutProperties() { SUT = new SyncQueryWithoutProperties(); Object = new SyncQueryWithoutProperties(); } } public class AsyncQuery : WithoutProperties { void GivenTwoAsyncQueriesOfTheSameTypeWithoutProperties() { SUT = new AsyncQueryWithoutProperties(); Object = new AsyncQueryWithoutProperties(); } } public class SyncCachedQuery : WithoutProperties { void GivenTwoSyncCachedQueriesOfTheSameTypeWithoutProperties() { SUT = new SyncCachedQueryWithoutProperties(); Object = new SyncCachedQueryWithoutProperties(); } } public class AsyncCachedQuery : WithoutProperties { void GivenTwoAsyncCachedQueriesOfTheSameTypeWithoutProperties() { SUT = new AsyncCachedQueryWithoutProperties(); Object = new AsyncCachedQueryWithoutProperties(); } } public class SyncTransformedCachedQuery : WithoutProperties { void GivenTwoSyncCachedQueriesOfTheSameTypeWithoutProperties() { SUT = new SyncTransformedCachedQueryWithoutProperties(); Object = new SyncTransformedCachedQueryWithoutProperties(); } } public class AsyncTransformedCachedQuery : WithoutProperties { void GivenTwoAsyncTransformedCachedQueriesOfTheSameTypeWithoutProperties() { SUT = new AsyncTransformedCachedQueryWithoutProperties(); Object = new AsyncTransformedCachedQueryWithoutProperties(); } } public class SyncCommand : WithoutProperties { void GivenTwoSyncCommandsOfTheSameTypeWithoutProperties() { SUT = new SyncCommandWithoutProperties(); Object = new SyncCommandWithoutProperties(); } } public class AsyncCommand : WithoutProperties { void GivenTwoAsyncCommandsOfTheSameTypeWithoutProperties() { SUT = new AsyncCommandWithoutProperties(); Object = new AsyncCommandWithoutProperties(); } } public class SyncReturningCommand : WithoutProperties { void GivenTwoSyncCommandsOfTheSameTypeWithoutProperties() { SUT = new SyncReturningCommandWithoutProperties(); Object = new SyncReturningCommandWithoutProperties(); } } public class AsyncReturningCommand : WithoutProperties { void GivenTwoAsyncCommandsOfTheSameTypeWithoutProperties() { SUT = new AsyncReturningCommandWithoutProperties(); Object = new AsyncReturningCommandWithoutProperties(); } } } public abstract class WithProperties : SameType { public class PropertiesEqual : WithProperties { void GivenTwoOperationsOfTheSameTypeWithPropertiesThatAreEqual() { var item = new object(); SUT = new OperationWithProperties1 { Integer = 1, Boolean = true, String = "String", Enum = UriKind.Absolute, Object = item, Collection = new[] { item } }; Object = new OperationWithProperties1 { Integer = 1, Boolean = true, String = "String", Enum = UriKind.Absolute, Object = item, Collection = new[] { item } }; } void ThenTheyAreEqual() => AssertEqual(); } public class PropertiesNotEqual : WithProperties { void GivenTwoOperationsOfTheSameTypeWithPropertiesThatAreNotEqual() { var item = new object(); SUT = new OperationWithProperties1 { Integer = 1, Boolean = true, String = "String", Enum = UriKind.Absolute, Object = item, Collection = new[] { item } }; Object = new OperationWithProperties1 { Integer = 2, Boolean = true, String = "String", Enum = UriKind.Absolute, Object = item, Collection = new[] { item } }; } void ThenTheyAreNotEqual() => AssertNotEqual(); } } } public abstract class DifferentType : CheckingEquality { public class WithoutProperties : DifferentType { void GivenTwoOperationsOfDifferentTypeWithoutProperties() { SUT = new OperationWithoutProperties1(); Object = new OperationWithoutProperties2(); } void ThenTheyAreNotEqual() => AssertNotEqual(); } public abstract class WithProperties : DifferentType { public class PropertiesEqual : WithProperties { void GivenTwoOperationsOfDifferentTypeWithPropertiesThatAreEqual() { var item = new object(); SUT = new OperationWithProperties1 { Integer = 1, Boolean = true, String = "String", Enum = UriKind.Absolute, Object = item, Collection = new[] { item } }; Object = new OperationWithProperties2 { Integer = 1, Boolean = true, String = "String", Enum = UriKind.Absolute, Object = item, Collection = new[] { item } }; } void ThenTheyAreNotEqual() => AssertNotEqual(); } public class PropertiesNotEqual : WithProperties { void GivenTwoOperationsOfDifferentTypeWithPropertiesThatAreNotEqual() { var item = new object(); SUT = new OperationWithProperties1 { Integer = 1, Boolean = true, String = "String", Enum = UriKind.Absolute, Object = item, Collection = new[] { item } }; Object = new OperationWithProperties2 { Integer = 2, Boolean = true, String = "String", Enum = UriKind.Absolute, Object = item, Collection = new[] { item } }; } void ThenTheyAreNotEqual() => AssertNotEqual(); } } } } public class OperationWithoutProperties1 : Operation { } public class OperationWithoutProperties2 : Operation { } public class SyncQueryWithoutProperties : SyncQuery<object, object> { protected override object Query(object context) => throw new NotImplementedException(); } public class AsyncQueryWithoutProperties : AsyncQuery<object, object> { protected override Task<object> Query(object context, CancellationToken cancellationToken) => throw new NotImplementedException(); } public class SyncCachedQueryWithoutProperties : SyncCachedQuery<object, object, object> { protected override void CacheKey(ICache cache) => throw new NotImplementedException(); protected override object CacheEntryOptions(object context) => throw new NotImplementedException(); protected override object Query(object context) => throw new NotImplementedException(); } public class AsyncCachedQueryWithoutProperties : AsyncCachedQuery<object, object, object> { protected override void CacheKey(ICache cache) => throw new NotImplementedException(); protected override object CacheEntryOptions(object context) => throw new NotImplementedException(); protected override Task<object> Query(object context, CancellationToken cancellationToken) => throw new NotImplementedException(); } public class SyncTransformedCachedQueryWithoutProperties : SyncTransformedCachedQuery<object, object, object, object> { protected override void CacheKey(ICache cache) => throw new NotImplementedException(); protected override object CacheEntryOptions(object context) => throw new NotImplementedException(); protected override object Query(object context) => throw new NotImplementedException(); protected override object TransformCachedResult(object cachedResult) => throw new NotImplementedException(); } public class AsyncTransformedCachedQueryWithoutProperties : AsyncTransformedCachedQuery<object, object, object, object> { protected override void CacheKey(ICache cache) => throw new NotImplementedException(); protected override object CacheEntryOptions(object context) => throw new NotImplementedException(); protected override Task<object> Query(object context, CancellationToken cancellationToken) => throw new NotImplementedException(); protected override Task<object> TransformCachedResult(object cachedResult, CancellationToken cancellationToken) => throw new NotImplementedException(); } public class SyncCommandWithoutProperties : SyncCommand<object> { public override void Execute(object context) { throw new NotImplementedException(); } } public class AsyncCommandWithoutProperties : AsyncCommand<object> { public override Task Execute(object context, CancellationToken cancellationToken) => throw new NotImplementedException(); } public class SyncReturningCommandWithoutProperties : SyncCommand<object, object> { public override object Execute(object context) => throw new NotImplementedException(); } public class AsyncReturningCommandWithoutProperties : AsyncCommand<object, object> { public override Task<object> Execute(object context, CancellationToken cancellationToken) => throw new NotImplementedException(); } public class OperationWithProperties1 : Operation { #pragma warning disable CA1720 // Identifier contains type name public int Integer { get; set; } public bool Boolean { get; set; } public string String { get; set; } public UriKind Enum { get; set; } public object Object { get; set; } #pragma warning restore CA1720 // Identifier contains type name public IEnumerable<object> Collection { get; set; } } public class OperationWithProperties2 : Operation { #pragma warning disable CA1720 // Identifier contains type name public int Integer { get; set; } public bool Boolean { get; set; } public string String { get; set; } public UriKind Enum { get; set; } public object Object { get; set; } #pragma warning restore CA1720 // Identifier contains type name public IEnumerable<object> Collection { get; set; } } }
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 Webby.Areas.HelpPage.ModelDescriptions; using Webby.Areas.HelpPage.Models; namespace Webby.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); } } } }
namespace OpenQA.Selenium.DevTools.Network { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Represents an adapter for the Network domain to simplify the command interface. /// </summary> public class NetworkAdapter { private readonly DevToolsSession m_session; private readonly string m_domainName = "Network"; private Dictionary<string, DevToolsEventData> m_eventMap = new Dictionary<string, DevToolsEventData>(); public NetworkAdapter(DevToolsSession session) { m_session = session ?? throw new ArgumentNullException(nameof(session)); m_session.DevToolsEventReceived += OnDevToolsEventReceived; m_eventMap["dataReceived"] = new DevToolsEventData(typeof(DataReceivedEventArgs), OnDataReceived); m_eventMap["eventSourceMessageReceived"] = new DevToolsEventData(typeof(EventSourceMessageReceivedEventArgs), OnEventSourceMessageReceived); m_eventMap["loadingFailed"] = new DevToolsEventData(typeof(LoadingFailedEventArgs), OnLoadingFailed); m_eventMap["loadingFinished"] = new DevToolsEventData(typeof(LoadingFinishedEventArgs), OnLoadingFinished); m_eventMap["requestIntercepted"] = new DevToolsEventData(typeof(RequestInterceptedEventArgs), OnRequestIntercepted); m_eventMap["requestServedFromCache"] = new DevToolsEventData(typeof(RequestServedFromCacheEventArgs), OnRequestServedFromCache); m_eventMap["requestWillBeSent"] = new DevToolsEventData(typeof(RequestWillBeSentEventArgs), OnRequestWillBeSent); m_eventMap["resourceChangedPriority"] = new DevToolsEventData(typeof(ResourceChangedPriorityEventArgs), OnResourceChangedPriority); m_eventMap["signedExchangeReceived"] = new DevToolsEventData(typeof(SignedExchangeReceivedEventArgs), OnSignedExchangeReceived); m_eventMap["responseReceived"] = new DevToolsEventData(typeof(ResponseReceivedEventArgs), OnResponseReceived); m_eventMap["webSocketClosed"] = new DevToolsEventData(typeof(WebSocketClosedEventArgs), OnWebSocketClosed); m_eventMap["webSocketCreated"] = new DevToolsEventData(typeof(WebSocketCreatedEventArgs), OnWebSocketCreated); m_eventMap["webSocketFrameError"] = new DevToolsEventData(typeof(WebSocketFrameErrorEventArgs), OnWebSocketFrameError); m_eventMap["webSocketFrameReceived"] = new DevToolsEventData(typeof(WebSocketFrameReceivedEventArgs), OnWebSocketFrameReceived); m_eventMap["webSocketFrameSent"] = new DevToolsEventData(typeof(WebSocketFrameSentEventArgs), OnWebSocketFrameSent); m_eventMap["webSocketHandshakeResponseReceived"] = new DevToolsEventData(typeof(WebSocketHandshakeResponseReceivedEventArgs), OnWebSocketHandshakeResponseReceived); m_eventMap["webSocketWillSendHandshakeRequest"] = new DevToolsEventData(typeof(WebSocketWillSendHandshakeRequestEventArgs), OnWebSocketWillSendHandshakeRequest); } /// <summary> /// Gets the DevToolsSession associated with the adapter. /// </summary> public DevToolsSession Session { get { return m_session; } } /// <summary> /// Fired when data chunk was received over the network. /// </summary> public event EventHandler<DataReceivedEventArgs> DataReceived; /// <summary> /// Fired when EventSource message is received. /// </summary> public event EventHandler<EventSourceMessageReceivedEventArgs> EventSourceMessageReceived; /// <summary> /// Fired when HTTP request has failed to load. /// </summary> public event EventHandler<LoadingFailedEventArgs> LoadingFailed; /// <summary> /// Fired when HTTP request has finished loading. /// </summary> public event EventHandler<LoadingFinishedEventArgs> LoadingFinished; /// <summary> /// Details of an intercepted HTTP request, which must be either allowed, blocked, modified or /// mocked. /// </summary> public event EventHandler<RequestInterceptedEventArgs> RequestIntercepted; /// <summary> /// Fired if request ended up loading from cache. /// </summary> public event EventHandler<RequestServedFromCacheEventArgs> RequestServedFromCache; /// <summary> /// Fired when page is about to send HTTP request. /// </summary> public event EventHandler<RequestWillBeSentEventArgs> RequestWillBeSent; /// <summary> /// Fired when resource loading priority is changed /// </summary> public event EventHandler<ResourceChangedPriorityEventArgs> ResourceChangedPriority; /// <summary> /// Fired when a signed exchange was received over the network /// </summary> public event EventHandler<SignedExchangeReceivedEventArgs> SignedExchangeReceived; /// <summary> /// Fired when HTTP response is available. /// </summary> public event EventHandler<ResponseReceivedEventArgs> ResponseReceived; /// <summary> /// Fired when WebSocket is closed. /// </summary> public event EventHandler<WebSocketClosedEventArgs> WebSocketClosed; /// <summary> /// Fired upon WebSocket creation. /// </summary> public event EventHandler<WebSocketCreatedEventArgs> WebSocketCreated; /// <summary> /// Fired when WebSocket message error occurs. /// </summary> public event EventHandler<WebSocketFrameErrorEventArgs> WebSocketFrameError; /// <summary> /// Fired when WebSocket message is received. /// </summary> public event EventHandler<WebSocketFrameReceivedEventArgs> WebSocketFrameReceived; /// <summary> /// Fired when WebSocket message is sent. /// </summary> public event EventHandler<WebSocketFrameSentEventArgs> WebSocketFrameSent; /// <summary> /// Fired when WebSocket handshake response becomes available. /// </summary> public event EventHandler<WebSocketHandshakeResponseReceivedEventArgs> WebSocketHandshakeResponseReceived; /// <summary> /// Fired when WebSocket is about to initiate handshake. /// </summary> public event EventHandler<WebSocketWillSendHandshakeRequestEventArgs> WebSocketWillSendHandshakeRequest; /// <summary> /// Tells whether clearing browser cache is supported. /// </summary> public async Task<CanClearBrowserCacheCommandResponse> CanClearBrowserCache(CanClearBrowserCacheCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<CanClearBrowserCacheCommandSettings, CanClearBrowserCacheCommandResponse>(command ?? new CanClearBrowserCacheCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Tells whether clearing browser cookies is supported. /// </summary> public async Task<CanClearBrowserCookiesCommandResponse> CanClearBrowserCookies(CanClearBrowserCookiesCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<CanClearBrowserCookiesCommandSettings, CanClearBrowserCookiesCommandResponse>(command ?? new CanClearBrowserCookiesCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Tells whether emulation of network conditions is supported. /// </summary> public async Task<CanEmulateNetworkConditionsCommandResponse> CanEmulateNetworkConditions(CanEmulateNetworkConditionsCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<CanEmulateNetworkConditionsCommandSettings, CanEmulateNetworkConditionsCommandResponse>(command ?? new CanEmulateNetworkConditionsCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Clears browser cache. /// </summary> public async Task<ClearBrowserCacheCommandResponse> ClearBrowserCache(ClearBrowserCacheCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<ClearBrowserCacheCommandSettings, ClearBrowserCacheCommandResponse>(command ?? new ClearBrowserCacheCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Clears browser cookies. /// </summary> public async Task<ClearBrowserCookiesCommandResponse> ClearBrowserCookies(ClearBrowserCookiesCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<ClearBrowserCookiesCommandSettings, ClearBrowserCookiesCommandResponse>(command ?? new ClearBrowserCookiesCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Response to Network.requestIntercepted which either modifies the request to continue with any /// modifications, or blocks it, or completes it with the provided response bytes. If a network /// fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted /// event will be sent with the same InterceptionId. /// </summary> public async Task<ContinueInterceptedRequestCommandResponse> ContinueInterceptedRequest(ContinueInterceptedRequestCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<ContinueInterceptedRequestCommandSettings, ContinueInterceptedRequestCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Deletes browser cookies with matching name and url or domain/path pair. /// </summary> public async Task<DeleteCookiesCommandResponse> DeleteCookies(DeleteCookiesCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<DeleteCookiesCommandSettings, DeleteCookiesCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Disables network tracking, prevents network events from being sent to the client. /// </summary> public async Task<DisableCommandResponse> Disable(DisableCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<DisableCommandSettings, DisableCommandResponse>(command ?? new DisableCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Activates emulation of network conditions. /// </summary> public async Task<EmulateNetworkConditionsCommandResponse> EmulateNetworkConditions(EmulateNetworkConditionsCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<EmulateNetworkConditionsCommandSettings, EmulateNetworkConditionsCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Enables network tracking, network events will now be delivered to the client. /// </summary> public async Task<EnableCommandResponse> Enable(EnableCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<EnableCommandSettings, EnableCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Returns all browser cookies. Depending on the backend support, will return detailed cookie /// information in the `cookies` field. /// </summary> public async Task<GetAllCookiesCommandResponse> GetAllCookies(GetAllCookiesCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<GetAllCookiesCommandSettings, GetAllCookiesCommandResponse>(command ?? new GetAllCookiesCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Returns the DER-encoded certificate. /// </summary> public async Task<GetCertificateCommandResponse> GetCertificate(GetCertificateCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<GetCertificateCommandSettings, GetCertificateCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Returns all browser cookies for the current URL. Depending on the backend support, will return /// detailed cookie information in the `cookies` field. /// </summary> public async Task<GetCookiesCommandResponse> GetCookies(GetCookiesCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<GetCookiesCommandSettings, GetCookiesCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Returns content served for the given request. /// </summary> public async Task<GetResponseBodyCommandResponse> GetResponseBody(GetResponseBodyCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<GetResponseBodyCommandSettings, GetResponseBodyCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Returns post data sent with the request. Returns an error when no data was sent with the request. /// </summary> public async Task<GetRequestPostDataCommandResponse> GetRequestPostData(GetRequestPostDataCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<GetRequestPostDataCommandSettings, GetRequestPostDataCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Returns content served for the given currently intercepted request. /// </summary> public async Task<GetResponseBodyForInterceptionCommandResponse> GetResponseBodyForInterception(GetResponseBodyForInterceptionCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<GetResponseBodyForInterceptionCommandSettings, GetResponseBodyForInterceptionCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Returns a handle to the stream representing the response body. Note that after this command, /// the intercepted request can't be continued as is -- you either need to cancel it or to provide /// the response body. The stream only supports sequential read, IO.read will fail if the position /// is specified. /// </summary> public async Task<TakeResponseBodyForInterceptionAsStreamCommandResponse> TakeResponseBodyForInterceptionAsStream(TakeResponseBodyForInterceptionAsStreamCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<TakeResponseBodyForInterceptionAsStreamCommandSettings, TakeResponseBodyForInterceptionAsStreamCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// This method sends a new XMLHttpRequest which is identical to the original one. The following /// parameters should be identical: method, url, async, request body, extra headers, withCredentials /// attribute, user, password. /// </summary> public async Task<ReplayXHRCommandResponse> ReplayXHR(ReplayXHRCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<ReplayXHRCommandSettings, ReplayXHRCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Searches for given string in response content. /// </summary> public async Task<SearchInResponseBodyCommandResponse> SearchInResponseBody(SearchInResponseBodyCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SearchInResponseBodyCommandSettings, SearchInResponseBodyCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Blocks URLs from loading. /// </summary> public async Task<SetBlockedURLsCommandResponse> SetBlockedURLs(SetBlockedURLsCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetBlockedURLsCommandSettings, SetBlockedURLsCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Toggles ignoring of service worker for each request. /// </summary> public async Task<SetBypassServiceWorkerCommandResponse> SetBypassServiceWorker(SetBypassServiceWorkerCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetBypassServiceWorkerCommandSettings, SetBypassServiceWorkerCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Toggles ignoring cache for each request. If `true`, cache will not be used. /// </summary> public async Task<SetCacheDisabledCommandResponse> SetCacheDisabled(SetCacheDisabledCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetCacheDisabledCommandSettings, SetCacheDisabledCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. /// </summary> public async Task<SetCookieCommandResponse> SetCookie(SetCookieCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetCookieCommandSettings, SetCookieCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Sets given cookies. /// </summary> public async Task<SetCookiesCommandResponse> SetCookies(SetCookiesCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetCookiesCommandSettings, SetCookiesCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// For testing. /// </summary> public async Task<SetDataSizeLimitsForTestCommandResponse> SetDataSizeLimitsForTest(SetDataSizeLimitsForTestCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetDataSizeLimitsForTestCommandSettings, SetDataSizeLimitsForTestCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Specifies whether to always send extra HTTP headers with the requests from this page. /// </summary> public async Task<SetExtraHTTPHeadersCommandResponse> SetExtraHTTPHeaders(SetExtraHTTPHeadersCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetExtraHTTPHeadersCommandSettings, SetExtraHTTPHeadersCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Sets the requests to intercept that match the provided patterns and optionally resource types. /// </summary> public async Task<SetRequestInterceptionCommandResponse> SetRequestInterception(SetRequestInterceptionCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetRequestInterceptionCommandSettings, SetRequestInterceptionCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Allows overriding user agent with the given string. /// </summary> public async Task<SetUserAgentOverrideCommandResponse> SetUserAgentOverride(SetUserAgentOverrideCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetUserAgentOverrideCommandSettings, SetUserAgentOverrideCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } private void OnDevToolsEventReceived(object sender, DevToolsEventReceivedEventArgs e) { if (e.DomainName == m_domainName) { if (m_eventMap.ContainsKey(e.EventName)) { var eventData = m_eventMap[e.EventName]; var eventArgs = e.EventData.ToObject(eventData.EventArgsType); eventData.EventInvoker(eventArgs); } } } private void OnDataReceived(object rawEventArgs) { DataReceivedEventArgs e = rawEventArgs as DataReceivedEventArgs; if (e != null && DataReceived != null) { DataReceived(this, e); } } private void OnEventSourceMessageReceived(object rawEventArgs) { EventSourceMessageReceivedEventArgs e = rawEventArgs as EventSourceMessageReceivedEventArgs; if (e != null && EventSourceMessageReceived != null) { EventSourceMessageReceived(this, e); } } private void OnLoadingFailed(object rawEventArgs) { LoadingFailedEventArgs e = rawEventArgs as LoadingFailedEventArgs; if (e != null && LoadingFailed != null) { LoadingFailed(this, e); } } private void OnLoadingFinished(object rawEventArgs) { LoadingFinishedEventArgs e = rawEventArgs as LoadingFinishedEventArgs; if (e != null && LoadingFinished != null) { LoadingFinished(this, e); } } private void OnRequestIntercepted(object rawEventArgs) { RequestInterceptedEventArgs e = rawEventArgs as RequestInterceptedEventArgs; if (e != null && RequestIntercepted != null) { RequestIntercepted(this, e); } } private void OnRequestServedFromCache(object rawEventArgs) { RequestServedFromCacheEventArgs e = rawEventArgs as RequestServedFromCacheEventArgs; if (e != null && RequestServedFromCache != null) { RequestServedFromCache(this, e); } } private void OnRequestWillBeSent(object rawEventArgs) { RequestWillBeSentEventArgs e = rawEventArgs as RequestWillBeSentEventArgs; if (e != null && RequestWillBeSent != null) { RequestWillBeSent(this, e); } } private void OnResourceChangedPriority(object rawEventArgs) { ResourceChangedPriorityEventArgs e = rawEventArgs as ResourceChangedPriorityEventArgs; if (e != null && ResourceChangedPriority != null) { ResourceChangedPriority(this, e); } } private void OnSignedExchangeReceived(object rawEventArgs) { SignedExchangeReceivedEventArgs e = rawEventArgs as SignedExchangeReceivedEventArgs; if (e != null && SignedExchangeReceived != null) { SignedExchangeReceived(this, e); } } private void OnResponseReceived(object rawEventArgs) { ResponseReceivedEventArgs e = rawEventArgs as ResponseReceivedEventArgs; if (e != null && ResponseReceived != null) { ResponseReceived(this, e); } } private void OnWebSocketClosed(object rawEventArgs) { WebSocketClosedEventArgs e = rawEventArgs as WebSocketClosedEventArgs; if (e != null && WebSocketClosed != null) { WebSocketClosed(this, e); } } private void OnWebSocketCreated(object rawEventArgs) { WebSocketCreatedEventArgs e = rawEventArgs as WebSocketCreatedEventArgs; if (e != null && WebSocketCreated != null) { WebSocketCreated(this, e); } } private void OnWebSocketFrameError(object rawEventArgs) { WebSocketFrameErrorEventArgs e = rawEventArgs as WebSocketFrameErrorEventArgs; if (e != null && WebSocketFrameError != null) { WebSocketFrameError(this, e); } } private void OnWebSocketFrameReceived(object rawEventArgs) { WebSocketFrameReceivedEventArgs e = rawEventArgs as WebSocketFrameReceivedEventArgs; if (e != null && WebSocketFrameReceived != null) { WebSocketFrameReceived(this, e); } } private void OnWebSocketFrameSent(object rawEventArgs) { WebSocketFrameSentEventArgs e = rawEventArgs as WebSocketFrameSentEventArgs; if (e != null && WebSocketFrameSent != null) { WebSocketFrameSent(this, e); } } private void OnWebSocketHandshakeResponseReceived(object rawEventArgs) { WebSocketHandshakeResponseReceivedEventArgs e = rawEventArgs as WebSocketHandshakeResponseReceivedEventArgs; if (e != null && WebSocketHandshakeResponseReceived != null) { WebSocketHandshakeResponseReceived(this, e); } } private void OnWebSocketWillSendHandshakeRequest(object rawEventArgs) { WebSocketWillSendHandshakeRequestEventArgs e = rawEventArgs as WebSocketWillSendHandshakeRequestEventArgs; if (e != null && WebSocketWillSendHandshakeRequest != null) { WebSocketWillSendHandshakeRequest(this, e); } } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // 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 -- License Terms -- using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using MsgPack.Rpc.Protocols.Filters; [module: SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Scope = "member", Target = "MsgPack.Rpc.Server.RpcServerConfiguration.#RequestContextPoolProvider" )] [module: SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Scope = "member", Target = "MsgPack.Rpc.Server.RpcServerConfiguration.#TcpTransportPoolProvider" )] [module: SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Scope = "member", Target = "MsgPack.Rpc.Server.RpcServerConfiguration.#ListeningContextPoolProvider" )] [module: SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Scope = "member", Target = "MsgPack.Rpc.Server.RpcServerConfiguration.#UdpTransportPoolProvider" )] [module: SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Scope = "member", Target = "MsgPack.Rpc.Server.RpcServerConfiguration.#ApplicationContextPoolProvider" )] [module: SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Scope = "member", Target = "MsgPack.Rpc.Server.RpcServerConfiguration.#ResponseContextPoolProvider" )] [module: SuppressMessage( "Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "MsgPack.Rpc.Server.RpcServerConfiguration.#ToString`1(!!0,System.Text.StringBuilder)", Justification = "Boolean value should be lower case." )] namespace MsgPack.Rpc.Server { /// <summary> /// Represents server configuration. /// </summary> public sealed partial class RpcServerConfiguration : FreezableObject { private static readonly RpcServerConfiguration _default = new RpcServerConfiguration().Freeze(); /// <summary> /// Gets the default frozen instance. /// </summary> /// <value> /// The default frozen instance. /// This value will not be <c>null</c>. /// </value> public static RpcServerConfiguration Default { get { Contract.Ensures( Contract.Result<RpcServerConfiguration>() != null ); return RpcServerConfiguration._default; } } private IList<MessageFilterProvider> _filterProviders = new List<MessageFilterProvider>(); /// <summary> /// Gets the filter providers collection. /// </summary> /// <value> /// The filter providers collection. Default is empty. /// </value> public IList<MessageFilterProvider> FilterProviders { get { return this._filterProviders; } } /// <summary> /// Initializes a new instance of the <see cref="RpcServerConfiguration"/> class. /// </summary> public RpcServerConfiguration() { } /// <summary> /// Creates the <see cref="ObjectPoolConfiguration"/> for the <see cref="MsgPack.Rpc.Server.Protocols.ListeningContext"/> pool corresponds to values of this instance. /// </summary> /// <returns> /// The <see cref="ObjectPoolConfiguration"/> for the <see cref="MsgPack.Rpc.Server.Protocols.ListeningContext"/> pool corresponds to values of this instance. /// This value will not be <c>null</c>. /// </returns> public ObjectPoolConfiguration CreateListeningContextPoolConfiguration() { Contract.Ensures( Contract.Result<ObjectPoolConfiguration>() != null ); return new ObjectPoolConfiguration() { ExhausionPolicy = ExhausionPolicy.ThrowException, MaximumPooled = this.MaximumConnection, MinimumReserved = this.MinimumConnection }; } /// <summary> /// Creates the <see cref="ObjectPoolConfiguration"/> for the transport pool corresponds to values of this instance. /// </summary> /// <returns> /// The <see cref="ObjectPoolConfiguration"/> for the transport pool corresponds to values of this instance. /// This value will not be <c>null</c>. /// </returns> public ObjectPoolConfiguration CreateTransportPoolConfiguration() { Contract.Ensures( Contract.Result<ObjectPoolConfiguration>() != null ); return new ObjectPoolConfiguration() { ExhausionPolicy = ExhausionPolicy.BlockUntilAvailable, MaximumPooled = this.MaximumConcurrentRequest, MinimumReserved = this.MinimumConcurrentRequest }; } /// <summary> /// Creates the <see cref="ObjectPoolConfiguration"/> for the RPC application context pool corresponds to values of this instance. /// </summary> /// <returns> /// The <see cref="ObjectPoolConfiguration"/> for the transport pool corresponds to values of this instance. /// This value will not be <c>null</c>. /// </returns> public ObjectPoolConfiguration CreateApplicationContextPoolConfiguration() { Contract.Ensures( Contract.Result<ObjectPoolConfiguration>() != null ); return new ObjectPoolConfiguration() { ExhausionPolicy = ExhausionPolicy.BlockUntilAvailable, MaximumPooled = this.MaximumConcurrentRequest, MinimumReserved = this.MinimumConcurrentRequest }; } /// <summary> /// Creates the <see cref="ObjectPoolConfiguration"/> for the <see cref="MsgPack.Rpc.Server.Protocols.ServerRequestContext"/> pool corresponds to values of this instance. /// </summary> /// <returns> /// The <see cref="ObjectPoolConfiguration"/> for the <see cref="MsgPack.Rpc.Server.Protocols.ServerRequestContext"/> pool corresponds to values of this instance. /// This value will not be <c>null</c>. /// </returns> public ObjectPoolConfiguration CreateRequestContextPoolConfiguration() { Contract.Ensures( Contract.Result<ObjectPoolConfiguration>() != null ); return new ObjectPoolConfiguration() { ExhausionPolicy = ExhausionPolicy.BlockUntilAvailable, MaximumPooled = this.MaximumConcurrentRequest, MinimumReserved = this.MinimumConcurrentRequest }; } /// <summary> /// Creates the <see cref="ObjectPoolConfiguration"/> for the <see cref="MsgPack.Rpc.Server.Protocols.ServerResponseContext"/> pool corresponds to values of this instance. /// </summary> /// <returns> /// The <see cref="ObjectPoolConfiguration"/> for the <see cref="MsgPack.Rpc.Server.Protocols.ServerResponseContext"/> pool corresponds to values of this instance. /// This value will not be <c>null</c>. /// </returns> public ObjectPoolConfiguration CreateResponseContextPoolConfiguration() { Contract.Ensures( Contract.Result<ObjectPoolConfiguration>() != null ); return new ObjectPoolConfiguration() { ExhausionPolicy = ExhausionPolicy.BlockUntilAvailable, MaximumPooled = this.MaximumConcurrentRequest, MinimumReserved = this.MinimumConcurrentRequest }; } /// <summary> /// Clones all of the fields of this instance. /// </summary> /// <returns> /// The shallow copy of this instance. /// </returns> public RpcServerConfiguration Clone() { Contract.Ensures( Contract.Result<RpcServerConfiguration>() != null ); Contract.Ensures( !Object.ReferenceEquals( Contract.Result<RpcServerConfiguration>(), this ) ); Contract.Ensures( Contract.Result<RpcServerConfiguration>().IsFrozen == this.IsFrozen ); return this.CloneCore() as RpcServerConfiguration; } /// <summary> /// Freezes this instance. /// </summary> /// <returns> /// This instance. /// </returns> public RpcServerConfiguration Freeze() { Contract.Ensures( Object.ReferenceEquals( Contract.Result<RpcServerConfiguration>(), this ) ); Contract.Ensures( this.IsFrozen ); return this.FreezeCore() as RpcServerConfiguration; } /// <summary> /// Gets the frozen copy of this instance. /// </summary> /// <returns> /// This instance if it is already frozen. /// Otherwise, frozen copy of this instance. /// </returns> public RpcServerConfiguration AsFrozen() { Contract.Ensures( Contract.Result<RpcServerConfiguration>() != null ); Contract.Ensures( !Object.ReferenceEquals( Contract.Result<RpcServerConfiguration>(), this ) ); Contract.Ensures( Contract.Result<RpcServerConfiguration>().IsFrozen ); Contract.Ensures( this.IsFrozen == Contract.OldValue( this.IsFrozen ) ); return this.AsFrozenCore() as RpcServerConfiguration; } /// <summary> /// Clones all of the fields of this instance. /// </summary> /// <returns> /// The shallow copy of this instance. Returned instance always is not frozen. /// </returns> protected override FreezableObject CloneCore() { var result = base.CloneCore() as RpcServerConfiguration; result._filterProviders = new List<MessageFilterProvider>( result._filterProviders ); return result; } /// <summary> /// Freezes this instance. /// </summary> /// <returns> /// This instance. /// </returns> protected override FreezableObject FreezeCore() { var result = base.FreezeCore() as RpcServerConfiguration; result._filterProviders = new ReadOnlyCollection<MessageFilterProvider>( result._filterProviders ); return result; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using Mono.Addins; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.World.Land { public class ParcelCounts { public int Owner = 0; public int Group = 0; public int Others = 0; public int Selected = 0; public Dictionary <UUID, int> Users = new Dictionary <UUID, int>(); } [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "PrimCountModule")] public class PrimCountModule : IPrimCountModule, INonSharedRegionModule { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_Scene; private Dictionary<UUID, PrimCounts> m_PrimCounts = new Dictionary<UUID, PrimCounts>(); private Dictionary<UUID, UUID> m_OwnerMap = new Dictionary<UUID, UUID>(); private Dictionary<UUID, int> m_SimwideCounts = new Dictionary<UUID, int>(); private Dictionary<UUID, ParcelCounts> m_ParcelCounts = new Dictionary<UUID, ParcelCounts>(); /// <value> /// For now, a simple simwide taint to get this up. Later parcel based /// taint to allow recounting a parcel if only ownership has changed /// without recounting the whole sim. /// /// We start out tainted so that the first get call resets the various prim counts. /// </value> private bool m_Tainted = true; private Object m_TaintLock = new Object(); public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { } public void AddRegion(Scene scene) { m_Scene = scene; m_Scene.RegisterModuleInterface<IPrimCountModule>(this); m_Scene.EventManager.OnObjectAddedToScene += OnParcelPrimCountAdd; m_Scene.EventManager.OnObjectBeingRemovedFromScene += OnObjectBeingRemovedFromScene; m_Scene.EventManager.OnParcelPrimCountTainted += OnParcelPrimCountTainted; m_Scene.EventManager.OnLandObjectAdded += delegate(ILandObject lo) { OnParcelPrimCountTainted(); }; } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { } public void Close() { } public string Name { get { return "PrimCountModule"; } } private void OnParcelPrimCountAdd(SceneObjectGroup obj) { // If we're tainted already, don't bother to add. The next // access will cause a recount anyway lock (m_TaintLock) { if (!m_Tainted) AddObject(obj); // else // m_log.DebugFormat( // "[PRIM COUNT MODULE]: Ignoring OnParcelPrimCountAdd() for {0} on {1} since count is tainted", // obj.Name, m_Scene.RegionInfo.RegionName); } } private void OnObjectBeingRemovedFromScene(SceneObjectGroup obj) { // Don't bother to update tainted counts lock (m_TaintLock) { if (!m_Tainted) RemoveObject(obj); // else // m_log.DebugFormat( // "[PRIM COUNT MODULE]: Ignoring OnObjectBeingRemovedFromScene() for {0} on {1} since count is tainted", // obj.Name, m_Scene.RegionInfo.RegionName); } } private void OnParcelPrimCountTainted() { // m_log.DebugFormat( // "[PRIM COUNT MODULE]: OnParcelPrimCountTainted() called on {0}", m_Scene.RegionInfo.RegionName); lock (m_TaintLock) m_Tainted = true; } public void TaintPrimCount(ILandObject land) { lock (m_TaintLock) m_Tainted = true; } public void TaintPrimCount(int x, int y) { lock (m_TaintLock) m_Tainted = true; } public void TaintPrimCount() { lock (m_TaintLock) m_Tainted = true; } // NOTE: Call under Taint Lock private void AddObject(SceneObjectGroup obj) { if (obj.IsAttachment) return; if (((obj.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)) return; Vector3 pos = obj.AbsolutePosition; ILandObject landObject = m_Scene.LandChannel.GetLandObject(pos.X, pos.Y); // If for some reason there is no land object (perhaps the object is out of bounds) then we can't count it if (landObject == null) { // m_log.WarnFormat( // "[PRIM COUNT MODULE]: Found no land object for {0} at position ({1}, {2}) on {3}", // obj.Name, pos.X, pos.Y, m_Scene.RegionInfo.RegionName); return; } LandData landData = landObject.LandData; // m_log.DebugFormat( // "[PRIM COUNT MODULE]: Adding object {0} with {1} parts to prim count for parcel {2} on {3}", // obj.Name, obj.Parts.Length, landData.Name, m_Scene.RegionInfo.RegionName); // m_log.DebugFormat( // "[PRIM COUNT MODULE]: Object {0} is owned by {1} over land owned by {2}", // obj.Name, obj.OwnerID, landData.OwnerID); ParcelCounts parcelCounts; if (m_ParcelCounts.TryGetValue(landData.GlobalID, out parcelCounts)) { UUID landOwner = landData.OwnerID; int partCount = obj.GetPartCount(); m_SimwideCounts[landOwner] += partCount; if (parcelCounts.Users.ContainsKey(obj.OwnerID)) parcelCounts.Users[obj.OwnerID] += partCount; else parcelCounts.Users[obj.OwnerID] = partCount; if (obj.IsSelected || obj.GetSittingAvatarsCount() > 0) parcelCounts.Selected += partCount; if (obj.OwnerID == landData.OwnerID) parcelCounts.Owner += partCount; else if (landData.GroupID != UUID.Zero && obj.GroupID == landData.GroupID) parcelCounts.Group += partCount; else parcelCounts.Others += partCount; } } // NOTE: Call under Taint Lock private void RemoveObject(SceneObjectGroup obj) { // m_log.DebugFormat("[PRIM COUNT MODULE]: Removing object {0} {1} from prim count", obj.Name, obj.UUID); // Currently this is being done by tainting the count instead. } public IPrimCounts GetPrimCounts(UUID parcelID) { // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetPrimCounts for parcel {0} in {1}", parcelID, m_Scene.RegionInfo.RegionName); PrimCounts primCounts; lock (m_PrimCounts) { if (m_PrimCounts.TryGetValue(parcelID, out primCounts)) return primCounts; primCounts = new PrimCounts(parcelID, this); m_PrimCounts[parcelID] = primCounts; } return primCounts; } /// <summary> /// Get the number of prims on the parcel that are owned by the parcel owner. /// </summary> /// <param name="parcelID"></param> /// <returns></returns> public int GetOwnerCount(UUID parcelID) { int count = 0; lock (m_TaintLock) { if (m_Tainted) Recount(); ParcelCounts counts; if (m_ParcelCounts.TryGetValue(parcelID, out counts)) count = counts.Owner; } // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetOwnerCount for parcel {0} in {1} returning {2}", // parcelID, m_Scene.RegionInfo.RegionName, count); return count; } /// <summary> /// Get the number of prims on the parcel that have been set to the group that owns the parcel. /// </summary> /// <param name="parcelID"></param> /// <returns></returns> public int GetGroupCount(UUID parcelID) { int count = 0; lock (m_TaintLock) { if (m_Tainted) Recount(); ParcelCounts counts; if (m_ParcelCounts.TryGetValue(parcelID, out counts)) count = counts.Group; } // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetGroupCount for parcel {0} in {1} returning {2}", // parcelID, m_Scene.RegionInfo.RegionName, count); return count; } /// <summary> /// Get the number of prims on the parcel that are not owned by the parcel owner or set to the parcel group. /// </summary> /// <param name="parcelID"></param> /// <returns></returns> public int GetOthersCount(UUID parcelID) { int count = 0; lock (m_TaintLock) { if (m_Tainted) Recount(); ParcelCounts counts; if (m_ParcelCounts.TryGetValue(parcelID, out counts)) count = counts.Others; } // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetOthersCount for parcel {0} in {1} returning {2}", // parcelID, m_Scene.RegionInfo.RegionName, count); return count; } /// <summary> /// Get the number of selected prims. /// </summary> /// <param name="parcelID"></param> /// <returns></returns> public int GetSelectedCount(UUID parcelID) { int count = 0; lock (m_TaintLock) { if (m_Tainted) Recount(); ParcelCounts counts; if (m_ParcelCounts.TryGetValue(parcelID, out counts)) count = counts.Selected; } // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetSelectedCount for parcel {0} in {1} returning {2}", // parcelID, m_Scene.RegionInfo.RegionName, count); return count; } /// <summary> /// Get the total count of owner, group and others prims on the parcel. /// FIXME: Need to do selected prims once this is reimplemented. /// </summary> /// <param name="parcelID"></param> /// <returns></returns> public int GetTotalCount(UUID parcelID) { int count = 0; lock (m_TaintLock) { if (m_Tainted) Recount(); ParcelCounts counts; if (m_ParcelCounts.TryGetValue(parcelID, out counts)) { count = counts.Owner; count += counts.Group; count += counts.Others; } } // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetTotalCount for parcel {0} in {1} returning {2}", // parcelID, m_Scene.RegionInfo.RegionName, count); return count; } /// <summary> /// Get the number of prims that are in the entire simulator for the owner of this parcel. /// </summary> /// <param name="parcelID"></param> /// <returns></returns> public int GetSimulatorCount(UUID parcelID) { int count = 0; lock (m_TaintLock) { if (m_Tainted) Recount(); UUID owner; if (m_OwnerMap.TryGetValue(parcelID, out owner)) { int val; if (m_SimwideCounts.TryGetValue(owner, out val)) count = val; } } // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetOthersCount for parcel {0} in {1} returning {2}", // parcelID, m_Scene.RegionInfo.RegionName, count); return count; } /// <summary> /// Get the number of prims that a particular user owns on this parcel. /// </summary> /// <param name="parcelID"></param> /// <param name="userID"></param> /// <returns></returns> public int GetUserCount(UUID parcelID, UUID userID) { int count = 0; lock (m_TaintLock) { if (m_Tainted) Recount(); ParcelCounts counts; if (m_ParcelCounts.TryGetValue(parcelID, out counts)) { int val; if (counts.Users.TryGetValue(userID, out val)) count = val; } } // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetUserCount for user {0} in parcel {1} in region {2} returning {3}", // userID, parcelID, m_Scene.RegionInfo.RegionName, count); return count; } // NOTE: This method MUST be called while holding the taint lock! private void Recount() { // m_log.DebugFormat("[PRIM COUNT MODULE]: Recounting prims on {0}", m_Scene.RegionInfo.RegionName); m_OwnerMap.Clear(); m_SimwideCounts.Clear(); m_ParcelCounts.Clear(); List<ILandObject> land = m_Scene.LandChannel.AllParcels(); foreach (ILandObject l in land) { LandData landData = l.LandData; m_OwnerMap[landData.GlobalID] = landData.OwnerID; m_SimwideCounts[landData.OwnerID] = 0; // m_log.DebugFormat( // "[PRIM COUNT MODULE]: Initializing parcel count for {0} on {1}", // landData.Name, m_Scene.RegionInfo.RegionName); m_ParcelCounts[landData.GlobalID] = new ParcelCounts(); } m_Scene.ForEachSOG(AddObject); lock (m_PrimCounts) { List<UUID> primcountKeys = new List<UUID>(m_PrimCounts.Keys); foreach (UUID k in primcountKeys) { if (!m_OwnerMap.ContainsKey(k)) m_PrimCounts.Remove(k); } } m_Tainted = false; } } public class PrimCounts : IPrimCounts { private PrimCountModule m_Parent; private UUID m_ParcelID; private UserPrimCounts m_UserPrimCounts; public PrimCounts (UUID parcelID, PrimCountModule parent) { m_ParcelID = parcelID; m_Parent = parent; m_UserPrimCounts = new UserPrimCounts(this); } public int Owner { get { return m_Parent.GetOwnerCount(m_ParcelID); } } public int Group { get { return m_Parent.GetGroupCount(m_ParcelID); } } public int Others { get { return m_Parent.GetOthersCount(m_ParcelID); } } public int Selected { get { return m_Parent.GetSelectedCount(m_ParcelID); } } public int Total { get { return m_Parent.GetTotalCount(m_ParcelID); } } public int Simulator { get { return m_Parent.GetSimulatorCount(m_ParcelID); } } public IUserPrimCounts Users { get { return m_UserPrimCounts; } } public int GetUserCount(UUID userID) { return m_Parent.GetUserCount(m_ParcelID, userID); } } public class UserPrimCounts : IUserPrimCounts { private PrimCounts m_Parent; public UserPrimCounts(PrimCounts parent) { m_Parent = parent; } public int this[UUID userID] { get { return m_Parent.GetUserCount(userID); } } } }
/* * 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 NUnit.Framework; using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer; using Document = Lucene.Net.Documents.Document; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using MultiReader = Lucene.Net.Index.MultiReader; using MaxFieldLength = Lucene.Net.Index.IndexWriter.MaxFieldLength; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using ReaderUtil = Lucene.Net.Util.ReaderUtil; namespace Lucene.Net.Search { public class QueryUtils { [Serializable] private class AnonymousClassQuery:Query { public override System.String ToString(System.String field) { return "My Whacky Query"; } } private class AnonymousClassCollector:Collector { public AnonymousClassCollector(int[] order, int[] opidx, int skip_op, IndexReader[] lastReader, float maxDiff, Query q, IndexSearcher s, int[] lastDoc) { InitBlock(order, opidx, skip_op, lastReader, maxDiff, q, s, lastDoc); } private void InitBlock(int[] order, int[] opidx, int skip_op, IndexReader[] lastReader, float maxDiff, Query q, IndexSearcher s, int[] lastDoc) { this.order = order; this.opidx = opidx; this.lastDoc = lastDoc; this.skip_op = skip_op; this.scorer = scorer; this.lastReader = lastReader; this.maxDiff = maxDiff; this.q = q; this.s = s; } private Scorer sc; private IndexReader reader; private Scorer scorer; private int[] order; private int[] lastDoc; private int[] opidx; private int skip_op; private float maxDiff; private Lucene.Net.Search.Query q; private Lucene.Net.Search.IndexSearcher s; private IndexReader[] lastReader; public override void SetScorer(Scorer scorer) { this.sc = scorer; } public override void Collect(int doc) { float score = sc.Score(); lastDoc[0] = doc; try { if (scorer == null) { Weight w = q.Weight(s); scorer = w.Scorer(reader, true, false); } int op = order[(opidx[0]++) % order.Length]; // System.out.println(op==skip_op ? // "skip("+(sdoc[0]+1)+")":"next()"); bool more = op == skip_op ? scorer.Advance(scorer.DocID() + 1) != DocIdSetIterator.NO_MORE_DOCS : scorer.NextDoc() != DocIdSetIterator.NO_MORE_DOCS; int scorerDoc = scorer.DocID(); float scorerScore = scorer.Score(); float scorerScore2 = scorer.Score(); float scoreDiff = System.Math.Abs(score - scorerScore); float scorerDiff = System.Math.Abs(scorerScore2 - scorerScore); if (!more || doc != scorerDoc || scoreDiff > maxDiff || scorerDiff > maxDiff) { System.Text.StringBuilder sbord = new System.Text.StringBuilder(); for (int i = 0; i < order.Length; i++) sbord.Append(order[i] == skip_op?" skip()":" next()"); throw new System.SystemException("ERROR matching docs:" + "\n\t" + (doc != scorerDoc ? "--> " : "") + "scorerDoc=" + scorerDoc + "\n\t" + (!more ? "--> " : "") + "tscorer.more=" + more + "\n\t" + (scoreDiff > maxDiff ? "--> " : "") + "scorerScore=" + scorerScore + " scoreDiff=" + scoreDiff + " maxDiff=" + maxDiff + "\n\t" + (scorerDiff > maxDiff ? "--> " : "") + "scorerScore2=" + scorerScore2 + " scorerDiff=" + scorerDiff + "\n\thitCollector.doc=" + doc + " score=" + score + "\n\t Scorer=" + scorer + "\n\t Query=" + q + " " + q.GetType().FullName + "\n\t Searcher=" + s + "\n\t Order=" + sbord + "\n\t Op=" + (op == skip_op ? " skip()" : " next()")); } } catch (System.IO.IOException e) { throw new System.SystemException("", e); } } public override void SetNextReader(IndexReader reader, int docBase) { // confirm that skipping beyond the last doc, on the // previous reader, hits NO_MORE_DOCS if (lastReader[0] != null) { IndexReader previousReader = lastReader[0]; Weight w = q.Weight(new IndexSearcher(previousReader)); Scorer scorer = w.Scorer(previousReader, true, false); if (scorer != null) { bool more = scorer.Advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS; Assert.IsFalse(more, "query's last doc was "+ lastDoc[0] +" but skipTo("+(lastDoc[0]+1)+") got to "+scorer.DocID()); } } this.reader = reader; this.scorer = null; lastDoc[0] = -1; } public override bool AcceptsDocsOutOfOrder { get { return true; } } } private class AnonymousClassCollector1:Collector { public AnonymousClassCollector1(int[] lastDoc, Lucene.Net.Search.Query q, Lucene.Net.Search.IndexSearcher s, float maxDiff, IndexReader[] lastReader) { InitBlock(lastDoc, q, s, maxDiff, lastReader); } private void InitBlock(int[] lastDoc, Lucene.Net.Search.Query q, Lucene.Net.Search.IndexSearcher s, float maxDiff, IndexReader[] lastReader) { this.lastDoc = lastDoc; this.q = q; this.s = s; this.maxDiff = maxDiff; this.lastReader = lastReader; } private int[] lastDoc; private Lucene.Net.Search.Query q; private Lucene.Net.Search.IndexSearcher s; private float maxDiff; private Scorer scorer; private IndexReader reader; private IndexReader[] lastReader; public override void SetScorer(Scorer scorer) { this.scorer = scorer; } public override void Collect(int doc) { //System.out.println("doc="+doc); float score = this.scorer.Score(); try { for (int i = lastDoc[0] + 1; i <= doc; i++) { Weight w = q.Weight(s); Scorer scorer = w.Scorer(reader, true, false); Assert.IsTrue(scorer.Advance(i) != DocIdSetIterator.NO_MORE_DOCS, "query collected " + doc + " but skipTo(" + i + ") says no more docs!"); Assert.AreEqual(doc, scorer.DocID(), "query collected " + doc + " but skipTo(" + i + ") got to " + scorer.DocID()); float skipToScore = scorer.Score(); Assert.AreEqual(skipToScore, scorer.Score(), maxDiff, "unstable skipTo(" + i + ") score!"); Assert.AreEqual(score, skipToScore, maxDiff, "query assigned doc " + doc + " a score of <" + score + "> but skipTo(" + i + ") has <" + skipToScore + ">!"); } lastDoc[0] = doc; } catch (System.IO.IOException e) { throw new System.SystemException("", e); } } public override void SetNextReader(IndexReader reader, int docBase) { // confirm that skipping beyond the last doc, on the // previous reader, hits NO_MORE_DOCS if (lastReader[0] != null) { IndexReader previousReader = lastReader[0]; Weight w = q.Weight(new IndexSearcher(previousReader)); Scorer scorer = w.Scorer(previousReader, true, false); if (scorer != null) { bool more = scorer.Advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS; Assert.IsFalse(more, "query's last doc was " + lastDoc[0] + " but skipTo(" + (lastDoc[0] + 1) + ") got to " + scorer.DocID()); } } this.reader = lastReader[0] = reader; lastDoc[0] = -1; } public override bool AcceptsDocsOutOfOrder { get { return false; } } } /// <summary>Check the types of things query objects should be able to do. </summary> public static void Check(Query q) { CheckHashEquals(q); } /// <summary>check very basic hashCode and equals </summary> public static void CheckHashEquals(Query q) { Query q2 = (Query) q.Clone(); CheckEqual(q, q2); Query q3 = (Query) q.Clone(); q3.Boost = 7.21792348f; CheckUnequal(q, q3); // test that a class check is done so that no exception is thrown // in the implementation of equals() Query whacky = new AnonymousClassQuery(); whacky.Boost = q.Boost; CheckUnequal(q, whacky); } public static void CheckEqual(Query q1, Query q2) { Assert.AreEqual(q1, q2); Assert.AreEqual(q1.GetHashCode(), q2.GetHashCode()); } public static void CheckUnequal(Query q1, Query q2) { Assert.IsTrue(!q1.Equals(q2)); Assert.IsTrue(!q2.Equals(q1)); // possible this test can fail on a hash collision... if that // happens, please change test to use a different example. Assert.IsTrue(q1.GetHashCode() != q2.GetHashCode()); } /// <summary>deep check that explanations of a query 'score' correctly </summary> public static void CheckExplanations(Query q, Searcher s) { CheckHits.CheckExplanations(q, null, s, true); } /// <summary> Various query sanity checks on a searcher, some checks are only done for /// instanceof IndexSearcher. /// /// </summary> /// <seealso cref="Check(Query)"> /// </seealso> /// <seealso cref="checkFirstSkipTo"> /// </seealso> /// <seealso cref="checkSkipTo"> /// </seealso> /// <seealso cref="checkExplanations"> /// </seealso> /// <seealso cref="checkSerialization"> /// </seealso> /// <seealso cref="checkEqual"> /// </seealso> public static void Check(Query q1, Searcher s) { Check(q1, s, true); } private static void Check(Query q1, Searcher s, bool wrap) { try { Check(q1); if (s != null) { if (s is IndexSearcher) { IndexSearcher is_Renamed = (IndexSearcher) s; CheckFirstSkipTo(q1, is_Renamed); CheckSkipTo(q1, is_Renamed); if (wrap) { Check(q1, WrapUnderlyingReader(is_Renamed, - 1), false); Check(q1, WrapUnderlyingReader(is_Renamed, 0), false); Check(q1, WrapUnderlyingReader(is_Renamed, + 1), false); } } if (wrap) { Check(q1, WrapSearcher(s, - 1), false); Check(q1, WrapSearcher(s, 0), false); Check(q1, WrapSearcher(s, + 1), false); } CheckExplanations(q1, s); CheckSerialization(q1, s); Query q2 = (Query) q1.Clone(); CheckEqual(s.Rewrite(q1), s.Rewrite(q2)); } } catch (System.IO.IOException e) { throw new System.SystemException("", e); } } /// <summary> Given an IndexSearcher, returns a new IndexSearcher whose IndexReader /// is a MultiReader containing the Reader of the original IndexSearcher, /// as well as several "empty" IndexReaders -- some of which will have /// deleted documents in them. This new IndexSearcher should /// behave exactly the same as the original IndexSearcher. /// </summary> /// <param name="s">the searcher to wrap /// </param> /// <param name="edge">if negative, s will be the first sub; if 0, s will be in the middle, if positive s will be the last sub /// </param> public static IndexSearcher WrapUnderlyingReader(IndexSearcher s, int edge) { IndexReader r = s.IndexReader; // we can't put deleted docs before the nested reader, because // it will throw off the docIds IndexReader[] readers = new IndexReader[] { edge < 0 ? r : IndexReader.Open(MakeEmptyIndex(0), true), IndexReader.Open(MakeEmptyIndex(0), true), new MultiReader(new IndexReader[] { IndexReader.Open(MakeEmptyIndex(edge < 0 ? 4 : 0), true), IndexReader.Open(MakeEmptyIndex(0), true), 0 == edge ? r : IndexReader.Open(MakeEmptyIndex(0), true) }), IndexReader.Open(MakeEmptyIndex(0 < edge ? 0 : 7), true), IndexReader.Open(MakeEmptyIndex(0), true), new MultiReader(new IndexReader[] { IndexReader.Open(MakeEmptyIndex(0 < edge ? 0 : 5), true), IndexReader.Open(MakeEmptyIndex(0), true), 0 < edge ? r : IndexReader.Open(MakeEmptyIndex(0), true) }) }; IndexSearcher out_Renamed = new IndexSearcher(new MultiReader(readers)); out_Renamed.Similarity = s.Similarity; return out_Renamed; } /// <summary> Given a Searcher, returns a new MultiSearcher wrapping the /// the original Searcher, /// as well as several "empty" IndexSearchers -- some of which will have /// deleted documents in them. This new MultiSearcher /// should behave exactly the same as the original Searcher. /// </summary> /// <param name="s">the Searcher to wrap /// </param> /// <param name="edge">if negative, s will be the first sub; if 0, s will be in hte middle, if positive s will be the last sub /// </param> public static MultiSearcher WrapSearcher(Searcher s, int edge) { // we can't put deleted docs before the nested reader, because // it will through off the docIds Searcher[] searchers = new Searcher[] { edge < 0 ? s : new IndexSearcher(MakeEmptyIndex(0), true), new MultiSearcher(new Searcher[] { new IndexSearcher(MakeEmptyIndex(edge < 0 ? 65 : 0), true), new IndexSearcher(MakeEmptyIndex(0), true), 0 == edge ? s : new IndexSearcher(MakeEmptyIndex(0), true) }), new IndexSearcher(MakeEmptyIndex(0 < edge ? 0 : 3), true), new IndexSearcher(MakeEmptyIndex(0), true), new MultiSearcher(new Searcher[] { new IndexSearcher(MakeEmptyIndex(0 < edge ? 0 : 5), true), new IndexSearcher(MakeEmptyIndex(0), true), 0 < edge ? s : new IndexSearcher(MakeEmptyIndex(0), true) }) }; MultiSearcher out_Renamed = new MultiSearcher(searchers); out_Renamed.Similarity = s.Similarity; return out_Renamed; } private static RAMDirectory MakeEmptyIndex(int numDeletedDocs) { RAMDirectory d = new RAMDirectory(); IndexWriter w = new IndexWriter(d, new WhitespaceAnalyzer(), true, MaxFieldLength.LIMITED); for (int i = 0; i < numDeletedDocs; i++) { w.AddDocument(new Document()); } w.Commit(); w.DeleteDocuments(new MatchAllDocsQuery()); w.Commit(); if (0 < numDeletedDocs) Assert.IsTrue(w.HasDeletions(), "writer has no deletions"); Assert.AreEqual(numDeletedDocs, w.MaxDoc(), "writer is missing some deleted docs"); Assert.AreEqual(0, w.NumDocs(), "writer has non-deleted docs"); w.Close(); IndexReader r = IndexReader.Open(d, true); Assert.AreEqual(numDeletedDocs, r.NumDeletedDocs, "reader has wrong number of deleted docs"); r.Close(); return d; } /// <summary>check that the query weight is serializable. </summary> /// <throws> IOException if serialization check fail. </throws> private static void CheckSerialization(Query q, Searcher s) { Weight w = q.Weight(s); try { System.IO.MemoryStream bos = new System.IO.MemoryStream(); System.IO.BinaryWriter oos = new System.IO.BinaryWriter(bos); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(oos.BaseStream, w); oos.Close(); System.IO.BinaryReader ois = new System.IO.BinaryReader(new System.IO.MemoryStream(bos.ToArray())); formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Deserialize(ois.BaseStream); ois.Close(); //skip equals() test for now - most weights don't override equals() and we won't add this just for the tests. //TestCase.Assert.AreEqual(w2,w,"writeObject(w) != w. ("+w+")"); } catch (System.Exception e) { System.IO.IOException e2 = new System.IO.IOException("Serialization failed for " + w, e); throw e2; } } /// <summary>alternate scorer skipTo(),skipTo(),next(),next(),skipTo(),skipTo(), etc /// and ensure a hitcollector receives same docs and scores /// </summary> public static void CheckSkipTo(Query q, IndexSearcher s) { //System.out.println("Checking "+q); if (q.Weight(s).GetScoresDocsOutOfOrder()) return ; // in this case order of skipTo() might differ from that of next(). int skip_op = 0; int next_op = 1; int[][] orders = new int[][]{new int[]{next_op}, new int[]{skip_op}, new int[]{skip_op, next_op}, new int[]{next_op, skip_op}, new int[]{skip_op, skip_op, next_op, next_op}, new int[]{next_op, next_op, skip_op, skip_op}, new int[]{skip_op, skip_op, skip_op, next_op, next_op}}; for (int k = 0; k < orders.Length; k++) { int[] order = orders[k]; // System.out.print("Order:");for (int i = 0; i < order.length; i++) // System.out.print(order[i]==skip_op ? " skip()":" next()"); // System.out.println(); int[] opidx = new int[]{0}; int[] lastDoc = new[] {-1}; // FUTURE: ensure scorer.doc()==-1 float maxDiff = 1e-5f; IndexReader[] lastReader = new IndexReader[] {null}; s.Search(q, new AnonymousClassCollector(order, opidx, skip_op, lastReader, maxDiff, q, s, lastDoc)); if (lastReader[0] != null) { // Confirm that skipping beyond the last doc, on the // previous reader, hits NO_MORE_DOCS IndexReader previousReader = lastReader[0]; Weight w = q.Weight(new IndexSearcher(previousReader)); Scorer scorer = w.Scorer(previousReader, true, false); if (scorer != null) { bool more = scorer.Advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS; Assert.IsFalse(more, "query's last doc was " + lastDoc[0] + " but skipTo(" + (lastDoc[0] + 1) + ") got to " + scorer.DocID()); } } } } // check that first skip on just created scorers always goes to the right doc private static void CheckFirstSkipTo(Query q, IndexSearcher s) { //System.out.println("checkFirstSkipTo: "+q); float maxDiff = 1e-4f; //{{Lucene.Net-2.9.1}}Intentional diversion from Java Lucene int[] lastDoc = new int[]{- 1}; IndexReader[] lastReader = {null}; s.Search(q, new AnonymousClassCollector1(lastDoc, q, s, maxDiff, lastReader)); if(lastReader[0] != null) { // confirm that skipping beyond the last doc, on the // previous reader, hits NO_MORE_DOCS IndexReader previousReader = lastReader[0]; Weight w = q.Weight(new IndexSearcher(previousReader)); Scorer scorer = w.Scorer(previousReader, true, false); if (scorer != null) { bool more = scorer.Advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS; Assert.IsFalse(more, "query's last doc was " + lastDoc[0] + " but skipTo(" + (lastDoc[0] + 1) + ") got to " + scorer.DocID()); } } } } }
using Bridge.Contract; using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.TypeSystem; using Mono.Cecil; using System; using System.Collections.Generic; using System.Text; namespace Bridge.Translator { public partial class Emitter : Visitor { public string Tag { get; set; } public EmitterCache Cache { get; private set; } public IValidator Validator { get; private set; } public List<ITypeInfo> Types { get; set; } public bool IsAssignment { get; set; } public AssignmentOperatorType AssignmentType { get; set; } public UnaryOperatorType UnaryOperatorType { get; set; } public bool IsUnaryAccessor { get; set; } public Dictionary<string, AstType> Locals { get; set; } public Dictionary<IVariable, string> LocalsMap { get; set; } public Dictionary<string, string> LocalsNamesMap { get; set; } public Stack<Dictionary<string, AstType>> LocalsStack { get; set; } public int Level { get; set; } public int initialLevel; public int InitialLevel { get { return initialLevel; } set { this.initialLevel = value; this.ResetLevel(); } } public int ResetLevel(int? level = null) { if (!level.HasValue) { level = InitialLevel; } if (level < InitialLevel && !this.InitPosition.HasValue ) { level = InitialLevel; } if (level < 0) { level = 0; } this.Level = level.Value; return this.Level; } public InitPosition? InitPosition { get; set; } public bool IsNewLine { get; set; } public bool EnableSemicolon { get; set; } public int IteratorCount { get; set; } public int ThisRefCounter { get; set; } public IDictionary<string, TypeDefinition> TypeDefinitions { get; protected set; } public ITypeInfo TypeInfo { get; set; } public StringBuilder Output { get; set; } public Stack<IWriter> Writers { get; set; } public bool Comma { get; set; } private HashSet<string> namespaces; protected virtual HashSet<string> Namespaces { get { if (this.namespaces == null) { this.namespaces = this.CreateNamespaces(); } return this.namespaces; } } public virtual IEnumerable<AssemblyDefinition> References { get; set; } public virtual IList<string> SourceFiles { get; set; } private List<IAssemblyReference> list; protected virtual IEnumerable<IAssemblyReference> AssemblyReferences { get { if (this.list != null) { return this.list; } this.list = Emitter.ToAssemblyReferences(this.References, this.Log); return this.list; } } internal static List<IAssemblyReference> ToAssemblyReferences(IEnumerable<AssemblyDefinition> references, ILogger logger) { logger.Info("Assembly definition to references..."); var list = new List<IAssemblyReference>(); if (references == null) { return list; } foreach (var reference in references) { logger.Trace("\tLoading AssemblyDefinition " + (reference != null && reference.Name != null && reference.Name.Name != null ? reference.Name.Name : "") + " ..."); var loader = new CecilLoader(); loader.IncludeInternalMembers = true; list.Add(loader.LoadAssembly(reference)); logger.Trace("\tLoading AssemblyDefinition done"); } logger.Info("Assembly definition to references done"); return list; } public IMemberResolver Resolver { get; set; } public IAssemblyInfo AssemblyInfo { get; set; } public Dictionary<string, ITypeInfo> TypeInfoDefinitions { get; set; } public List<IPluginDependency> CurrentDependencies { get; set; } public IEmitterOutputs Outputs { get; set; } public IEmitterOutput EmitterOutput { get; set; } public bool SkipSemiColon { get; set; } public IEnumerable<MethodDefinition> MethodsGroup { get; set; } public Dictionary<int, StringBuilder> MethodsGroupBuilder { get; set; } public bool IsAsync { get; set; } public bool IsYield { get; set; } public List<string> AsyncVariables { get; set; } public IAsyncBlock AsyncBlock { get; set; } public bool ReplaceAwaiterByVar { get; set; } public bool AsyncExpressionHandling { get; set; } public AstNode IgnoreBlock { get; set; } public AstNode NoBraceBlock { get; set; } public Action BeforeBlock { get; set; } public IWriterInfo LastSavedWriter { get; set; } public List<IJumpInfo> JumpStatements { get; set; } public SwitchStatement AsyncSwitch { get; set; } public IPlugins Plugins { get; set; } public Dictionary<string, bool> TempVariables { get; set; } public Dictionary<string, string> NamedTempVariables { get; set; } public Dictionary<string, bool> ParentTempVariables { get; set; } public BridgeTypes BridgeTypes { get; set; } public ITranslator Translator { get; set; } public IJsDoc JsDoc { get; set; } public IType ReturnType { get; set; } public bool ReplaceJump { get; set; } public string CatchBlockVariable { get; set; } public bool StaticBlock { get; set; } public Dictionary<string, string> NamedFunctions { get; set; } public Dictionary<IType, Dictionary<string, string>> NamedBoxedFunctions { get; set; } public bool IsJavaScriptOverflowMode { get { return this.AssemblyInfo.OverflowMode.HasValue && this.AssemblyInfo.OverflowMode == OverflowMode.Javascript; } } public bool IsRefArg { get; set; } public Dictionary<AnonymousType, IAnonymousTypeConfig> AnonymousTypes { get; set; } public List<string> AutoStartupMethods { get; set; } public bool IsAnonymousReflectable { get; set; } public string MetaDataOutputName { get; set; } public IType[] ReflectableTypes { get; set; } public Dictionary<string, int> NamespacesCache { get; set; } private bool AssemblyJsDocWritten { get; set; } public bool ForbidLifting { get; set; } public bool DisableDependencyTracking { get; set; } public Dictionary<IAssembly, NameRule[]> AssemblyNameRuleCache { get; } public Dictionary<ITypeDefinition, NameRule[]> ClassNameRuleCache { get; } public Dictionary<IAssembly, CompilerRule[]> AssemblyCompilerRuleCache { get; } public Dictionary<ITypeDefinition, CompilerRule[]> ClassCompilerRuleCache { get; } public string SourceFileName { get; set; } public int SourceFileNameIndex { get; set; } public string LastSequencePoint { get; set; } public bool InConstructor { get; set; } public CompilerRule Rules { get; set; } public bool HasModules { get; set; } public string TemplateModifier { get; set; } public int WrapRestCounter { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; #if BIT64 using nuint = System.UInt64; #else using nuint = System.UInt32; #endif namespace System { /// <summary> /// Extension methods and non-generic helpers for Span, ReadOnlySpan, Memory, and ReadOnlyMemory. /// </summary> public static class Span { public static bool Contains(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { return (IndexOf(span, value, comparisonType) >= 0); } public static bool Equals(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { StringSpanHelpers.CheckStringComparison(comparisonType); switch (comparisonType) { case StringComparison.CurrentCulture: return (CultureInfo.CurrentCulture.CompareInfo.Compare(span, value, CompareOptions.None) == 0); case StringComparison.CurrentCultureIgnoreCase: return (CultureInfo.CurrentCulture.CompareInfo.Compare(span, value, CompareOptions.IgnoreCase) == 0); case StringComparison.InvariantCulture: return (CompareInfo.Invariant.Compare(span, value, CompareOptions.None) == 0); case StringComparison.InvariantCultureIgnoreCase: return (CompareInfo.Invariant.Compare(span, value, CompareOptions.IgnoreCase) == 0); case StringComparison.Ordinal: if (span.Length != value.Length) return false; if (value.Length == 0) // span.Length == value.Length == 0 return true; return OrdinalHelper(span, value, value.Length); case StringComparison.OrdinalIgnoreCase: if (span.Length != value.Length) return false; if (value.Length == 0) // span.Length == value.Length == 0 return true; return (CompareInfo.CompareOrdinalIgnoreCase(span, value) == 0); } Debug.Fail("StringComparison outside range"); return false; } public static int CompareTo(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { StringSpanHelpers.CheckStringComparison(comparisonType); switch (comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.Compare(span, value, CompareOptions.None); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.Compare(span, value, CompareOptions.IgnoreCase); case StringComparison.InvariantCulture: return CompareInfo.Invariant.Compare(span, value, CompareOptions.None); case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.Compare(span, value, CompareOptions.IgnoreCase); case StringComparison.Ordinal: if (span.Length == 0 || value.Length == 0) return span.Length - value.Length; return string.CompareOrdinal(span, value); case StringComparison.OrdinalIgnoreCase: return CompareInfo.CompareOrdinalIgnoreCase(span, value); } Debug.Fail("StringComparison outside range"); return 0; } public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { StringSpanHelpers.CheckStringComparison(comparisonType); if (value.Length == 0) { return 0; } if (span.Length == 0) { return -1; } switch (comparisonType) { case StringComparison.CurrentCulture: return IndexOfCultureHelper(span, value, CultureInfo.CurrentCulture.CompareInfo); case StringComparison.CurrentCultureIgnoreCase: return IndexOfCultureIgnoreCaseHelper(span, value, CultureInfo.CurrentCulture.CompareInfo); case StringComparison.InvariantCulture: return IndexOfCultureHelper(span, value, CompareInfo.Invariant); case StringComparison.InvariantCultureIgnoreCase: return IndexOfCultureIgnoreCaseHelper(span, value, CompareInfo.Invariant); case StringComparison.Ordinal: return IndexOfOrdinalHelper(span, value, ignoreCase: false); case StringComparison.OrdinalIgnoreCase: return IndexOfOrdinalHelper(span, value, ignoreCase: true); } Debug.Fail("StringComparison outside range"); return -1; } internal static int IndexOfCultureHelper(ReadOnlySpan<char> span, ReadOnlySpan<char> value, CompareInfo compareInfo) { Debug.Assert(span.Length != 0); Debug.Assert(value.Length != 0); if (GlobalizationMode.Invariant) { return CompareInfo.InvariantIndexOf(span, value, ignoreCase: false); } return compareInfo.IndexOf(span, value, CompareOptions.None); } internal static int IndexOfCultureIgnoreCaseHelper(ReadOnlySpan<char> span, ReadOnlySpan<char> value, CompareInfo compareInfo) { Debug.Assert(span.Length != 0); Debug.Assert(value.Length != 0); if (GlobalizationMode.Invariant) { return CompareInfo.InvariantIndexOf(span, value, ignoreCase: true); } return compareInfo.IndexOf(span, value, CompareOptions.IgnoreCase); } internal static int IndexOfOrdinalHelper(ReadOnlySpan<char> span, ReadOnlySpan<char> value, bool ignoreCase) { Debug.Assert(span.Length != 0); Debug.Assert(value.Length != 0); if (GlobalizationMode.Invariant) { return CompareInfo.InvariantIndexOf(span, value, ignoreCase); } return CompareInfo.Invariant.IndexOfOrdinal(span, value, ignoreCase); } /// <summary> /// Copies the characters from the source span into the destination, converting each character to lowercase. /// </summary> public static int ToLower(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture) { if (culture == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.culture); // Assuming that changing case does not affect length if (destination.Length < source.Length) return -1; if (GlobalizationMode.Invariant) culture.TextInfo.ToLowerAsciiInvariant(source, destination); else culture.TextInfo.ChangeCase(source, destination, toUpper: false); return source.Length; } /// <summary> /// Copies the characters from the source span into the destination, converting each character to lowercase /// using the casing rules of the invariant culture. /// </summary> public static int ToLowerInvariant(this ReadOnlySpan<char> source, Span<char> destination) { // Assuming that changing case does not affect length if (destination.Length < source.Length) return -1; if (GlobalizationMode.Invariant) CultureInfo.InvariantCulture.TextInfo.ToLowerAsciiInvariant(source, destination); else CultureInfo.InvariantCulture.TextInfo.ChangeCase(source, destination, toUpper: false); return source.Length; } /// <summary> /// Copies the characters from the source span into the destination, converting each character to uppercase. /// </summary> public static int ToUpper(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture) { if (culture == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.culture); // Assuming that changing case does not affect length if (destination.Length < source.Length) return -1; if (GlobalizationMode.Invariant) culture.TextInfo.ToUpperAsciiInvariant(source, destination); else culture.TextInfo.ChangeCase(source, destination, toUpper: true); return source.Length; } /// <summary> /// Copies the characters from the source span into the destination, converting each character to uppercase /// using the casing rules of the invariant culture. /// </summary> public static int ToUpperInvariant(this ReadOnlySpan<char> source, Span<char> destination) { // Assuming that changing case does not affect length if (destination.Length < source.Length) return -1; if (GlobalizationMode.Invariant) CultureInfo.InvariantCulture.TextInfo.ToUpperAsciiInvariant(source, destination); else CultureInfo.InvariantCulture.TextInfo.ChangeCase(source, destination, toUpper: true); return source.Length; } /// <summary> /// Determines whether the beginning of the span matches the specified value when compared using the specified comparison option. /// </summary> public static bool StartsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { if (value.Length == 0) { StringSpanHelpers.CheckStringComparison(comparisonType); return true; } switch (comparisonType) { case StringComparison.CurrentCulture: return StartsWithCultureHelper(span, value, CultureInfo.CurrentCulture.CompareInfo); case StringComparison.CurrentCultureIgnoreCase: return StartsWithCultureIgnoreCaseHelper(span, value, CultureInfo.CurrentCulture.CompareInfo); case StringComparison.InvariantCulture: return StartsWithCultureHelper(span, value, CompareInfo.Invariant); case StringComparison.InvariantCultureIgnoreCase: return StartsWithCultureIgnoreCaseHelper(span, value, CompareInfo.Invariant); case StringComparison.Ordinal: return StartsWithOrdinalHelper(span, value); case StringComparison.OrdinalIgnoreCase: return StartsWithOrdinalIgnoreCaseHelper(span, value); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } internal static bool StartsWithCultureHelper(ReadOnlySpan<char> span, ReadOnlySpan<char> value, CompareInfo compareInfo) { Debug.Assert(value.Length != 0); if (GlobalizationMode.Invariant) { return StartsWithOrdinalHelper(span, value); } if (span.Length == 0) { return false; } return compareInfo.IsPrefix(span, value, CompareOptions.None); } internal static bool StartsWithCultureIgnoreCaseHelper(ReadOnlySpan<char> span, ReadOnlySpan<char> value, CompareInfo compareInfo) { Debug.Assert(value.Length != 0); if (GlobalizationMode.Invariant) { return StartsWithOrdinalIgnoreCaseHelper(span, value); } if (span.Length == 0) { return false; } return compareInfo.IsPrefix(span, value, CompareOptions.IgnoreCase); } internal static bool StartsWithOrdinalIgnoreCaseHelper(ReadOnlySpan<char> span, ReadOnlySpan<char> value) { Debug.Assert(value.Length != 0); if (span.Length < value.Length) { return false; } return CompareInfo.CompareOrdinalIgnoreCase(span.Slice(0, value.Length), value) == 0; } internal static bool StartsWithOrdinalHelper(ReadOnlySpan<char> span, ReadOnlySpan<char> value) { Debug.Assert(value.Length != 0); if (span.Length < value.Length) { return false; } return OrdinalHelper(span, value, value.Length); } internal static unsafe bool OrdinalHelper(ReadOnlySpan<char> span, ReadOnlySpan<char> value, int length) { Debug.Assert(length != 0); Debug.Assert(span.Length >= length); fixed (char* ap = &MemoryMarshal.GetReference(span)) fixed (char* bp = &MemoryMarshal.GetReference(value)) { char* a = ap; char* b = bp; #if BIT64 // Single int read aligns pointers for the following long reads if (length >= 2) { if (*(int*)a != *(int*)b) return false; length -= 2; a += 2; b += 2; } while (length >= 12) { if (*(long*)a != *(long*)b) return false; if (*(long*)(a + 4) != *(long*)(b + 4)) return false; if (*(long*)(a + 8) != *(long*)(b + 8)) return false; length -= 12; a += 12; b += 12; } #else while (length >= 10) { if (*(int*)a != *(int*)b) return false; if (*(int*)(a+2) != *(int*)(b+2)) return false; if (*(int*)(a+4) != *(int*)(b+4)) return false; if (*(int*)(a+6) != *(int*)(b+6)) return false; if (*(int*)(a+8) != *(int*)(b+8)) return false; length -= 10; a += 10; b += 10; } #endif while (length >= 2) { if (*(int*)a != *(int*)b) return false; length -= 2; a += 2; b += 2; } // PERF: This depends on the fact that the String objects are always zero terminated // and that the terminating zero is not included in the length. For even string sizes // this compare can include the zero terminator. Bitwise OR avoids a branch. return length == 0 | *a == *b; } } /// <summary> /// Determines whether the end of the span matches the specified value when compared using the specified comparison option. /// </summary> public static bool EndsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { if (value.Length == 0) { StringSpanHelpers.CheckStringComparison(comparisonType); return true; } switch (comparisonType) { case StringComparison.CurrentCulture: return EndsWithCultureHelper(span, value, CultureInfo.CurrentCulture.CompareInfo); case StringComparison.CurrentCultureIgnoreCase: return EndsWithCultureIgnoreCaseHelper(span, value, CultureInfo.CurrentCulture.CompareInfo); case StringComparison.InvariantCulture: return EndsWithCultureHelper(span, value, CompareInfo.Invariant); case StringComparison.InvariantCultureIgnoreCase: return EndsWithCultureIgnoreCaseHelper(span, value, CompareInfo.Invariant); case StringComparison.Ordinal: return EndsWithOrdinalHelper(span, value); case StringComparison.OrdinalIgnoreCase: return EndsWithOrdinalIgnoreCaseHelper(span, value); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } internal static bool EndsWithCultureHelper(ReadOnlySpan<char> span, ReadOnlySpan<char> value, CompareInfo compareInfo) { Debug.Assert(value.Length != 0); if (GlobalizationMode.Invariant) { return EndsWithOrdinalHelper(span, value); } if (span.Length == 0) { return false; } return compareInfo.IsSuffix(span, value, CompareOptions.None); } internal static bool EndsWithCultureIgnoreCaseHelper(ReadOnlySpan<char> span, ReadOnlySpan<char> value, CompareInfo compareInfo) { Debug.Assert(value.Length != 0); if (GlobalizationMode.Invariant) { return EndsWithOrdinalIgnoreCaseHelper(span, value); } if (span.Length == 0) { return false; } return compareInfo.IsSuffix(span, value, CompareOptions.IgnoreCase); } internal static bool EndsWithOrdinalIgnoreCaseHelper(ReadOnlySpan<char> span, ReadOnlySpan<char> value) { Debug.Assert(value.Length != 0); if (span.Length < value.Length) { return false; } return (CompareInfo.CompareOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value) == 0); } internal static bool EndsWithOrdinalHelper(ReadOnlySpan<char> span, ReadOnlySpan<char> value) { Debug.Assert(value.Length != 0); if (span.Length < value.Length) { return false; } return OrdinalHelper(span.Slice(span.Length - value.Length), value, value.Length); } /// <summary> /// Helper method for MemoryExtensions.AsSpan(T[] array, int start). /// </summary> public static Span<T> AsSpan<T>(T[] array, int start) { if (array == null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); return default; } if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new Span<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start), array.Length - start); } /// <summary> /// Helper method for MemoryExtensions.AsMemory(T[] array, int start). /// </summary> public static Memory<T> AsMemory<T>(T[] array, int start) => new Memory<T>(array, start); /// <summary>Creates a new <see cref="ReadOnlyMemory{char}"/> over the portion of the target string.</summary> /// <param name="text">The target string.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> public static ReadOnlyMemory<char> AsReadOnlyMemory(this string text) { if (text == null) return default; return new ReadOnlyMemory<char>(text, 0, text.Length); } /// <summary>Creates a new <see cref="ReadOnlyMemory{char}"/> over the portion of the target string.</summary> /// <param name="text">The target string.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;text.Length). /// </exception> public static ReadOnlyMemory<char> AsReadOnlyMemory(this string text, int start) { if (text == null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return default; } if ((uint)start > (uint)text.Length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return new ReadOnlyMemory<char>(text, start, text.Length - start); } /// <summary>Creates a new <see cref="ReadOnlyMemory{char}"/> over the portion of the target string.</summary> /// <param name="text">The target string.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range. /// </exception> public static ReadOnlyMemory<char> AsReadOnlyMemory(this string text, int start, int length) { if (text == null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return default; } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return new ReadOnlyMemory<char>(text, start, length); } /// <summary>Attempts to get the underlying <see cref="string"/> from a <see cref="ReadOnlyMemory{T}"/>.</summary> /// <param name="readOnlyMemory">The memory that may be wrapping a <see cref="string"/> object.</param> /// <param name="text">The string.</param> /// <param name="start">The starting location in <paramref name="text"/>.</param> /// <param name="length">The number of items in <paramref name="text"/>.</param> /// <returns></returns> public static bool TryGetString(this ReadOnlyMemory<char> readOnlyMemory, out string text, out int start, out int length) { if (readOnlyMemory.GetObjectStartLength(out int offset, out int count) is string s) { text = s; start = offset; length = count; return true; } else { text = null; start = 0; length = 0; return false; } } /// <summary> /// Casts a Span of one primitive type <typeparamref name="T"/> to Span of bytes. /// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// </summary> /// <param name="source">The source slice, of type <typeparamref name="T"/>.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> contains pointers. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<byte> AsBytes<T>(this Span<T> source) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); return new Span<byte>( ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(source)), checked(source.Length * Unsafe.SizeOf<T>())); } /// <summary> /// Casts a ReadOnlySpan of one primitive type <typeparamref name="T"/> to ReadOnlySpan of bytes. /// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// </summary> /// <param name="source">The source slice, of type <typeparamref name="T"/>.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> contains pointers. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<byte> AsBytes<T>(this ReadOnlySpan<T> source) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); return new ReadOnlySpan<byte>( ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(source)), checked(source.Length * Unsafe.SizeOf<T>())); } /// <summary> /// Creates a new readonly span over the portion of the target string. /// </summary> /// <param name="text">The target string.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> /// reference (Nothing in Visual Basic).</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text) { if (text == null) return default; return new ReadOnlySpan<char>(ref text.GetRawStringData(), text.Length); } /// <summary> /// Creates a new readonly span over the portion of the target string. /// </summary> /// <param name="text">The target string.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;text.Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text, int start) { if (text == null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return default; } if ((uint)start > (uint)text.Length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetRawStringData(), start), text.Length - start); } /// <summary> /// Creates a new readonly span over the portion of the target string. /// </summary> /// <param name="text">The target string.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text, int start, int length) { if (text == null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return default; } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetRawStringData(), start), length); } // TODO: Delete once the AsReadOnlySpan -> AsSpan rename propages through the system public static ReadOnlySpan<char> AsReadOnlySpan(this string text) => AsSpan(text); public static ReadOnlySpan<char> AsReadOnlySpan(this string text, int start) => AsSpan(text, start); public static ReadOnlySpan<char> AsReadOnlySpan(this string text, int start, int length) => AsSpan(text, start, length); internal static unsafe void ClearWithoutReferences(ref byte b, nuint byteLength) { if (byteLength == 0) return; #if CORECLR && (AMD64 || ARM64) if (byteLength > 4096) goto PInvoke; Unsafe.InitBlockUnaligned(ref b, 0, (uint)byteLength); return; #else // TODO: Optimize other platforms to be on par with AMD64 CoreCLR // Note: It's important that this switch handles lengths at least up to 22. // See notes below near the main loop for why. // The switch will be very fast since it can be implemented using a jump // table in assembly. See http://stackoverflow.com/a/449297/4077294 for more info. switch (byteLength) { case 1: b = 0; return; case 2: Unsafe.As<byte, short>(ref b) = 0; return; case 3: Unsafe.As<byte, short>(ref b) = 0; Unsafe.Add<byte>(ref b, 2) = 0; return; case 4: Unsafe.As<byte, int>(ref b) = 0; return; case 5: Unsafe.As<byte, int>(ref b) = 0; Unsafe.Add<byte>(ref b, 4) = 0; return; case 6: Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 4)) = 0; return; case 7: Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.Add<byte>(ref b, 6) = 0; return; case 8: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif return; case 9: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.Add<byte>(ref b, 8) = 0; return; case 10: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 8)) = 0; return; case 11: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.Add<byte>(ref b, 10) = 0; return; case 12: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; return; case 13: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.Add<byte>(ref b, 12) = 0; return; case 14: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 12)) = 0; return; case 15: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 12)) = 0; Unsafe.Add<byte>(ref b, 14) = 0; return; case 16: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif return; case 17: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.Add<byte>(ref b, 16) = 0; return; case 18: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 16)) = 0; return; case 19: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 16)) = 0; Unsafe.Add<byte>(ref b, 18) = 0; return; case 20: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0; return; case 21: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0; Unsafe.Add<byte>(ref b, 20) = 0; return; case 22: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 20)) = 0; return; } // P/Invoke into the native version for large lengths if (byteLength >= 512) goto PInvoke; nuint i = 0; // byte offset at which we're copying if ((Unsafe.As<byte, int>(ref b) & 3) != 0) { if ((Unsafe.As<byte, int>(ref b) & 1) != 0) { Unsafe.AddByteOffset<byte>(ref b, i) = 0; i += 1; if ((Unsafe.As<byte, int>(ref b) & 2) != 0) goto IntAligned; } Unsafe.As<byte, short>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 2; } IntAligned: // On 64-bit IntPtr.Size == 8, so we want to advance to the next 8-aligned address. If // (int)b % 8 is 0, 5, 6, or 7, we will already have advanced by 0, 3, 2, or 1 // bytes to the next aligned address (respectively), so do nothing. On the other hand, // if it is 1, 2, 3, or 4 we will want to copy-and-advance another 4 bytes until // we're aligned. // The thing 1, 2, 3, and 4 have in common that the others don't is that if you // subtract one from them, their 3rd lsb will not be set. Hence, the below check. if (((Unsafe.As<byte, int>(ref b) - 1) & 4) == 0) { Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 4; } nuint end = byteLength - 16; byteLength -= i; // lower 4 bits of byteLength represent how many bytes are left *after* the unrolled loop // We know due to the above switch-case that this loop will always run 1 iteration; max // bytes we clear before checking is 23 (7 to align the pointers, 16 for 1 iteration) so // the switch handles lengths 0-22. Debug.Assert(end >= 7 && i <= end); // This is separated out into a different variable, so the i + 16 addition can be // performed at the start of the pipeline and the loop condition does not have // a dependency on the writes. nuint counter; do { counter = i + 16; // This loop looks very costly since there appear to be a bunch of temporary values // being created with the adds, but the jit (for x86 anyways) will convert each of // these to use memory addressing operands. // So the only cost is a bit of code size, which is made up for by the fact that // we save on writes to b. #if BIT64 Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i + 8)) = 0; #else Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 12)) = 0; #endif i = counter; // See notes above for why this wasn't used instead // i += 16; } while (counter <= end); if ((byteLength & 8) != 0) { #if BIT64 Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; #else Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 4)) = 0; #endif i += 8; } if ((byteLength & 4) != 0) { Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 4; } if ((byteLength & 2) != 0) { Unsafe.As<byte, short>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 2; } if ((byteLength & 1) != 0) { Unsafe.AddByteOffset<byte>(ref b, i) = 0; // We're not using i after this, so not needed // i += 1; } return; #endif PInvoke: RuntimeImports.RhZeroMemory(ref b, byteLength); } internal static unsafe void ClearWithReferences(ref IntPtr ip, nuint pointerSizeLength) { if (pointerSizeLength == 0) return; // TODO: Perhaps do switch casing to improve small size perf nuint i = 0; nuint n = 0; while ((n = i + 8) <= (pointerSizeLength)) { Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 2) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 3) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 4) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 5) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 6) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 7) * (nuint)sizeof(IntPtr)) = default(IntPtr); i = n; } if ((n = i + 4) <= (pointerSizeLength)) { Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 2) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 3) * (nuint)sizeof(IntPtr)) = default(IntPtr); i = n; } if ((n = i + 2) <= (pointerSizeLength)) { Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr); i = n; } if ((i + 1) <= (pointerSizeLength)) { Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); } } } }
using System; using Lucene.Net.Attributes; using Lucene.Net.Support; using NUnit.Framework; using System.Collections; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * 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. */ [TestFixture] public class TestLongBitSet : LuceneTestCase { internal virtual void DoGet(BitArray a, Int64BitSet b) { long max = b.Length; for (int i = 0; i < max; i++) { if (a.SafeGet(i) != b.Get(i)) { Assert.Fail("mismatch: BitSet=[" + i + "]=" + a.SafeGet(i)); } } } internal virtual void DoNextSetBit(BitArray a, Int64BitSet b) { int aa = -1; long bb = -1; do { aa = a.NextSetBit(aa + 1); bb = bb < b.Length - 1 ? b.NextSetBit(bb + 1) : -1; Assert.AreEqual(aa, bb); } while (aa >= 0); } internal virtual void DoPrevSetBit(BitArray a, Int64BitSet b) { int aa = a.Length + Random.Next(100); long bb = aa; do { //aa = a.PrevSetBit(aa-1); aa--; while ((aa >= 0) && (!a.SafeGet(aa))) { aa--; } if (b.Length == 0) { bb = -1; } else if (bb > b.Length - 1) { bb = b.PrevSetBit(b.Length - 1); } else if (bb < 1) { bb = -1; } else { bb = bb >= 1 ? b.PrevSetBit(bb - 1) : -1; } Assert.AreEqual(aa, bb); } while (aa >= 0); } internal virtual void DoRandomSets(int maxSize, int iter, int mode) { BitArray a0 = null; Int64BitSet b0 = null; for (int i = 0; i < iter; i++) { int sz = TestUtil.NextInt32(Random, 2, maxSize); BitArray a = new BitArray(sz); Int64BitSet b = new Int64BitSet(sz); // test the various ways of setting bits if (sz > 0) { int nOper = Random.Next(sz); for (int j = 0; j < nOper; j++) { int idx; idx = Random.Next(sz); a.SafeSet(idx, true); b.Set(idx); idx = Random.Next(sz); a.SafeSet(idx, false); b.Clear(idx); idx = Random.Next(sz); a.SafeSet(idx, !a.SafeGet(idx)); b.Flip(idx, idx + 1); idx = Random.Next(sz); a.SafeSet(idx, !a.SafeGet(idx)); b.Flip(idx, idx + 1); bool val2 = b.Get(idx); bool val = b.GetAndSet(idx); Assert.IsTrue(val2 == val); Assert.IsTrue(b.Get(idx)); if (!val) { b.Clear(idx); } Assert.IsTrue(b.Get(idx) == val); } } // test that the various ways of accessing the bits are equivalent DoGet(a, b); // test ranges, including possible extension int fromIndex, toIndex; fromIndex = Random.Next(sz / 2); toIndex = fromIndex + Random.Next(sz - fromIndex); BitArray aa = new BitArray(a); aa.Flip(fromIndex, toIndex); Int64BitSet bb = b.Clone(); bb.Flip(fromIndex, toIndex); fromIndex = Random.Next(sz / 2); toIndex = fromIndex + Random.Next(sz - fromIndex); aa = new BitArray(a); aa.Clear(fromIndex, toIndex); bb = b.Clone(); bb.Clear(fromIndex, toIndex); DoNextSetBit(aa, bb); // a problem here is from clear() or nextSetBit DoPrevSetBit(aa, bb); fromIndex = Random.Next(sz / 2); toIndex = fromIndex + Random.Next(sz - fromIndex); aa = new BitArray(a); aa.Set(fromIndex, toIndex); bb = b.Clone(); bb.Set(fromIndex, toIndex); DoNextSetBit(aa, bb); // a problem here is from set() or nextSetBit DoPrevSetBit(aa, bb); if (b0 != null && b0.Length <= b.Length) { Assert.AreEqual(a.Cardinality(), b.Cardinality()); BitArray a_and = new BitArray(a); a_and = a_and.And_UnequalLengths(a0); BitArray a_or = new BitArray(a); a_or = a_or.Or_UnequalLengths(a0); BitArray a_xor = new BitArray(a); a_xor = a_xor.Xor_UnequalLengths(a0); BitArray a_andn = new BitArray(a); a_andn.AndNot(a0); Int64BitSet b_and = b.Clone(); Assert.AreEqual(b, b_and); b_and.And(b0); Int64BitSet b_or = b.Clone(); b_or.Or(b0); Int64BitSet b_xor = b.Clone(); b_xor.Xor(b0); Int64BitSet b_andn = b.Clone(); b_andn.AndNot(b0); Assert.AreEqual(a0.Cardinality(), b0.Cardinality()); Assert.AreEqual(a_or.Cardinality(), b_or.Cardinality()); Assert.AreEqual(a_and.Cardinality(), b_and.Cardinality()); Assert.AreEqual(a_or.Cardinality(), b_or.Cardinality()); Assert.AreEqual(a_xor.Cardinality(), b_xor.Cardinality()); Assert.AreEqual(a_andn.Cardinality(), b_andn.Cardinality()); } a0 = a; b0 = b; } } // large enough to flush obvious bugs, small enough to run in <.5 sec as part of a // larger testsuite. [Test] public virtual void TestSmall() { DoRandomSets(AtLeast(1200), AtLeast(1000), 1); DoRandomSets(AtLeast(1200), AtLeast(1000), 2); } [Test, LuceneNetSpecific] public void TestClearSmall() { Int64BitSet a = new Int64BitSet(30); // 0110010111001000101101001001110...0 int[] onesA = { 1, 2, 5, 7, 8, 9, 12, 16, 18, 19, 21, 24, 27, 28, 29 }; for (int i = 0; i < onesA.size(); i++) { a.Set(onesA[i]); } Int64BitSet b = new Int64BitSet(30); // 0110000001001000101101001001110...0 int[] onesB = { 1, 2, 9, 12, 16, 18, 19, 21, 24, 27, 28, 29 }; for (int i = 0; i < onesB.size(); i++) { b.Set(onesB[i]); } a.Clear(5, 9); Assert.True(a.Equals(b)); a.Clear(9, 10); Assert.False(a.Equals(b)); a.Set(9); Assert.True(a.Equals(b)); } [Test, LuceneNetSpecific] public void TestClearLarge() { int iters = AtLeast(1000); for (int it = 0; it < iters; it++) { Random random = new Random(); int sz = AtLeast(1200); Int64BitSet a = new Int64BitSet(sz); Int64BitSet b = new Int64BitSet(sz); int from = random.Next(sz - 1); int to = random.Next(from, sz); for (int i = 0; i < sz / 2; i++) { int index = random.Next(sz - 1); a.Set(index); if (index < from || index >= to) { b.Set(index); } } a.Clear(from, to); Assert.True(a.Equals(b)); } } // uncomment to run a bigger test (~2 minutes). /* public void testBig() { doRandomSets(2000,200000, 1); doRandomSets(2000,200000, 2); } */ [Test] public virtual void TestEquals() { // this test can't handle numBits==0: int numBits = Random.Next(2000) + 1; Int64BitSet b1 = new Int64BitSet(numBits); Int64BitSet b2 = new Int64BitSet(numBits); Assert.IsTrue(b1.Equals(b2)); Assert.IsTrue(b2.Equals(b1)); for (int iter = 0; iter < 10 * RandomMultiplier; iter++) { int idx = Random.Next(numBits); if (!b1.Get(idx)) { b1.Set(idx); Assert.IsFalse(b1.Equals(b2)); Assert.IsFalse(b2.Equals(b1)); b2.Set(idx); Assert.IsTrue(b1.Equals(b2)); Assert.IsTrue(b2.Equals(b1)); } } // try different type of object Assert.IsFalse(b1.Equals(new object())); } [Test] public virtual void TestHashCodeEquals() { // this test can't handle numBits==0: int numBits = Random.Next(2000) + 1; Int64BitSet b1 = new Int64BitSet(numBits); Int64BitSet b2 = new Int64BitSet(numBits); Assert.IsTrue(b1.Equals(b2)); Assert.IsTrue(b2.Equals(b1)); for (int iter = 0; iter < 10 * RandomMultiplier; iter++) { int idx = Random.Next(numBits); if (!b1.Get(idx)) { b1.Set(idx); Assert.IsFalse(b1.Equals(b2)); Assert.IsFalse(b1.GetHashCode() == b2.GetHashCode()); b2.Set(idx); Assert.AreEqual(b1, b2); Assert.AreEqual(b1.GetHashCode(), b2.GetHashCode()); } } } [Test] public virtual void TestSmallBitSets() { // Make sure size 0-10 bit sets are OK: for (int numBits = 0; numBits < 10; numBits++) { Int64BitSet b1 = new Int64BitSet(numBits); Int64BitSet b2 = new Int64BitSet(numBits); Assert.IsTrue(b1.Equals(b2)); Assert.AreEqual(b1.GetHashCode(), b2.GetHashCode()); Assert.AreEqual(0, b1.Cardinality()); if (numBits > 0) { b1.Set(0, numBits); Assert.AreEqual(numBits, b1.Cardinality()); b1.Flip(0, numBits); Assert.AreEqual(0, b1.Cardinality()); } } } private Int64BitSet MakeLongFixedBitSet(int[] a, int numBits) { Int64BitSet bs; if (Random.NextBoolean()) { int bits2words = Int64BitSet.Bits2words(numBits); long[] words = new long[bits2words + Random.Next(100)]; for (int i = bits2words; i < words.Length; i++) { words[i] = Random.NextInt64(); } bs = new Int64BitSet(words, numBits); } else { bs = new Int64BitSet(numBits); } foreach (int e in a) { bs.Set(e); } return bs; } private BitArray MakeBitSet(int[] a) { BitArray bs = new BitArray(a.Length); foreach (int e in a) { bs.SafeSet(e, true); } return bs; } private void CheckPrevSetBitArray(int[] a, int numBits) { Int64BitSet obs = MakeLongFixedBitSet(a, numBits); BitArray bs = MakeBitSet(a); DoPrevSetBit(bs, obs); } [Test] public virtual void TestPrevSetBit() { CheckPrevSetBitArray(new int[] { }, 0); CheckPrevSetBitArray(new int[] { 0 }, 1); CheckPrevSetBitArray(new int[] { 0, 2 }, 3); } private void CheckNextSetBitArray(int[] a, int numBits) { Int64BitSet obs = MakeLongFixedBitSet(a, numBits); BitArray bs = MakeBitSet(a); DoNextSetBit(bs, obs); } [Test] public virtual void TestNextBitSet() { int[] setBits = new int[0 + Random.Next(1000)]; for (int i = 0; i < setBits.Length; i++) { setBits[i] = Random.Next(setBits.Length); } CheckNextSetBitArray(setBits, setBits.Length + Random.Next(10)); CheckNextSetBitArray(new int[0], setBits.Length + Random.Next(10)); } [Test] public virtual void TestEnsureCapacity() { Int64BitSet bits = new Int64BitSet(5); bits.Set(1); bits.Set(4); Int64BitSet newBits = Int64BitSet.EnsureCapacity(bits, 8); // grow within the word Assert.IsTrue(newBits.Get(1)); Assert.IsTrue(newBits.Get(4)); newBits.Clear(1); // we align to 64-bits, so even though it shouldn't have, it re-allocated a long[1] Assert.IsTrue(bits.Get(1)); Assert.IsFalse(newBits.Get(1)); newBits.Set(1); newBits = Int64BitSet.EnsureCapacity(newBits, newBits.Length - 2); // reuse Assert.IsTrue(newBits.Get(1)); bits.Set(1); newBits = Int64BitSet.EnsureCapacity(bits, 72); // grow beyond one word Assert.IsTrue(newBits.Get(1)); Assert.IsTrue(newBits.Get(4)); newBits.Clear(1); // we grew the long[], so it's not shared Assert.IsTrue(bits.Get(1)); Assert.IsFalse(newBits.Get(1)); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System.IO; namespace IIWGTI { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SubjectNames subjects; KeyboardState oldKb; Texture2D spriteSheet; Rectangle[] rects; string[] names; bool enterKeyPressed; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; //graphics.PreferredBackBufferWidth = 1000; //graphics.ApplyChanges(); } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { this.IsMouseVisible = true; // TODO: Add your initialization logic here subjects = SubjectNames.CompSci; rects = new Rectangle[16]; names = new string[16]; enterKeyPressed = false; oldKb = Keyboard.GetState(); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here spriteSheet = this.Content.Load<Texture2D>("Test Image"); ReadStringFile(@"Content/Test Image - Names.txt"); ReadIntegerFile(@"Content/Test Image - Points.txt"); } void ReadStringFile(string path) { try { using (StreamReader reader = new StreamReader(path)) { int i = 0; while (!reader.EndOfStream) { string line = reader.ReadLine(); names[i] = line; i++; } } } catch (Exception e) { Console.WriteLine("Error with file:"); Console.WriteLine(e.Message); } } private void ReadIntegerFile(string path) { try { using (StreamReader reader = new StreamReader(path)) { int i = 0; while (!reader.EndOfStream) { string line = reader.ReadLine(); string[] parts = line.Split(' '); rects[i] = new Rectangle(Convert.ToInt32(parts[0]), Convert.ToInt32(parts[1]), Convert.ToInt32(parts[2]), Convert.ToInt32(parts[3])); i++; } } } catch (Exception e) { Console.WriteLine("Error with file:"); Console.WriteLine(e.Message); } } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { KeyboardState kb = Keyboard.GetState(); // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit(); // TODO: Add your update logic here if (kb.IsKeyDown(Keys.Space) && !(oldKb.IsKeyDown(Keys.Space))) { switch (subjects) { case SubjectNames.CompSci: subjects = SubjectNames.English; break; case SubjectNames.English: subjects = SubjectNames.Math; break; case SubjectNames.Math: subjects = SubjectNames.PE; break; case SubjectNames.PE: subjects = SubjectNames.CompSci; break; } } oldKb = kb; base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); // TODO: Add your drawing code here switch (subjects) { case SubjectNames.CompSci: if (!enterKeyPressed) { for (int i = 0;i < 4;i++) { switch (i) { case 0: spriteBatch.Draw(spriteSheet, new Rectangle(10, 10, rects[1].Width / 2, rects[1].Height / 2), rects[1], Color.White); break; case 1: spriteBatch.Draw(spriteSheet, new Rectangle(rects[1].Width / 2 + 20, 10, rects[0].Width / 2, rects[0].Height / 2), rects[0], Color.White); break; case 2: spriteBatch.Draw(spriteSheet, new Rectangle(rects[0].Width / 2 + 200, 10, rects[2].Width / 2, rects[2].Height / 2), rects[2], Color.White); break; case 3: spriteBatch.Draw(spriteSheet, new Rectangle(rects[2].Width / 2 + 350, 10, rects[3].Width / 2, rects[3].Height / 2), rects[3], Color.White); break; } } } else { } break; case SubjectNames.English: if (!enterKeyPressed) { for (int i = 0; i < 4; i++) { switch (i) { case 0: spriteBatch.Draw(spriteSheet, new Rectangle(10, 10, rects[4].Width , rects[4].Height ), rects[4], Color.White); break; case 1: spriteBatch.Draw(spriteSheet, new Rectangle(rects[4].Width + 20, 10, rects[6].Width , rects[6].Height ), rects[6], Color.White); break; case 2: spriteBatch.Draw(spriteSheet, new Rectangle(rects[6].Width + 450, 10, rects[5].Width, rects[5].Height), rects[5], Color.White); break; case 3: spriteBatch.Draw(spriteSheet, new Rectangle(rects[5].Width + 200, 10, rects[7].Width, rects[7].Height), rects[7], Color.White); break; } } } else { } break; case SubjectNames.Math: if (!enterKeyPressed) { for (int i = 0; i < 4; i++) { switch (i) { case 0: spriteBatch.Draw(spriteSheet, new Rectangle(10, 10, rects[8].Width, rects[8].Height), rects[8], Color.White); break; case 1: spriteBatch.Draw(spriteSheet, new Rectangle(rects[8].Width + 20, 10, rects[9].Width, rects[9].Height), rects[9], Color.White); break; case 2: spriteBatch.Draw(spriteSheet, new Rectangle(rects[9].Width + 20, 10, rects[10].Width, rects[10].Height), rects[9], Color.White); break; case 3: spriteBatch.Draw(spriteSheet, new Rectangle(rects[10].Width + 100, 10, rects[11].Width, rects[11].Height), rects[11], Color.White); break; } } } else { } break; case SubjectNames.PE: if (!enterKeyPressed) { } else { } break; default: Console.WriteLine("Error with SWITCH"); this.Exit(); break; } spriteBatch.End(); base.Draw(gameTime); } } }
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Expressions = Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Expressions; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.Agent.Worker.Handlers; using Microsoft.VisualStudio.Services.Agent.Worker.Container; using System.Threading; using System.Linq; namespace Microsoft.VisualStudio.Services.Agent.Worker { [ServiceLocator(Default = typeof(LinuxContainerOperationProvider))] public interface IContainerOperationProvider : IAgentService { IStep GetContainerStartStep(IExecutionContext jobContext); IStep GetContainerStopStep(IExecutionContext jobContext); void GetHandlerContainerExecutionCommandline(IExecutionContext executionContext, string filePath, string arguments, string workingDirectory, IDictionary<string, string> environment, out string containerEnginePath, out string containerExecutionArgs); } public class LinuxContainerOperationProvider : AgentService, IContainerOperationProvider { private IDockerCommandManager _dockerManger; public override void Initialize(IHostContext hostContext) { base.Initialize(hostContext); _dockerManger = HostContext.GetService<IDockerCommandManager>(); } public IStep GetContainerStartStep(IExecutionContext jobContext) { return new JobExtensionRunner(context: jobContext.CreateChild(Guid.NewGuid(), StringUtil.Loc("InitializeContainer"), nameof(LinuxContainerOperationProvider)), runAsync: StartContainerAsync, condition: ExpressionManager.Succeeded, displayName: StringUtil.Loc("InitializeContainer")); } public IStep GetContainerStopStep(IExecutionContext jobContext) { return new JobExtensionRunner(context: jobContext.CreateChild(Guid.NewGuid(), StringUtil.Loc("StopContainer"), nameof(LinuxContainerOperationProvider)), runAsync: StopContainerAsync, condition: ExpressionManager.Always, displayName: StringUtil.Loc("StopContainer")); } public void GetHandlerContainerExecutionCommandline( IExecutionContext executionContext, string filePath, string arguments, string workingDirectory, IDictionary<string, string> environment, out string containerEnginePath, out string containerExecutionArgs) { string envOptions = ""; foreach (var env in environment) { envOptions += $" -e \"{env.Key}={env.Value.Replace("\"", "\\\"")}\""; } // we need cd to the workingDir then run the executable with args. // bash -c "cd \"workingDirectory\"; \"filePath\" \"arguments\"" string workingDirectoryEscaped = StringUtil.Format(@"\""{0}\""", workingDirectory.Replace(@"""", @"\\\""")); string filePathEscaped = StringUtil.Format(@"\""{0}\""", filePath.Replace(@"""", @"\\\""")); string argumentsEscaped = arguments.Replace(@"\", @"\\").Replace(@"""", @"\"""); string bashCommandLine = $"bash -c \"cd {workingDirectoryEscaped}&{filePathEscaped} {argumentsEscaped}\""; arguments = $"exec -u {executionContext.Container.CurrentUserId} {envOptions} {executionContext.Container.ContainerId} {bashCommandLine}"; containerEnginePath = _dockerManger.DockerPath; containerExecutionArgs = arguments; } private async Task StartContainerAsync(IExecutionContext executionContext) { Trace.Entering(); ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNullOrEmpty(executionContext.Container.ContainerImage, nameof(executionContext.Container.ContainerImage)); // Check docker client/server version DockerVersion dockerVersion = await _dockerManger.DockerVersion(executionContext); ArgUtil.NotNull(dockerVersion.ServerVersion, nameof(dockerVersion.ServerVersion)); ArgUtil.NotNull(dockerVersion.ClientVersion, nameof(dockerVersion.ClientVersion)); Version requiredDockerVersion = new Version(17, 3); if (dockerVersion.ServerVersion < requiredDockerVersion) { throw new NotSupportedException(StringUtil.Loc("MinRequiredDockerServerVersion", requiredDockerVersion, _dockerManger.DockerPath, dockerVersion.ServerVersion)); } if (dockerVersion.ClientVersion < requiredDockerVersion) { throw new NotSupportedException(StringUtil.Loc("MinRequiredDockerClientVersion", requiredDockerVersion, _dockerManger.DockerPath, dockerVersion.ClientVersion)); } // Pull down docker image int pullExitCode = await _dockerManger.DockerPull(executionContext, executionContext.Container.ContainerImage); if (pullExitCode != 0) { throw new InvalidOperationException($"Docker pull fail with exit code {pullExitCode}"); } // Mount folder into container executionContext.Container.MountVolumes.Add(new MountVolume(Path.GetDirectoryName(executionContext.Variables.System_DefaultWorkingDirectory.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)))); executionContext.Container.MountVolumes.Add(new MountVolume(executionContext.Variables.Agent_TempDirectory)); executionContext.Container.MountVolumes.Add(new MountVolume(executionContext.Variables.Agent_ToolsDirectory)); executionContext.Container.MountVolumes.Add(new MountVolume(HostContext.GetDirectory(WellKnownDirectory.Externals), true)); executionContext.Container.MountVolumes.Add(new MountVolume(HostContext.GetDirectory(WellKnownDirectory.Tasks), true)); // Ensure .taskkey file exist so we can mount it. string taskKeyFile = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), ".taskkey"); if (!File.Exists(taskKeyFile)) { File.WriteAllText(taskKeyFile, string.Empty); } executionContext.Container.MountVolumes.Add(new MountVolume(taskKeyFile)); executionContext.Container.ContainerId = await _dockerManger.DockerCreate(executionContext, executionContext.Container.ContainerImage, executionContext.Container.MountVolumes); ArgUtil.NotNullOrEmpty(executionContext.Container.ContainerId, nameof(executionContext.Container.ContainerId)); // Get current username executionContext.Container.CurrentUserName = (await ExecuteCommandAsync(executionContext, "whoami", string.Empty)).FirstOrDefault(); ArgUtil.NotNullOrEmpty(executionContext.Container.CurrentUserName, nameof(executionContext.Container.CurrentUserName)); // Get current userId executionContext.Container.CurrentUserId = (await ExecuteCommandAsync(executionContext, "id", $"-u {executionContext.Container.CurrentUserName}")).FirstOrDefault(); ArgUtil.NotNullOrEmpty(executionContext.Container.CurrentUserId, nameof(executionContext.Container.CurrentUserId)); int startExitCode = await _dockerManger.DockerStart(executionContext, executionContext.Container.ContainerId); if (startExitCode != 0) { throw new InvalidOperationException($"Docker start fail with exit code {startExitCode}"); } // Ensure bash exist in the image int execWhichBashExitCode = await _dockerManger.DockerExec(executionContext, executionContext.Container.ContainerId, string.Empty, $"which bash"); if (execWhichBashExitCode != 0) { throw new InvalidOperationException($"Docker exec fail with exit code {execWhichBashExitCode}"); } // Create an user with same uid as the agent run as user inside the container. // All command execute in docker will run as Root by default, // this will cause the agent on the host machine doesn't have permission to any new file/folder created inside the container. // So, we create a user account with same UID inside the container and let all docker exec command run as that user. int execUseraddExitCode = await _dockerManger.DockerExec(executionContext, executionContext.Container.ContainerId, string.Empty, $"useradd -m -o -u {executionContext.Container.CurrentUserId} {executionContext.Container.CurrentUserName}_VSTSContainer"); if (execUseraddExitCode != 0) { throw new InvalidOperationException($"Docker exec fail with exit code {execUseraddExitCode}"); } } private async Task StopContainerAsync(IExecutionContext executionContext) { Trace.Entering(); ArgUtil.NotNull(executionContext, nameof(executionContext)); if (!string.IsNullOrEmpty(executionContext.Container.ContainerId)) { executionContext.Output($"Stop container: {executionContext.Container.ContainerName}"); int stopExitCode = await _dockerManger.DockerStop(executionContext, executionContext.Container.ContainerId); if (stopExitCode != 0) { executionContext.Error($"Docker stop fail with exit code {stopExitCode}"); } } } private async Task<List<string>> ExecuteCommandAsync(IExecutionContext context, string command, string arg) { context.Command($"{command} {arg}"); List<string> outputs = new List<string>(); object outputLock = new object(); var processInvoker = HostContext.CreateService<IProcessInvoker>(); processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { if (!string.IsNullOrEmpty(message.Data)) { lock (outputLock) { outputs.Add(message.Data); } } }; processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { if (!string.IsNullOrEmpty(message.Data)) { lock (outputLock) { outputs.Add(message.Data); } } }; await processInvoker.ExecuteAsync( workingDirectory: context.Variables.Agent_WorkFolder, fileName: command, arguments: arg, environment: null, requireExitCodeZero: true, outputEncoding: null, cancellationToken: CancellationToken.None); foreach (var outputLine in outputs) { context.Output(outputLine); } return outputs; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ #pragma warning disable 1591 // disable warning on missing comments using System; using Adaptive.SimpleBinaryEncoding; namespace Adaptive.SimpleBinaryEncoding.Tests.Generated { public class MDIncrementalRefreshSessionStatistics { public const ushort TemplateId = (ushort)22; public const byte TemplateVersion = (byte)1; public const ushort BlockLength = (ushort)9; public const string SematicType = "X"; private readonly MDIncrementalRefreshSessionStatistics _parentMessage; private DirectBuffer _buffer; private int _offset; private int _limit; private int _actingBlockLength; private int _actingVersion; public int Offset { get { return _offset; } } public MDIncrementalRefreshSessionStatistics() { _parentMessage = this; } public void WrapForEncode(DirectBuffer buffer, int offset) { _buffer = buffer; _offset = offset; _actingBlockLength = BlockLength; _actingVersion = TemplateVersion; Limit = offset + _actingBlockLength; } public void WrapForDecode(DirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { _buffer = buffer; _offset = offset; _actingBlockLength = actingBlockLength; _actingVersion = actingVersion; Limit = offset + _actingBlockLength; } public int Size { get { return _limit - _offset; } } public int Limit { get { return _limit; } set { _buffer.CheckLimit(value); _limit = value; } } public const int TransactTimeSchemaId = 60; public static string TransactTimeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "UTCTimestamp"; } return ""; } public const ulong TransactTimeNullValue = 0x8000000000000000UL; public const ulong TransactTimeMinValue = 0x0UL; public const ulong TransactTimeMaxValue = 0x7fffffffffffffffUL; public ulong TransactTime { get { return _buffer.Uint64GetLittleEndian(_offset + 0); } set { _buffer.Uint64PutLittleEndian(_offset + 0, value); } } public const int MatchEventIndicatorSchemaId = 5799; public static string MatchEventIndicatorMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "MultipleCharValue"; } return ""; } public MatchEventIndicator MatchEventIndicator { get { return (MatchEventIndicator)_buffer.Uint8Get(_offset + 8); } set { _buffer.Uint8Put(_offset + 8, (byte)value); } } private readonly NoMDEntriesGroup _noMDEntries = new NoMDEntriesGroup(); public const long NoMDEntriesSchemaId = 268; public NoMDEntriesGroup NoMDEntries { get { _noMDEntries.WrapForDecode(_parentMessage, _buffer, _actingVersion); return _noMDEntries; } } public NoMDEntriesGroup NoMDEntriesCount(int count) { _noMDEntries.WrapForEncode(_parentMessage, _buffer, count); return _noMDEntries; } public class NoMDEntriesGroup { private readonly GroupSize _dimensions = new GroupSize(); private MDIncrementalRefreshSessionStatistics _parentMessage; private DirectBuffer _buffer; private int _blockLength; private int _actingVersion; private int _count; private int _index; private int _offset; public void WrapForDecode(MDIncrementalRefreshSessionStatistics parentMessage, DirectBuffer buffer, int actingVersion) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, actingVersion); _count = _dimensions.NumInGroup; _blockLength = _dimensions.BlockLength; _actingVersion = actingVersion; _index = -1; _parentMessage.Limit = parentMessage.Limit + 3; } public void WrapForEncode(MDIncrementalRefreshSessionStatistics parentMessage, DirectBuffer buffer, int count) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion); _dimensions.NumInGroup = (byte)count; _dimensions.BlockLength = (ushort)19; _index = -1; _count = count; _blockLength = 19; parentMessage.Limit = parentMessage.Limit + 3; } public int Count { get { return _count; } } public bool HasNext { get { return _index + 1 < _count; } } public NoMDEntriesGroup Next() { if (_index + 1 >= _count) { throw new InvalidOperationException(); } _offset = _parentMessage.Limit; _parentMessage.Limit = _offset + _blockLength; ++_index; return this; } public const int MDUpdateActionSchemaId = 279; public static string MDUpdateActionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public MDUpdateAction MDUpdateAction { get { return (MDUpdateAction)_buffer.Uint8Get(_offset + 0); } set { _buffer.Uint8Put(_offset + 0, (byte)value); } } public const int MDEntryTypeSchemaId = 269; public static string MDEntryTypeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "char"; } return ""; } public MDEntryTypeStatistics MDEntryType { get { return (MDEntryTypeStatistics)_buffer.CharGet(_offset + 1); } set { _buffer.CharPut(_offset + 1, (byte)value); } } public const int SecurityIDSchemaId = 48; public static string SecurityIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public const int SecurityIDNullValue = -2147483648; public const int SecurityIDMinValue = -2147483647; public const int SecurityIDMaxValue = 2147483647; public int SecurityID { get { return _buffer.Int32GetLittleEndian(_offset + 2); } set { _buffer.Int32PutLittleEndian(_offset + 2, value); } } public const int RptSeqSchemaId = 83; public static string RptSeqMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public const int RptSeqNullValue = -2147483648; public const int RptSeqMinValue = -2147483647; public const int RptSeqMaxValue = 2147483647; public int RptSeq { get { return _buffer.Int32GetLittleEndian(_offset + 6); } set { _buffer.Int32PutLittleEndian(_offset + 6, value); } } public const int MDEntryPxSchemaId = 270; public static string MDEntryPxMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "Price"; } return ""; } private readonly PRICE _mDEntryPx = new PRICE(); public PRICE MDEntryPx { get { _mDEntryPx.Wrap(_buffer, _offset + 10, _actingVersion); return _mDEntryPx; } } public const int OpenCloseSettlFlagSchemaId = 286; public static string OpenCloseSettlFlagMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public OpenCloseSettlFlag OpenCloseSettlFlag { get { return (OpenCloseSettlFlag)_buffer.Uint8Get(_offset + 18); } set { _buffer.Uint8Put(_offset + 18, (byte)value); } } } } }
/* This version of ObjImporter first reads through the entire file, getting a count of how large * the final arrays will be, and then uses standard arrays for everything (as opposed to ArrayLists * or any other fancy things). * * Script downloaded from: * http://wiki.unity3d.com/index.php?title=ObjImporter */ using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace Ecosim { public class ObjImporter { private struct meshStruct { public Vector3[] vertices; public Vector3[] normals; public Vector2[] uv; public Vector2[] uv1; public Vector2[] uv2; public int[] triangles; public int[] faceVerts; public int[] faceUVs; public Vector3[] faceData; public string name; public string fileName; } // Use this for initialization public static Mesh ImportFile (string filePath, Vector3 scale) { meshStruct newMesh = createMeshStruct (filePath); populateMeshStruct (ref newMesh); Vector3[] newVerts = new Vector3[newMesh.faceData.Length]; Vector2[] newUVs = new Vector2[newMesh.faceData.Length]; Vector3[] newNormals = new Vector3[newMesh.faceData.Length]; int i = 0; /* The following foreach loops through the facedata and assigns the appropriate vertex, uv, or normal * for the appropriate Unity mesh array. */ foreach (Vector3 v in newMesh.faceData) { newVerts [i] = Vector3.Scale (newMesh.vertices [(int)v.x - 1], scale); if (v.y >= 1) newUVs [i] = newMesh.uv [(int)v.y - 1]; if (v.z >= 1) newNormals [i] = newMesh.normals [(int)v.z - 1]; i++; } Mesh mesh = new Mesh (); mesh.vertices = newVerts; mesh.uv = newUVs; mesh.normals = newNormals; mesh.triangles = newMesh.triangles; mesh.RecalculateBounds (); mesh.Optimize (); return mesh; } private static meshStruct createMeshStruct (string filename) { int triangles = 0; int vertices = 0; int vt = 0; int vn = 0; int face = 0; meshStruct mesh = new meshStruct (); mesh.fileName = filename; StreamReader stream = File.OpenText (filename); string entireText = stream.ReadToEnd (); stream.Close (); using (StringReader reader = new StringReader(entireText)) { string currentText = reader.ReadLine (); char[] splitIdentifier = { ' ' }; string[] brokenString; while (currentText != null) { if (!currentText.StartsWith ("f ") && !currentText.StartsWith ("v ") && !currentText.StartsWith ("vt ") && !currentText.StartsWith ("vn ")) { currentText = reader.ReadLine (); if (currentText != null) { currentText = currentText.Replace (" ", " "); } } else { currentText = currentText.Trim (); //Trim the current line brokenString = currentText.Split (splitIdentifier, 50); //Split the line into an array, separating the original line by blank spaces switch (brokenString [0]) { case "v": vertices++; break; case "vt": vt++; break; case "vn": vn++; break; case "f": face = face + brokenString.Length - 1; triangles = triangles + 3 * (brokenString.Length - 2); /*brokenString.Length is 3 or greater since a face must have at least 3 vertices. For each additional vertice, there is an additional triangle in the mesh (hence this formula).*/ break; } currentText = reader.ReadLine (); if (currentText != null) { currentText = currentText.Replace (" ", " "); } } } } mesh.triangles = new int[triangles]; mesh.vertices = new Vector3[vertices]; mesh.uv = new Vector2[vt]; mesh.normals = new Vector3[vn]; mesh.faceData = new Vector3[face]; return mesh; } private static void populateMeshStruct (ref meshStruct mesh) { StreamReader stream = File.OpenText (mesh.fileName); string entireText = stream.ReadToEnd (); stream.Close (); using (StringReader reader = new StringReader(entireText)) { string currentText = reader.ReadLine (); char[] splitIdentifier = { ' ' }; char[] splitIdentifier2 = { '/' }; string[] brokenString; string[] brokenBrokenString; int f = 0; int f2 = 0; int v = 0; int vn = 0; int vt = 0; int vt1 = 0; int vt2 = 0; while (currentText != null) { if (!currentText.StartsWith ("f ") && !currentText.StartsWith ("v ") && !currentText.StartsWith ("vt ") && !currentText.StartsWith ("vn ") && !currentText.StartsWith ("g ") && !currentText.StartsWith ("usemtl ") && !currentText.StartsWith ("mtllib ") && !currentText.StartsWith ("vt1 ") && !currentText.StartsWith ("vt2 ") && !currentText.StartsWith ("vc ") && !currentText.StartsWith ("usemap ")) { currentText = reader.ReadLine (); if (currentText != null) { currentText = currentText.Replace (" ", " "); } } else { currentText = currentText.Trim (); brokenString = currentText.Split (splitIdentifier, 50); switch (brokenString [0]) { case "#": break; case "g": break; case "usemtl": break; case "usemap": break; case "mtllib": break; case "v": mesh.vertices [v] = new Vector3 (System.Convert.ToSingle (brokenString [1]), System.Convert.ToSingle (brokenString [2]), System.Convert.ToSingle (brokenString [3])); v++; break; case "vt": mesh.uv [vt] = new Vector2 (System.Convert.ToSingle (brokenString [1]), System.Convert.ToSingle (brokenString [2])); vt++; break; case "vt1": mesh.uv [vt1] = new Vector2 (System.Convert.ToSingle (brokenString [1]), System.Convert.ToSingle (brokenString [2])); vt1++; break; case "vt2": mesh.uv [vt2] = new Vector2 (System.Convert.ToSingle (brokenString [1]), System.Convert.ToSingle (brokenString [2])); vt2++; break; case "vn": mesh.normals [vn] = new Vector3 (System.Convert.ToSingle (brokenString [1]), System.Convert.ToSingle (brokenString [2]), System.Convert.ToSingle (brokenString [3])); vn++; break; case "vc": break; case "f": int j = 1; List<int> intArray = new List<int> (); while (j < brokenString.Length && ("" + brokenString[j]).Length > 0) { Vector3 temp = new Vector3 (); brokenBrokenString = brokenString [j].Split (splitIdentifier2, 3); // Separate the face into individual components (vert, uv, normal) temp.x = System.Convert.ToInt32 (brokenBrokenString [0]); if (brokenBrokenString.Length > 1) { // Some .obj files skip UV and normal if (brokenBrokenString [1] != "") { // Some .obj files skip the uv and not the normal temp.y = System.Convert.ToInt32 (brokenBrokenString [1]); } temp.z = System.Convert.ToInt32 (brokenBrokenString [2]); } j++; mesh.faceData [f2] = temp; intArray.Add (f2); f2++; } j = 1; while (j + 2 < brokenString.Length) { // Create triangles out of the face data. There will generally be more than 1 triangle per face. mesh.triangles [f] = intArray [0]; f++; mesh.triangles [f] = intArray [j]; f++; mesh.triangles [f] = intArray [j + 1]; f++; j++; } break; } currentText = reader.ReadLine (); if (currentText != null) { currentText = currentText.Replace (" ", " "); // Some .obj files insert double spaces, this removes them. } } } } } } }
using Prism.Logging; using Prism.Properties; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Prism.Modularity { /// <summary> /// Component responsible for coordinating the modules' type loading and module initialization process. /// </summary> public partial class ModuleManager : IModuleManager, IDisposable { private readonly IModuleInitializer moduleInitializer; private readonly IModuleCatalog moduleCatalog; private readonly ILoggerFacade loggerFacade; private IEnumerable<IModuleTypeLoader> typeLoaders; private HashSet<IModuleTypeLoader> subscribedToModuleTypeLoaders = new HashSet<IModuleTypeLoader>(); /// <summary> /// Initializes an instance of the <see cref="ModuleManager"/> class. /// </summary> /// <param name="moduleInitializer">Service used for initialization of modules.</param> /// <param name="moduleCatalog">Catalog that enumerates the modules to be loaded and initialized.</param> /// <param name="loggerFacade">Logger used during the load and initialization of modules.</param> public ModuleManager(IModuleInitializer moduleInitializer, IModuleCatalog moduleCatalog, ILoggerFacade loggerFacade) { if (moduleInitializer == null) throw new ArgumentNullException(nameof(moduleInitializer)); if (moduleCatalog == null) throw new ArgumentNullException(nameof(moduleCatalog)); if (loggerFacade == null) throw new ArgumentNullException(nameof(loggerFacade)); this.moduleInitializer = moduleInitializer; this.moduleCatalog = moduleCatalog; this.loggerFacade = loggerFacade; } /// <summary> /// The module catalog specified in the constructor. /// </summary> protected IModuleCatalog ModuleCatalog { get { return this.moduleCatalog; } } /// <summary> /// Raised repeatedly to provide progress as modules are loaded in the background. /// </summary> public event EventHandler<ModuleDownloadProgressChangedEventArgs> ModuleDownloadProgressChanged; private void RaiseModuleDownloadProgressChanged(ModuleDownloadProgressChangedEventArgs e) { if (this.ModuleDownloadProgressChanged != null) { this.ModuleDownloadProgressChanged(this, e); } } /// <summary> /// Raised when a module is loaded or fails to load. /// </summary> public event EventHandler<LoadModuleCompletedEventArgs> LoadModuleCompleted; private void RaiseLoadModuleCompleted(ModuleInfo moduleInfo, Exception error) { this.RaiseLoadModuleCompleted(new LoadModuleCompletedEventArgs(moduleInfo, error)); } private void RaiseLoadModuleCompleted(LoadModuleCompletedEventArgs e) { if (this.LoadModuleCompleted != null) { this.LoadModuleCompleted(this, e); } } /// <summary> /// Initializes the modules marked as <see cref="InitializationMode.WhenAvailable"/> on the <see cref="ModuleCatalog"/>. /// </summary> public void Run() { this.moduleCatalog.Initialize(); this.LoadModulesWhenAvailable(); } /// <summary> /// Loads and initializes the module on the <see cref="ModuleCatalog"/> with the name <paramref name="moduleName"/>. /// </summary> /// <param name="moduleName">Name of the module requested for initialization.</param> public void LoadModule(string moduleName) { IEnumerable<ModuleInfo> module = this.moduleCatalog.Modules.Where(m => m.ModuleName == moduleName); if (module == null || module.Count() != 1) { throw new ModuleNotFoundException(moduleName, string.Format(CultureInfo.CurrentCulture, Resources.ModuleNotFound, moduleName)); } IEnumerable<ModuleInfo> modulesToLoad = this.moduleCatalog.CompleteListWithDependencies(module); this.LoadModuleTypes(modulesToLoad); } /// <summary> /// Checks if the module needs to be retrieved before it's initialized. /// </summary> /// <param name="moduleInfo">Module that is being checked if needs retrieval.</param> /// <returns></returns> protected virtual bool ModuleNeedsRetrieval(ModuleInfo moduleInfo) { if (moduleInfo == null) throw new ArgumentNullException(nameof(moduleInfo)); if (moduleInfo.State == ModuleState.NotStarted) { // If we can instantiate the type, that means the module's assembly is already loaded into // the AppDomain and we don't need to retrieve it. bool isAvailable = Type.GetType(moduleInfo.ModuleType) != null; if (isAvailable) { moduleInfo.State = ModuleState.ReadyForInitialization; } return !isAvailable; } return false; } private void LoadModulesWhenAvailable() { IEnumerable<ModuleInfo> whenAvailableModules = this.moduleCatalog.Modules.Where(m => m.InitializationMode == InitializationMode.WhenAvailable); IEnumerable<ModuleInfo> modulesToLoadTypes = this.moduleCatalog.CompleteListWithDependencies(whenAvailableModules); if (modulesToLoadTypes != null) { this.LoadModuleTypes(modulesToLoadTypes); } } private void LoadModuleTypes(IEnumerable<ModuleInfo> moduleInfos) { if (moduleInfos == null) { return; } foreach (ModuleInfo moduleInfo in moduleInfos) { if (moduleInfo.State == ModuleState.NotStarted) { if (this.ModuleNeedsRetrieval(moduleInfo)) { this.BeginRetrievingModule(moduleInfo); } else { moduleInfo.State = ModuleState.ReadyForInitialization; } } } this.LoadModulesThatAreReadyForLoad(); } /// <summary> /// Loads the modules that are not intialized and have their dependencies loaded. /// </summary> protected virtual void LoadModulesThatAreReadyForLoad() { bool keepLoading = true; while (keepLoading) { keepLoading = false; IEnumerable<ModuleInfo> availableModules = this.moduleCatalog.Modules.Where(m => m.State == ModuleState.ReadyForInitialization); foreach (ModuleInfo moduleInfo in availableModules) { if ((moduleInfo.State != ModuleState.Initialized) && (this.AreDependenciesLoaded(moduleInfo))) { moduleInfo.State = ModuleState.Initializing; this.InitializeModule(moduleInfo); keepLoading = true; break; } } } } private void BeginRetrievingModule(ModuleInfo moduleInfo) { ModuleInfo moduleInfoToLoadType = moduleInfo; IModuleTypeLoader moduleTypeLoader = this.GetTypeLoaderForModule(moduleInfoToLoadType); moduleInfoToLoadType.State = ModuleState.LoadingTypes; // Delegate += works differently betweem SL and WPF. // We only want to subscribe to each instance once. if (!this.subscribedToModuleTypeLoaders.Contains(moduleTypeLoader)) { moduleTypeLoader.ModuleDownloadProgressChanged += this.IModuleTypeLoader_ModuleDownloadProgressChanged; moduleTypeLoader.LoadModuleCompleted += this.IModuleTypeLoader_LoadModuleCompleted; this.subscribedToModuleTypeLoaders.Add(moduleTypeLoader); } moduleTypeLoader.LoadModuleType(moduleInfo); } private void IModuleTypeLoader_ModuleDownloadProgressChanged(object sender, ModuleDownloadProgressChangedEventArgs e) { this.RaiseModuleDownloadProgressChanged(e); } private void IModuleTypeLoader_LoadModuleCompleted(object sender, LoadModuleCompletedEventArgs e) { if (e.Error == null) { if ((e.ModuleInfo.State != ModuleState.Initializing) && (e.ModuleInfo.State != ModuleState.Initialized)) { e.ModuleInfo.State = ModuleState.ReadyForInitialization; } // This callback may call back on the UI thread, but we are not guaranteeing it. // If you were to add a custom retriever that retrieved in the background, you // would need to consider dispatching to the UI thread. this.LoadModulesThatAreReadyForLoad(); } else { this.RaiseLoadModuleCompleted(e); // If the error is not handled then I log it and raise an exception. if (!e.IsErrorHandled) { this.HandleModuleTypeLoadingError(e.ModuleInfo, e.Error); } } } /// <summary> /// Handles any exception occurred in the module typeloading process, /// logs the error using the <see cref="ILoggerFacade"/> and throws a <see cref="ModuleTypeLoadingException"/>. /// This method can be overridden to provide a different behavior. /// </summary> /// <param name="moduleInfo">The module metadata where the error happenened.</param> /// <param name="exception">The exception thrown that is the cause of the current error.</param> /// <exception cref="ModuleTypeLoadingException"></exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1")] protected virtual void HandleModuleTypeLoadingError(ModuleInfo moduleInfo, Exception exception) { if (moduleInfo == null) throw new ArgumentNullException(nameof(moduleInfo)); ModuleTypeLoadingException moduleTypeLoadingException = exception as ModuleTypeLoadingException; if (moduleTypeLoadingException == null) { moduleTypeLoadingException = new ModuleTypeLoadingException(moduleInfo.ModuleName, exception.Message, exception); } this.loggerFacade.Log(moduleTypeLoadingException.Message, Category.Exception, Priority.High); throw moduleTypeLoadingException; } private bool AreDependenciesLoaded(ModuleInfo moduleInfo) { IEnumerable<ModuleInfo> requiredModules = this.moduleCatalog.GetDependentModules(moduleInfo); if (requiredModules == null) { return true; } int notReadyRequiredModuleCount = requiredModules.Count(requiredModule => requiredModule.State != ModuleState.Initialized); return notReadyRequiredModuleCount == 0; } private IModuleTypeLoader GetTypeLoaderForModule(ModuleInfo moduleInfo) { foreach (IModuleTypeLoader typeLoader in this.ModuleTypeLoaders) { if (typeLoader.CanLoadModuleType(moduleInfo)) { return typeLoader; } } throw new ModuleTypeLoaderNotFoundException(moduleInfo.ModuleName, String.Format(CultureInfo.CurrentCulture, Resources.NoRetrieverCanRetrieveModule, moduleInfo.ModuleName), null); } private void InitializeModule(ModuleInfo moduleInfo) { if (moduleInfo.State == ModuleState.Initializing) { this.moduleInitializer.Initialize(moduleInfo); moduleInfo.State = ModuleState.Initialized; this.RaiseLoadModuleCompleted(moduleInfo, null); } } #region Implementation of IDisposable /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <remarks>Calls <see cref="Dispose(bool)"/></remarks>. /// <filterpriority>2</filterpriority> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Disposes the associated <see cref="IModuleTypeLoader"/>s. /// </summary> /// <param name="disposing">When <see langword="true"/>, it is being called from the Dispose method.</param> protected virtual void Dispose(bool disposing) { foreach (IModuleTypeLoader typeLoader in this.ModuleTypeLoaders) { IDisposable disposableTypeLoader = typeLoader as IDisposable; if (disposableTypeLoader != null) { disposableTypeLoader.Dispose(); } } } #endregion } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class NewLeaderEventEncoder { public const ushort BLOCK_LENGTH = 20; public const ushort TEMPLATE_ID = 6; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private NewLeaderEventEncoder _parentMessage; private IMutableDirectBuffer _buffer; protected int _offset; protected int _limit; public NewLeaderEventEncoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IMutableDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public NewLeaderEventEncoder Wrap(IMutableDirectBuffer buffer, int offset) { this._buffer = buffer; this._offset = offset; Limit(offset + BLOCK_LENGTH); return this; } public NewLeaderEventEncoder WrapAndApplyHeader( IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder) { headerEncoder .Wrap(buffer, offset) .BlockLength(BLOCK_LENGTH) .TemplateId(TEMPLATE_ID) .SchemaId(SCHEMA_ID) .Version(SCHEMA_VERSION); return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int LeadershipTermIdEncodingOffset() { return 0; } public static int LeadershipTermIdEncodingLength() { return 8; } public static long LeadershipTermIdNullValue() { return -9223372036854775808L; } public static long LeadershipTermIdMinValue() { return -9223372036854775807L; } public static long LeadershipTermIdMaxValue() { return 9223372036854775807L; } public NewLeaderEventEncoder LeadershipTermId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int ClusterSessionIdEncodingOffset() { return 8; } public static int ClusterSessionIdEncodingLength() { return 8; } public static long ClusterSessionIdNullValue() { return -9223372036854775808L; } public static long ClusterSessionIdMinValue() { return -9223372036854775807L; } public static long ClusterSessionIdMaxValue() { return 9223372036854775807L; } public NewLeaderEventEncoder ClusterSessionId(long value) { _buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int LeaderMemberIdEncodingOffset() { return 16; } public static int LeaderMemberIdEncodingLength() { return 4; } public static int LeaderMemberIdNullValue() { return -2147483648; } public static int LeaderMemberIdMinValue() { return -2147483647; } public static int LeaderMemberIdMaxValue() { return 2147483647; } public NewLeaderEventEncoder LeaderMemberId(int value) { _buffer.PutInt(_offset + 16, value, ByteOrder.LittleEndian); return this; } public static int IngressEndpointsId() { return 4; } public static string IngressEndpointsCharacterEncoding() { return "US-ASCII"; } public static string IngressEndpointsMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int IngressEndpointsHeaderLength() { return 4; } public NewLeaderEventEncoder PutIngressEndpoints(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public NewLeaderEventEncoder PutIngressEndpoints(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public NewLeaderEventEncoder IngressEndpoints(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { NewLeaderEventDecoder writer = new NewLeaderEventDecoder(); writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.AppendTo(builder); } } }
using System; using System.Data; using System.Globalization; using System.IO; using System.Text; using System.Xml; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Models.EntityBase; using Umbraco.Web; using umbraco.BasePages; using umbraco.BusinessLogic; using umbraco.BusinessLogic.Actions; using umbraco.cms.businesslogic.propertytype; using umbraco.cms.businesslogic.task; using umbraco.cms.businesslogic.translation; //using umbraco.cms.businesslogic.utilities; using umbraco.cms.businesslogic.web; using ICSharpCode.SharpZipLib.BZip2; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using ICSharpCode.SharpZipLib.GZip; using Umbraco.Core.IO; using System.Collections.Generic; namespace umbraco.presentation.translation { public partial class _default : UmbracoEnsuredPage { public _default() { CurrentApp = DefaultApps.translation.ToString(); } protected void Page_Load(object sender, EventArgs e) { DataTable tasks = new DataTable(); tasks.Columns.Add("Id"); tasks.Columns.Add("Date"); tasks.Columns.Add("NodeId"); tasks.Columns.Add("NodeName"); tasks.Columns.Add("ReferingUser"); tasks.Columns.Add("Language"); taskList.Columns[0].HeaderText = ui.Text("nodeName"); taskList.Columns[1].HeaderText = ui.Text("translation", "taskAssignedBy"); taskList.Columns[2].HeaderText = ui.Text("date"); ((System.Web.UI.WebControls.HyperLinkField)taskList.Columns[3]).Text = ui.Text("translation", "details"); ((System.Web.UI.WebControls.HyperLinkField)taskList.Columns[4]).Text = ui.Text("translation", "downloadTaskAsXml"); Tasks ts = new Tasks(); if (Request["mode"] == "owned") { ts = Task.GetOwnedTasks(base.getUser(), false); pane_tasks.Text = ui.Text("translation", "ownedTasks"); Panel2.Text = ui.Text("translation", "ownedTasks"); } else { ts = Task.GetTasks(base.getUser(), false); pane_tasks.Text = ui.Text("translation", "assignedTasks"); Panel2.Text = ui.Text("translation", "assignedTasks"); } uploadFile.Text = ui.Text("upload"); pane_uploadFile.Text = ui.Text("translation", "uploadTranslationXml"); foreach (Task t in ts) { if (t.Type.Alias == "toTranslate") { DataRow task = tasks.NewRow(); task["Id"] = t.Id; task["Date"] = t.Date; task["NodeId"] = t.Node.Id; task["NodeName"] = t.Node.Text; task["ReferingUser"] = t.ParentUser.Name; tasks.Rows.Add(task); } } taskList.DataSource = tasks; taskList.DataBind(); feedback.Style.Add("margin-top", "10px"); } protected void uploadFile_Click(object sender, EventArgs e) { // Save temp file if (translationFile.PostedFile != null) { string tempFileName; if (translationFile.PostedFile.FileName.ToLower().Contains(".zip")) tempFileName = IOHelper.MapPath(SystemDirectories.Data + "/" + "translationFile_" + Guid.NewGuid().ToString() + ".zip"); else tempFileName = IOHelper.MapPath(SystemDirectories.Data + "/" + "translationFile_" + Guid.NewGuid().ToString() + ".xml"); translationFile.PostedFile.SaveAs(tempFileName); // xml or zip file if (new FileInfo(tempFileName).Extension.ToLower() == ".zip") { // Zip Directory string tempPath = IOHelper.MapPath(SystemDirectories.Data + "/" + "translationFiles_" + Guid.NewGuid().ToString()); // Add the path to the zipfile to viewstate ViewState.Add("zipFile", tempPath); // Unpack the zip file cms.businesslogic.utilities.Zip.UnPack(tempFileName, tempPath, true); // Test the number of xml files try { StringBuilder sb = new StringBuilder(); foreach (FileInfo translationFileXml in new DirectoryInfo(ViewState["zipFile"].ToString()).GetFiles("*.xml")) { try { foreach (Task translation in ImportTranslatationFile(translationFileXml.FullName)) { sb.Append("<li>" + translation.Node.Text + " <a target=\"_blank\" href=\"preview.aspx?id=" + translation.Id + "\">" + ui.Text("preview") + "</a></li>"); } } catch (Exception ee) { sb.Append("<li style=\"color: red;\">" + ee.ToString() + "</li>"); } } feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.success; feedback.Text = "<h3>" + ui.Text("translation", "MultipleTranslationDone") + "</h3><p>" + ui.Text("translation", "translationDoneHelp") + "</p><ul>" + sb.ToString() + "</ul>"; } catch (Exception ex) { feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.error; feedback.Text = "<h3>" + ui.Text("translation", "translationFailed") + "</h3><p>" + ex.ToString() + "</>"; } } else { StringBuilder sb = new StringBuilder(); List<Task> l = ImportTranslatationFile(tempFileName); if (l.Count == 1) { feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.success; feedback.Text = "<h3>" + ui.Text("translation", "translationDone") + "</h3><p>" + ui.Text("translation", "translationDoneHelp") + "</p><p><a target=\"_blank\" href=\"preview.aspx?id=" + l[0].Id + "\">" + ui.Text("preview") + "</a></p>"; } else { foreach (Task t in l) { sb.Append("<li>" + t.Node.Text + " <a target=\"_blank\" href=\"preview.aspx?id=" + t.Id + "\">" + ui.Text("preview") + "</a></li>"); } feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.success; feedback.Text = "<h3>" + ui.Text("translation", "MultipleTranslationDone") + "</h3><p>" + ui.Text("translation", "translationDoneHelp") + "</p><ul>" + sb.ToString() + "</ul>"; } } // clean up File.Delete(tempFileName); } } private List<Task> ImportTranslatationFile(string tempFileName) { try { List<Task> tl = new List<Task>(); // open file XmlDocument tf = new XmlDocument(); tf.XmlResolver = null; tf.Load(tempFileName); // Get task xml node XmlNodeList tasks = tf.SelectNodes("//task"); foreach (XmlNode taskXml in tasks) { string xpath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : "* [@isDoc]"; XmlNode taskNode = taskXml.SelectSingleNode(xpath); // validate file Task t = new Task(int.Parse(taskXml.Attributes.GetNamedItem("Id").Value)); if (t != null) { //user auth and content node validation if (t.Node.Id == int.Parse(taskNode.Attributes.GetNamedItem("id").Value) && (t.User.Id == UmbracoUser.Id || t.ParentUser.Id == UmbracoUser.Id)) { // update node contents var d = new Document(t.Node.Id); Document.Import(d.ParentId, UmbracoUser, (XmlElement)taskNode); //send notifications! TODO: This should be put somewhere centralized instead of hard coded directly here ApplicationContext.Services.NotificationService.SendNotification(d.Content, ActionTranslate.Instance, ApplicationContext); t.Closed = true; t.Save(); tl.Add(t); } } } return tl; } catch (Exception ee) { throw new Exception("Error importing translation file '" + tempFileName + "': " + ee.ToString()); } } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; namespace Mono.Cecil { public sealed class ExportedType : IMetadataTokenProvider { string @namespace; string name; uint attributes; IMetadataScope scope; ModuleDefinition module; int identifier; ExportedType declaring_type; internal MetadataToken token; public string Namespace { get { return @namespace; } set { @namespace = value; } } public string Name { get { return name; } set { name = value; } } public TypeAttributes Attributes { get { return (TypeAttributes) attributes; } set { attributes = (uint) value; } } public IMetadataScope Scope { get { if (declaring_type != null) return declaring_type.Scope; return scope; } } public ExportedType DeclaringType { get { return declaring_type; } set { declaring_type = value; } } public MetadataToken MetadataToken { get { return token; } set { token = value; } } public int Identifier { get { return identifier; } set { identifier = value; } } #region TypeAttributes public bool IsNotPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic, value); } } public bool IsPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public, value); } } public bool IsNestedPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic, value); } } public bool IsNestedPrivate { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate, value); } } public bool IsNestedFamily { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily, value); } } public bool IsNestedAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly, value); } } public bool IsNestedFamilyAndAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem, value); } } public bool IsNestedFamilyOrAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem, value); } } public bool IsAutoLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout, value); } } public bool IsSequentialLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout, value); } } public bool IsExplicitLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout, value); } } public bool IsClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class, value); } } public bool IsInterface { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface, value); } } public bool IsAbstract { get { return attributes.GetAttributes ((uint) TypeAttributes.Abstract); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Abstract, value); } } public bool IsSealed { get { return attributes.GetAttributes ((uint) TypeAttributes.Sealed); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Sealed, value); } } public bool IsSpecialName { get { return attributes.GetAttributes ((uint) TypeAttributes.SpecialName); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.SpecialName, value); } } public bool IsImport { get { return attributes.GetAttributes ((uint) TypeAttributes.Import); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Import, value); } } public bool IsSerializable { get { return attributes.GetAttributes ((uint) TypeAttributes.Serializable); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Serializable, value); } } public bool IsAnsiClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass, value); } } public bool IsUnicodeClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass, value); } } public bool IsAutoClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass, value); } } public bool IsBeforeFieldInit { get { return attributes.GetAttributes ((uint) TypeAttributes.BeforeFieldInit); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.BeforeFieldInit, value); } } public bool IsRuntimeSpecialName { get { return attributes.GetAttributes ((uint) TypeAttributes.RTSpecialName); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.RTSpecialName, value); } } public bool HasSecurity { get { return attributes.GetAttributes ((uint) TypeAttributes.HasSecurity); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.HasSecurity, value); } } #endregion public bool IsForwarder { get { return attributes.GetAttributes ((uint) TypeAttributes.Forwarder); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Forwarder, value); } } public string FullName { get { var fullname = string.IsNullOrEmpty (@namespace) ? name : @namespace + '.' + name; if (declaring_type != null) return declaring_type.FullName + "/" + fullname; return fullname; } } public ExportedType (string @namespace, string name, ModuleDefinition module, IMetadataScope scope) { this.@namespace = @namespace; this.name = name; this.scope = scope; this.module = module; } public override string ToString () { return FullName; } public TypeDefinition Resolve () { return module.Resolve (CreateReference ()); } internal TypeReference CreateReference () { return new TypeReference (@namespace, name, module, scope) { DeclaringType = declaring_type != null ? declaring_type.CreateReference () : null, }; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Listener; using Microsoft.VisualStudio.Services.Agent.Listener.Configuration; using Xunit; using YamlDotNet.Core; using Yaml = Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Pipelines.Yaml; namespace Microsoft.VisualStudio.Services.Agent.Tests.Listener { public sealed class PipelineParserL0 { [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void TaskStep() { using (CreateTestContext()) { // Arrange. String expected = @" steps: - task: myTask@1 - task: myOtherTask@2 name: Fancy task enabled: false condition: always() continueOnError: true timeoutInMinutes: 123 inputs: myInput: input value env: MY_VAR: val "; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "taskStep.yml")] = expected; // Act. String actual = m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "taskStep.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.Equal(expected.Trim(), actual.Trim()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void ScriptStep() { using (CreateTestContext()) { // Arrange. String expected = @" steps: - script: echo hello from script 1 - script: echo hello from script 2 name: Fancy script enabled: false condition: always() continueOnError: true timeoutInMinutes: 123 failOnStderr: $(failOnStderrVariable) workingDirectory: $(workingDirectoryVariable) env: MY_VAR: value "; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "scriptStep.yml")] = expected; // Act. String actual = m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "scriptStep.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.Equal(expected.Trim(), actual.Trim()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void BashStep() { using (CreateTestContext()) { // Arrange. String expected = @" steps: - bash: echo hello from bash - bash: echo hello again from bash name: Fancy script enabled: false condition: always() continueOnError: true timeoutInMinutes: 123 failOnStderr: $(failOnStderrVariable) workingDirectory: $(workingDirectoryVariable) env: MY_VAR: value "; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "bashStep.yml")] = expected; // Act. String actual = m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "bashStep.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.Equal(expected.Trim(), actual.Trim()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void PowerShellStep() { using (CreateTestContext()) { // Arrange. String expected = @" steps: - powershell: write-host 'hello from powershell' - powershell: write-host 'hello again from powershell' name: Fancy script enabled: false condition: always() continueOnError: true timeoutInMinutes: 123 errorActionPreference: $(errorActionPreferenceVariable) failOnStderr: $(failOnStderrVariable) ignoreLASTEXITCODE: $(ignoreLASTEXITCODEVariable) workingDirectory: $(workingDirectoryVariable) env: MY_VAR: value "; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "powershellStep.yml")] = expected; // Act. String actual = m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "powershellStep.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.Equal(expected.Trim(), actual.Trim()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void CheckoutStep() { using (CreateTestContext()) { // Arrange. String expected = @" phases: - name: phase1 steps: - checkout: none - name: phase2 steps: - checkout: self - name: phase3 steps: - checkout: self clean: $(cleanVariable) fetchDepth: $(fetchDepthVariable) lfs: $(fetchDepthVariable) "; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "checkoutStep.yml")] = expected; // Act. String actual = m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "checkoutStep.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.Equal(expected.Trim(), actual.Trim()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void CheckoutStep_RepoDefined() { using (CreateTestContext()) { // Arrange. String expected = @" resources: - repo: self clean: true phases: - name: phase1 steps: - checkout: none - name: phase2 steps: - checkout: self - name: phase3 steps: - checkout: self clean: $(cleanVariable) fetchDepth: $(fetchDepthVariable) lfs: $(fetchDepthVariable) "; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "checkoutStep_repoDefined.yml")] = expected; // Act. String actual = m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "checkoutStep_repoDefined.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.Equal(expected.Trim(), actual.Trim()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void Phase() { using (CreateTestContext()) { // Arrange. String expected = @" phases: - name: phase1 steps: - script: echo hello - name: phase2 dependsOn: phase1 condition: always() continueOnError: $(continueOnErrorVariable) enableAccessToken: $(enableAccessTokenVariable) queue: myQueue variables: var1: val1 steps: - script: echo hello - name: phase3 dependsOn: - phase1 - phase2 queue: demands: a -eq b steps: - script: echo hello "; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "phase.yml")] = expected; // Act. String actual = m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "phase.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.Equal(expected.Trim(), actual.Trim()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void PhaseDeploymentTarget() { using (CreateTestContext()) { // Arrange. String expected = @" phases: - name: deployPhase1 deployment: myDeploymentGroup steps: - script: echo hello - name: deployPhase2 deployment: group: myDeploymentGroup tags: myTag steps: - script: echo hello - name: deployPhase3 deployment: group: myDeploymentGroup continueOnError: $(continueOnErrorVariable) healthOption: percentage percentage: 50 timeoutInMinutes: $(timeoutInMinutesVariable) tags: - myTag1 - myTag2 steps: - script: echo hello "; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "phaseDeploymentTarget.yml")] = expected; // Act. String actual = m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "phaseDeploymentTarget.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.Equal(expected.Trim(), actual.Trim()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void PhaseQueueTarget() { using (CreateTestContext()) { // Arrange. String expected = @" phases: - name: buildPhase1 steps: - script: echo hello - name: buildPhase2 queue: myQueue steps: - script: echo hello - name: buildPhase3 queue: demands: a -eq b steps: - script: echo hello - name: buildPhase4 queue: name: myQueue continueOnError: $(continueOnErrorVariable) parallel: $(parallelVariable) timeoutInMinutes: $(timeoutInMinutesVariable) demands: - a -eq b - c -eq d matrix: x64_release: arch: x64 config: release x86_debug: arch: x86 config: debug steps: - script: echo hello "; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "phaseQueueTarget.yml")] = expected; // Act. String actual = m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "phaseQueueTarget.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.Equal(expected.Trim(), actual.Trim()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void PhaseServerTarget() { using (CreateTestContext()) { // Arrange. String expected = @" phases: - name: serverPhase1 server: true steps: - task: myServerTask@1 - name: serverPhase2 server: timeoutInMinutes: $(timeoutInMinutesVariable) steps: - task: myServerTask@1 - name: serverPhase3 server: continueOnError: $(continueOnErrorVariable) parallel: $(parallelVariable) timeoutInMinutes: $(timeoutInMinutesVariable) matrix: x64_release: arch: x64 config: release x86_debug: arch: x86 config: debug steps: - task: myServerTask@1 "; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "phaseServerTarget.yml")] = expected; // Act. String actual = m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "phaseServerTarget.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.Equal(expected.Trim(), actual.Trim()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void PhaseVariables_Simple() { using (CreateTestContext()) { // Arrange. String expected = @" variables: var1: val1 steps: - script: echo hello "; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "phaseVariables_simple.yml")] = expected; // Act. String actual = m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "phaseVariables_simple.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.Equal(expected.Trim(), actual.Trim()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void PhaseVariables_NameValue() { using (CreateTestContext()) { // Arrange. String content = @" variables: - name: var1 value: val1 steps: - script: echo hello "; String expected = @" variables: var1: val1 steps: - script: echo hello "; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "phaseVariables_nameValue.yml")] = content; // Act. String actual = m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "phaseVariables_nameValue.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.Equal(expected.Trim(), actual.Trim()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void MaxObjectDepth_Mapping() { using (CreateTestContext()) { // Arrange - sanity test allowed threshold String contentFormat = @" resources: - endpoint: someEndpoint myProperty: {0}"; String allowedObject = "{a: {a: {a: {a: {a: {a: {a: {a: {a: {a: \"b\"} } } } } } } } } }"; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "maxObjectDepth_mapping_allowed.yml")] = String.Format(CultureInfo.InvariantCulture, contentFormat, allowedObject); m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "maxObjectDepth_mapping_allowed.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Arrange - setup exceeding threshold String unallowedObject = "{a: " + allowedObject + " }"; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "maxObjectDepth_mapping_unallowed.yml")] = String.Format(CultureInfo.InvariantCulture, contentFormat, unallowedObject); try { // Act. m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "maxObjectDepth_mapping_unallowed.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.True(false, "Should have thrown syntax error exception"); } catch (SyntaxErrorException ex) { // Assert. Assert.Contains("Max object depth of 10 exceeded", ex.Message); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void MaxObjectDepth_Sequence() { using (CreateTestContext()) { // Arrange - sanity test allowed threshold String contentFormat = @" resources: - endpoint: someEndpoint myProperty: {0}"; String allowedObject = "[ [ [ [ [ [ [ [ [ [ \"a\" ] ] ] ] ] ] ] ] ] ]"; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "maxObjectDepth_sequence_allowed.yml")] = String.Format(CultureInfo.InvariantCulture, contentFormat, allowedObject); m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "maxObjectDepth_sequence_allowed.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Arrange - setup exceeding threshold String unallowedObject = "[ " + allowedObject + " ]"; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "maxObjectDepth_sequence_unallowed.yml")] = String.Format(CultureInfo.InvariantCulture, contentFormat, unallowedObject); try { // Act. m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "maxObjectDepth_sequence_unallowed.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.True(false, "Should have thrown syntax error exception"); } catch (SyntaxErrorException ex) { // Assert. Assert.Contains("Max object depth of 10 exceeded", ex.Message); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void MaxObjectDepth_Mixed() { using (CreateTestContext()) { // Arrange - sanity test allowed threshold String contentFormat = @" resources: - endpoint: someEndpoint myProperty: {0}"; String allowedObject = "{a: [ {a: [ {a: [ {a: [ {a: [ \"a\" ] } ] } ] } ] } ] }"; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "maxObjectDepth_mixed_allowed.yml")] = String.Format(CultureInfo.InvariantCulture, contentFormat, allowedObject); m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "maxObjectDepth_mixed_allowed.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Arrange - setup exceeding threshold String unallowedObject = "[ " + allowedObject + " ]"; m_fileProvider.FileContent[Path.Combine(c_defaultRoot, "maxObjectDepth_mixed_unallowed.yml")] = String.Format(CultureInfo.InvariantCulture, contentFormat, unallowedObject); try { // Act. m_pipelineParser.DeserializeAndSerialize( c_defaultRoot, "maxObjectDepth_mixed_unallowed.yml", mustacheContext: null, cancellationToken: CancellationToken.None); // Assert. Assert.True(false, "Should have thrown syntax error exception"); } catch (SyntaxErrorException ex) { // Assert. Assert.Contains("Max object depth of 10 exceeded", ex.Message); } } } private TestHostContext CreateTestContext([CallerMemberName] string testName = "") { TestHostContext hc = new TestHostContext(this, testName); m_fileProvider = new YamlFileProvider(); m_pipelineParser = new Yaml.PipelineParser( new YamlTraceWriter(hc), m_fileProvider, new Yaml.ParseOptions() { MaxFiles = 10, MustacheEvaluationMaxResultLength = 512 * 1024, // 512k string length MustacheEvaluationTimeout = TimeSpan.FromSeconds(10), MustacheMaxDepth = 5, }); Yaml.ITraceWriter traceWriter = new YamlTraceWriter(hc); return hc; } private sealed class YamlFileProvider : Yaml.IFileProvider { public Dictionary<String, String> FileContent => m_fileContent; public Yaml.FileData GetFile(String path) { return new Yaml.FileData { Name = Path.GetFileName(path), Directory = Path.GetDirectoryName(path), Content = m_fileContent[path], }; } public String ResolvePath(String defaultRoot, String path) { return Path.Combine(defaultRoot, path); } private readonly Dictionary<String, String> m_fileContent = new Dictionary<String, String>(); } private sealed class YamlTraceWriter : Yaml.ITraceWriter { public YamlTraceWriter(TestHostContext hostContext) { m_trace = hostContext.GetTrace(nameof(YamlTraceWriter)); } public void Info(String format, params Object[] args) { m_trace.Info(format, args); } public void Verbose(String format, params Object[] args) { m_trace.Verbose(format, args); } private readonly Tracing m_trace; } private const String c_defaultRoot = @"C:\TestYamlFiles"; private Yaml.PipelineParser m_pipelineParser; private YamlFileProvider m_fileProvider; } }
using System; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; using Hydra.Framework; namespace Hydra.SharedCache.Common.Provider.Cache { // // ********************************************************************** /// <summary> /// Implementing a provider for LBSView Shared Cache based on /// Microsofts Provider model. /// </summary> // ********************************************************************** // public class LBSSharedCacheProvider : LBSProviderBase { // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="LBSSharedCacheProvider"/> class. /// </summary> // ********************************************************************** // public LBSSharedCacheProvider() { CacheUtil.SetContext(true); } #region Member Variables // // ********************************************************************** /// <summary> /// For multi get no specific key is required so /// use a constant to represent the key value. /// </summary> // ********************************************************************** // private const string MultiGetKey = "MG"; private const string MultiAddKey = "MA"; private const string MultiDelKey = "MD"; private const string RegexRemoveKey = "RRK"; private const string RegexGetItems = "RGI"; private const string VersionClr = "CLR"; private const string VersionSharedCache = "VSC"; private const string AbsoluteTimeExpiration = "ATE"; // // ********************************************************************** /// <summary> /// a list which represents only configured server node ip addresses. /// </summary> // ********************************************************************** // private static List<string> serverIp; private static List<string> replicatedServerIp; private static List<Configuration.Client.LBSServerSetting> replicatedServerList; // // ********************************************************************** /// <summary> /// A list of all available server <see cref="Configuration.Client.LBSServerSetting"/> configured nodes /// with the provided key. /// </summary> // ********************************************************************** // private static List<Configuration.Client.LBSServerSetting> serverList; #endregion #region Properties // // ********************************************************************** /// <summary> /// Retrieve amount of configured server nodes. /// </summary> /// <value>The count.</value> // ********************************************************************** // public override long Count { [System.Diagnostics.DebuggerStepThrough] get { if (this.Servers != null && this.Servers.Length > 0) return (long)this.Servers.Length; else return 0; } } // // ********************************************************************** /// <summary> /// Retrieve configured server nodes as an array of <see cref="string"/> /// </summary> /// <value>The servers.</value> // ********************************************************************** // public override string[] Servers { [System.Diagnostics.DebuggerStepThrough] get { if (serverIp == null) { serverIp = new List<string>(); foreach (Configuration.Client.LBSServerSetting server in LBSDistributionCache.ProviderSection.Servers) { serverIp.Add(server.IpAddress); } } return serverIp.ToArray(); } } // // ********************************************************************** /// <summary> /// Retrieve configured server nodes configuration as a <see cref="List"/>. This /// is provides the Key and IPAddress of each item in the configuration section. /// </summary> /// <value>The servers list.</value> // ********************************************************************** // public override List<Configuration.Client.LBSServerSetting> ServersList { get { if (serverList == null) { serverList = new List<Configuration.Client.LBSServerSetting>(); foreach (Configuration.Client.LBSServerSetting server in LBSDistributionCache.ProviderSection.Servers) { serverList.Add(server); } } return serverList; } } // // ********************************************************************** /// <summary> /// Retrieve replication server nodes configuration as an array of <see cref="string"/>. This /// is provides the Key and IPAddress of each item in the configuration section. /// </summary> /// <value> /// An array of <see cref="string"/> with all configured replicated servers. /// </value> // ********************************************************************** // public override string[] ReplicatedServers { get { if (replicatedServerIp == null) { replicatedServerIp = new List<string>(); foreach (Configuration.Client.LBSServerSetting server in LBSDistributionCache.ProviderSection.ReplicatedServers) { replicatedServerIp.Add(server.IpAddress); } } return replicatedServerIp.ToArray(); } } // // ********************************************************************** /// <summary> /// Retrieve replication server nodes configuration as a <see cref="List"/>. This /// is provides the Key and IPAddress of each item in the configuration section. /// </summary> /// <value> /// A List of <see cref="string"/> with all configured replicated servers. /// </value> // ********************************************************************** // public override List<Configuration.Client.LBSServerSetting> ReplicatedServersList { get { if (replicatedServerList == null) { replicatedServerList = new List<Configuration.Client.LBSServerSetting>(); foreach (Configuration.Client.LBSServerSetting server in LBSDistributionCache.ProviderSection.ReplicatedServers) { replicatedServerList.Add(server); } } return replicatedServerList; } } private static Enums.HashingAlgorithm hashing = Enums.HashingAlgorithm.Hashing; // // ********************************************************************** /// <summary> /// Gets the Hashing /// </summary> /// <value>The hashing.</value> // ********************************************************************** // public static Enums.HashingAlgorithm Hashing { [System.Diagnostics.DebuggerStepThrough] get { try { hashing = Provider.Cache.LBSDistributionCache.ProviderSection.ClientSetting.HashingAlgorithm; } catch (Exception ex) { Console.WriteLine(string.Format(@"Could not read configuration for Hashing , recheck your app.config / web.config")); Log.Exception(ex); } return hashing; } } #endregion // // ********************************************************************** /// <summary> /// Adding an item to cache with all possibility options. All overloads are using this /// method to add items based on various provided variables. e.g. expire date time, /// item priority or to a specific host /// </summary> /// <param name="key">The key for cache item</param> /// <param name="payload">The payload which is the object itself.</param> /// <param name="expires">Identify when item will expire from the cache.</param> /// <param name="action">The action is always Add item to cache. See also <see cref="LBSMessage.ActionValue"/> options.</param> /// <param name="prio">Item priority - See also <see cref="LBSMessage.CacheItemPriority"/></param> /// <param name="status">The status of the request. See also <see cref="LBSMessage.StatusValue"/></param> /// <param name="host">The host, represents the specific server node.</param> // ********************************************************************** // internal override void Add(string key, byte[] payload, DateTime expires, ActionType action, CacheItemPriorityType prio, StatusType status, string host) { if (string.IsNullOrEmpty(host)) throw new ArgumentException("host parameter must be defined - simply use GetServerForKey(key)", host); using (LBSMessage msg = new LBSMessage()) { msg.Key = key; msg.Payload = payload; msg.Expires = expires; msg.Action = action; msg.ItemPriority = prio; msg.Status = status; msg.Hostname = host; CacheUtil.Add(msg); } } // // ********************************************************************** /// <summary> /// Adding an item to cache. Items are added with Normal priority and /// DateTime.MaxValue. Items are only get cleared from cache in case /// max. cache factor arrived or the cache get refreshed. /// </summary> /// <param name="key">The key for cache item</param> /// <param name="payload">The payload which is the object itself.</param> // ********************************************************************** // public override void Add(string key, object payload) { byte[] array = Formatters.Serialization.BinarySerialize(payload); this.Add(key, array); } // // ********************************************************************** /// <summary> /// Adding an item to cache. Items are added with Normal priority and /// DateTime.MaxValue. Items are only get cleared from cache in case /// max. cache factor arrived or the cache get refreshed. /// </summary> /// <param name="key">The key for cache item</param> /// <param name="payload">The payload which is the object itself.</param> // ********************************************************************** // public override void Add(string key, byte[] payload) { this.Add(key, payload, DateTime.MaxValue, ActionType.Add, CacheItemPriorityType.Normal, StatusType.Request, this.GetServerForKey(key)); } // // ********************************************************************** /// <summary> /// Adding an item to cache. Items are added with Normal priority and /// provided <see cref="DateTime"/>. Items get cleared from cache in case /// max. cache factor arrived, cache get refreshed or provided <see cref="DateTime"/> /// reached provided <see cref="DateTime"/>. The server takes care of items /// with provided <see cref="DateTime"/>. /// </summary> /// <param name="key">The key for cache item</param> /// <param name="payload">The payload which is the object itself.</param> /// <param name="expires">Identify when item will expire from the cache.</param> // ********************************************************************** // public override void Add(string key, object payload, DateTime expires) { byte[] array = Formatters.Serialization.BinarySerialize(payload); this.Add(key, array, expires); } // // ********************************************************************** /// <summary> /// Adding an item to cache. Items are added with Normal priority and /// provided <see cref="DateTime"/>. Items get cleared from cache in case /// max. cache factor arrived, cache get refreshed or provided <see cref="DateTime"/> /// reached provided <see cref="DateTime"/>. The server takes care of items /// with provided <see cref="DateTime"/>. /// </summary> /// <param name="key">The key for cache item</param> /// <param name="payload">The payload which is the object itself.</param> /// <param name="expires">Identify when item will expire from the cache.</param> // ********************************************************************** // public override void Add(string key, byte[] payload, DateTime expires) { this.Add(key, payload, expires, ActionType.Add, CacheItemPriorityType.Normal, StatusType.Request, this.GetServerForKey(key)); } // // ********************************************************************** /// <summary> /// Adding an item to cache. Items are added with provided priority <see cref="LBSMessage.CacheItemPriority"/> and /// DateTime.MaxValue. Items are only get cleared from cache in case max. cache factor arrived or the cache get refreshed. /// </summary> /// <param name="key">The key for cache item</param> /// <param name="payload">The payload which is the object itself.</param> /// <param name="prio">Item priority - See also <see cref="LBSMessage.CacheItemPriority"/></param> // ********************************************************************** // public override void Add(string key, object payload, CacheItemPriorityType prio) { byte[] array = Formatters.Serialization.BinarySerialize(payload); this.Add(key, array, prio); } // // ********************************************************************** /// <summary> /// Adding an item to cache. Items are added with provided priority <see cref="LBSMessage.CacheItemPriority"/> and /// DateTime.MaxValue. Items are only get cleared from cache in case max. cache factor arrived or the cache get refreshed. /// </summary> /// <param name="key">The key for cache item</param> /// <param name="payload">The payload which is the object itself.</param> /// <param name="prio">Item priority - See also <see cref="LBSMessage.CacheItemPriority"/></param> // ********************************************************************** // public override void Add(string key, byte[] payload, CacheItemPriorityType prio) { this.Add(key, payload, DateTime.MaxValue, ActionType.Add, prio, StatusType.Request, this.GetServerForKey(key)); } // // ********************************************************************** /// <summary> /// Adding an item to specific cache node. It let user to control on which server node the item will be placed. /// Items are added with normal priority <see cref="LBSMessage.CacheItemPriority"/> and /// DateTime.MaxValue <see cref="DateTime"/>. Items are only get cleared from cache in case max. cache factor /// arrived or the cache get refreshed. /// </summary> /// <param name="key">The key for cache item</param> /// <param name="payload">The payload which is the object itself.</param> /// <param name="host">The host represents the ip address of a server node.</param> // ********************************************************************** // public override void Add(string key, object payload, string host) { byte[] array = Formatters.Serialization.BinarySerialize(payload); this.Add(key, array, host); } // // ********************************************************************** /// <summary> /// Adding an item to specific cache node. It let user to control on which server node the item will be placed. /// Items are added with normal priority <see cref="LBSMessage.CacheItemPriority"/> and /// DateTime.MaxValue <see cref="DateTime"/>. Items are only get cleared from cache in case max. cache factor /// arrived or the cache get refreshed. /// </summary> /// <param name="key">The key for cache item</param> /// <param name="payload">The payload which is the object itself.</param> /// <param name="host">The host represents the ip address of a server node.</param> // ********************************************************************** // public override void Add(string key, byte[] payload, string host) { this.Add(key, payload, DateTime.MaxValue, ActionType.Add, CacheItemPriorityType.Normal, StatusType.Request, host); } // // ********************************************************************** /// <summary> /// Adding an item to cache. Items are added with provided priority <see cref="LBSMessage.CacheItemPriority"/> and /// provided <see cref="DateTime"/>. Items get cleared from cache in case /// max. cache factor arrived, cache get refreshed or provided <see cref="DateTime"/> /// reached provided <see cref="DateTime"/>. The server takes care of items with provided <see cref="DateTime"/>. /// </summary> /// <param name="key">The key for cache item</param> /// <param name="payload">The payload which is the object itself.</param> /// <param name="expires">Identify when item will expire from the cache.</param> /// <param name="prio">Item priority - See also <see cref="LBSMessage.CacheItemPriority"/></param> // ********************************************************************** // public override void Add(string key, object payload, DateTime expires, CacheItemPriorityType prio) { byte[] array = Formatters.Serialization.BinarySerialize(payload); this.Add(key, array, expires, prio); } // // ********************************************************************** /// <summary> /// Adding an item to cache. Items are added with provided priority <see cref="LBSMessage.CacheItemPriority"/> and /// provided <see cref="DateTime"/>. Items get cleared from cache in case /// max. cache factor arrived, cache get refreshed or provided <see cref="DateTime"/> /// reached provided <see cref="DateTime"/>. The server takes care of items with provided <see cref="DateTime"/>. /// </summary> /// <param name="key">The key for cache item</param> /// <param name="payload">The payload which is the object itself.</param> /// <param name="expires">Identify when item will expire from the cache.</param> /// <param name="prio">Item priority - See also <see cref="LBSMessage.CacheItemPriority"/></param> // ********************************************************************** // public override void Add(string key, byte[] payload, DateTime expires, CacheItemPriorityType prio) { this.Add(key, payload, expires, ActionType.Add, prio, StatusType.Request, this.GetServerForKey(key)); } // // ********************************************************************** /// <summary> /// This Method extends item time to live. /// </summary> /// <param name="key">The key for cache item</param> /// <param name="expires">Identify when item will expire from the cache.</param> // ********************************************************************** // public override void ExtendTtl(string key, DateTime expires) { this.Add(key, null, expires, ActionType.ExtendTtl, CacheItemPriorityType.None, StatusType.Request, this.GetServerForKey(key)); } // // ********************************************************************** /// <summary> /// Return Servers CLR (Common Language Runtime), this is needed to decide which /// Hashing codes can be used. /// </summary> /// <returns> /// CLR (Common Language Runtime) version number as <see cref="string"/> e.g. xxxx.xxxx.xxxx.xxxx /// </returns> // ********************************************************************** // public override IDictionary<string, string> ServerNodeVersionClr() { IDictionary<string, string> result = new Dictionary<string, string>(); foreach (string item in this.Servers) { using (LBSMessage msg = new LBSMessage()) { msg.Hostname = item; msg.Key = VersionClr; msg.Status = StatusType.Request; msg.Action = ActionType.VersionNumberClr; msg.Payload = null; if (CacheUtil.Get(msg) && msg.Payload != null) { string clrVersionNumber = Formatters.Serialization.BinaryDeSerialize<string>(msg.Payload); if (!string.IsNullOrEmpty(clrVersionNumber)) { result.Add(item, clrVersionNumber); } else { // // TODO: LOG missing data from server node!!! // } } } } return result; } // // ********************************************************************** /// <summary> /// Returns current build version of Shared Cache /// </summary> /// <returns> /// Shared Cache version number as <see cref="string"/> e.g. xxxx.xxxx.xxxx.xxxx /// </returns> // ********************************************************************** // public override IDictionary<string, string> ServerNodeVersionSharedCache() { IDictionary<string, string> result = new Dictionary<string, string>(); foreach (string item in this.Servers) { using (LBSMessage msg = new LBSMessage()) { msg.Hostname = item; msg.Key = VersionSharedCache; msg.Status = StatusType.Request; msg.Action = ActionType.VersionNumberSharedCache; msg.Payload = null; if (CacheUtil.Get(msg) && msg.Payload != null) { string clrVersionNumber = Formatters.Serialization.BinaryDeSerialize<string>(msg.Payload); if (!string.IsNullOrEmpty(clrVersionNumber)) { result.Add(item, clrVersionNumber); } else { // // TODO: LOG missing data from server node!!! // } } } } return result; } public override IDictionary<string, DateTime> GetAbsoluteTimeExpiration(List<string> keys) { // // for each server node we split up the keys // Dictionary<string, List<string>> splitter = new Dictionary<string, List<string>>(); Dictionary<string, DateTime> result = new Dictionary<string, DateTime>(); foreach (string server in this.Servers) { splitter.Add(server, new List<string>()); } foreach (string k in keys) { splitter[this.GetServerForKey(k)].Add(k); } foreach (string server in splitter.Keys) { // // evaluate only to send messages to servers // which really have items - prevent roundtrips // if (splitter[server].Count > 0) { using (LBSMessage msg = new LBSMessage()) { msg.Hostname = server; msg.Key = AbsoluteTimeExpiration; msg.Action = ActionType.GetAbsoluteTimeExpiration; msg.Payload = Formatters.Serialization.BinarySerialize(splitter[server]); if (CacheUtil.Get(msg) && msg.Payload != null) { IDictionary<string, DateTime> partialResult = Formatters.Serialization.BinaryDeSerialize<IDictionary<string, DateTime>>(msg.Payload); foreach (KeyValuePair<string, DateTime> item in partialResult) { result.Add(item.Key, item.Value); } } } } } return result; } // // ********************************************************************** /// <summary> /// Retrieve specific item from cache based on provided key. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key for cache item</param> /// <returns>Returns received item as casted object T</returns> // ********************************************************************** // public override T Get<T>(string key) { using (LBSMessage msg = new LBSMessage()) { msg.Hostname = this.GetServerForKey(key); msg.Key = key; msg.Action = ActionType.Get; if (CacheUtil.Get(msg) && msg.Payload != null) { return Formatters.Serialization.BinaryDeSerialize<T>(msg.Payload); } else { return default(T); } } } // // ********************************************************************** /// <summary> /// Retrieve specific item from cache based on provided key. /// </summary> /// <param name="key">The key for cache item</param> /// <returns> /// Returns received item as casted <see cref="object"/> /// </returns> // ********************************************************************** // public override object Get(string key) { return this.Get<object>(key); } // // ********************************************************************** /// <summary> /// Based on a list of key's the client receives a dictonary with /// all available data depending on the keys. /// </summary> /// <param name="keys">A List of <see cref="string"/> with all requested keys.</param> /// <returns> /// A <see cref="IDictionary"/> with <see cref="string"/> and <see cref="byte"/> array element. /// </returns> // ********************************************************************** // public override IDictionary<string, byte[]> MultiGet(List<string> keys) { // // for each server node we split up the keys // Dictionary<string, List<string>> splitter = new Dictionary<string, List<string>>(); Dictionary<string, byte[]> result = new Dictionary<string, byte[]>(); foreach (string server in this.Servers) { splitter.Add(server, new List<string>()); } foreach (string k in keys) { splitter[this.GetServerForKey(k)].Add(k); } foreach (string server in splitter.Keys) { // // evaluate only to send messages to servers // which really have items. // if (splitter[server].Count > 0) { using (LBSMessage msg = new LBSMessage()) { msg.Hostname = server; msg.Key = MultiGetKey; msg.Action = ActionType.MultiGet; msg.Payload = Formatters.Serialization.BinarySerialize(splitter[server]); if (CacheUtil.Get(msg) && msg.Payload != null) { IDictionary<string, byte[]> partialResult = Formatters.Serialization.BinaryDeSerialize<IDictionary<string, byte[]>>(msg.Payload); foreach (KeyValuePair<string, byte[]> item in partialResult) { result.Add(item.Key, item.Value); } } } } } return result; } // // ********************************************************************** /// <summary> /// Adding a bunch of data to the cache, prevents to make several calls /// from the client to the server. All data is tranported with /// a <see cref="Dictonary"/> with a <see cref="string"/> and <see cref="byte"/> /// array combination. /// </summary> /// <param name="data">The data to add as a <see cref="IDictionary"/></param> // ********************************************************************** // public override void MultiAdd(IDictionary<string, byte[]> data) { Dictionary<string, IDictionary<string, byte[]>> splitter = new Dictionary<string, IDictionary<string, byte[]>>(); foreach (string server in this.Servers) { splitter.Add(server, new Dictionary<string, byte[]>()); } foreach (string k in data.Keys) { splitter[this.GetServerForKey(k)].Add(k, data[k]); } foreach (string server in splitter.Keys) { if (splitter[server].Count > 0) { using (LBSMessage msg = new LBSMessage()) { msg.Action = ActionType.MultiAdd; msg.Hostname = server; msg.Key = MultiAddKey; msg.Payload = Formatters.Serialization.BinarySerialize(splitter[server]); if (CacheUtil.Add(msg)) { return; } else { // // write something to log ?? // } } } } } // // ********************************************************************** /// <summary> /// Delete a bunch of data from the cache. This prevents several calls from /// the client to the server. Only one single call is done with all relevant /// key's for the server node. /// </summary> /// <param name="keys">A List of <see cref="string"/> with all requested keys to delete</param> // ********************************************************************** // public override void MultiDelete(List<string> keys) { Dictionary<string, bool> nodeResult = new Dictionary<string, bool>(); Dictionary<string, List<string>> splitter = new Dictionary<string, List<string>>(); Dictionary<string, byte[]> result = new Dictionary<string, byte[]>(); foreach (string server in this.Servers) { splitter.Add(server, new List<string>()); } foreach (string k in keys) { splitter[this.GetServerForKey(k)].Add(k); } foreach (string server in splitter.Keys) { if (splitter[server].Count > 0) { using (LBSMessage msg = new LBSMessage()) { msg.Action = ActionType.MultiDelete; msg.Hostname = server; msg.Key = MultiDelKey; msg.Payload = Formatters.Serialization.BinarySerialize(splitter[server]); bool tmpResult = CacheUtil.Remove(msg); nodeResult.Add(msg.Hostname, tmpResult); } } } foreach (KeyValuePair<string, bool> res in nodeResult) { if (!res.Value) { Log.Error(string.Format("MultiDelete could not be executed successfully at node: {0}", res.Key.ToString())); } } } // // ********************************************************************** /// <summary> /// Remove cache item with provided key. /// </summary> /// <param name="key">The key for cache item</param> // ********************************************************************** // public override void Remove(string key) { using (LBSMessage msg = new LBSMessage()) { msg.Hostname = this.GetServerForKey(key); msg.Key = key; msg.Action = ActionType.Remove; CacheUtil.Remove(msg); } } // // ********************************************************************** /// <summary> /// Remove Cache Items on server node based on regular expression. Each item which matches /// will be automatically removed from each server. /// </summary> /// <param name="regularExpression">The regular expression.</param> /// <returns></returns> // ********************************************************************** // public override bool RegexRemove(string regularExpression) { Dictionary<string, bool> result = new Dictionary<string, bool>(); bool overallResult = true; foreach (Configuration.Client.LBSServerSetting setting in this.ServersList) { using (LBSMessage msg = new LBSMessage()) { msg.Hostname = setting.IpAddress; msg.Key = RegexRemoveKey; msg.Action = ActionType.RegexRemove; msg.Payload = Encoding.UTF8.GetBytes(regularExpression); bool nodeResult = CacheUtil.Remove(msg); result.Add(msg.Hostname, nodeResult); } } foreach (KeyValuePair<string, bool> res in result) { if (!res.Value) { overallResult = false; Log.Error(string.Format("RegexRemove could not be executed successfully at node: {0}", res.Key.ToString())); } } return overallResult; } // // ********************************************************************** /// <summary> /// Returns items from cache node based on provided pattern. /// </summary> /// <param name="regularExpression">The regular expression.</param> /// <returns> /// An IDictionary with <see cref="string"/> and <see cref="byte"/> array with all founded elementes /// </returns> // ********************************************************************** // public override IDictionary<string, byte[]> RegexGet(string regularExpression) { IDictionary<string, byte[]> result = new Dictionary<string, byte[]>(); foreach (Configuration.Client.LBSServerSetting setting in this.ServersList) { using (LBSMessage msg = new LBSMessage()) { msg.Hostname = setting.IpAddress; msg.Key = RegexGetItems; msg.Action = ActionType.RegexGet; msg.Payload = Encoding.UTF8.GetBytes(regularExpression); if (CacheUtil.Get(msg)) { if (msg.Status == StatusType.Request) { // // no server roundtrip happend // return result; } IDictionary<string, byte[]> nodeResult = Formatters.Serialization.BinaryDeSerialize<IDictionary<string, byte[]>>(msg.Payload); if (nodeResult != null) { foreach (KeyValuePair<string, byte[]> item in nodeResult) { result.Add(item); } } } } } return result; } // // ********************************************************************** /// <summary> /// Pings the specified host. /// </summary> /// <param name="host">The host.</param> /// <returns> /// if the server is available then it returns true otherwise false. /// </returns> // ********************************************************************** // public override bool Ping(string host) { return CacheUtil.Ping(host); } // // ********************************************************************** /// <summary> /// Force each configured cache server node to clear the cache. /// </summary> // ********************************************************************** // public override void Clear() { foreach (Configuration.Client.LBSServerSetting setting in this.ServersList) { CacheUtil.Clear(setting.IpAddress); } } // // ********************************************************************** /// <summary> /// Retrieve a list with all key which are available on all cofnigured server nodes. /// </summary> /// <param name="host">The host represents the ip address of a server node.</param> /// <returns> /// A List of <see cref="string"/> with all available keys. /// </returns> // ********************************************************************** // public override List<string> GetAllKeys(string host) { return CacheUtil.GetAllKeys(host); } // // ********************************************************************** /// <summary> /// Retrieve a list with all key which are available on cache. /// </summary> /// <returns> /// A List of <see cref="string"/> with all available keys. /// </returns> // ********************************************************************** // public override List<string> GetAllKeys() { List<string> result = new List<string>(); foreach (Configuration.Client.LBSServerSetting setting in this.ServersList) { result.AddRange(this.GetAllKeys(setting.IpAddress)); } return result; } // // ********************************************************************** /// <summary> /// Retrieve statistic information <see cref="LBSStatistic"/> from specific /// server based on provided host. /// </summary> /// <param name="host">The host represents the ip address of a server node.</param> /// <returns> /// an <see cref="LBSStatistic"/> object /// </returns> // ********************************************************************** // public override LBSStatistic GetStats(string host) { LBSStatistic result = new LBSStatistic(); // // retrieve for specific host all data // LBSStatistic remoteStat = CacheUtil.Statistic(host); // // read the local data, need to read them upon the last item, otherwise the amount // of stats would be missing the server calls. // result.apiCounterAdd = remoteStat.apiCounterAdd; result.apiCounterFailed = remoteStat.apiCounterFailed; result.apiCounterGet = remoteStat.apiCounterGet; result.apiCounterRemove = remoteStat.apiCounterRemove; result.apiCounterSuccess = remoteStat.apiCounterSuccess; result.apiCounterStatistic = remoteStat.apiCounterStatistic; result.apiHitSuccess = remoteStat.apiHitSuccess; result.apiHitFailed = remoteStat.apiHitFailed; // // creating a node stat object // ServerStats nodeStat = new ServerStats(host, remoteStat.ServiceAmountOfObjects, remoteStat.ServiceTotalSize, remoteStat.ServiceUsageList); // // adding the node to the stat object. // result.NodeDate.Add(nodeStat); // // comulate the data from each node. // result.ServiceAmountOfObjects += remoteStat.ServiceAmountOfObjects; result.ServiceTotalSize += remoteStat.ServiceTotalSize; // // if the remote object is not null or empty nothing has to take over and // printout gone be empty then the cache is empty // if (remoteStat.ServiceUsageList != null && remoteStat.ServiceUsageList.Count > 0) { // // init inner list of the local object, first time // this is not initialized. // if (result.ServiceUsageList == null) result.ServiceUsageList = new Dictionary<string, long>(); // // need to iterate over every key value pair and adding it into // general list to support a general overview of top values from // all servers together. // foreach (KeyValuePair<string, long> de in remoteStat.ServiceUsageList) { // // upon replication the key's are available on all server // if (!result.ServiceUsageList.ContainsKey(de.Key)) { result.ServiceUsageList.Add(de.Key, de.Value); } } // // sorting comulated data from each node. // Handler.Generic.Util.SortDictionaryDesc(result.ServiceUsageList); } return result; } // // ********************************************************************** /// <summary> /// Retrieve all statistic information <see cref="LBSStatistic"/> from each configured /// server as one item. /// </summary> /// <returns> /// an aggrigated <see cref="LBSStatistic"/> object with all server statistics /// </returns> // ********************************************************************** // public override LBSStatistic GetStats() { LBSStatistic result = new LBSStatistic(); int cntr = 0; foreach (Configuration.Client.LBSServerSetting setting in this.ServersList) { string configuredHost = setting.IpAddress; // // retrieve for specific host all data // LBSStatistic remoteStat = CacheUtil.Statistic(configuredHost); // // read the local data, need to read them upon the last item, otherwise the amount // of stats would be missing the server calls. // if (cntr == (this.ServersList.Count - 1)) { result.apiCounterAdd = remoteStat.apiCounterAdd; result.apiCounterFailed = remoteStat.apiCounterFailed; result.apiCounterGet = remoteStat.apiCounterGet; result.apiCounterRemove = remoteStat.apiCounterRemove; result.apiCounterSuccess = remoteStat.apiCounterSuccess; result.apiCounterStatistic = remoteStat.apiCounterStatistic; result.apiHitSuccess = remoteStat.apiHitSuccess; result.apiHitFailed = remoteStat.apiHitFailed; } cntr++; // // creating a node stat object // ServerStats nodeStat = new ServerStats(configuredHost, remoteStat.ServiceAmountOfObjects, remoteStat.ServiceTotalSize, remoteStat.ServiceUsageList); // // adding the node to the stat object. // result.NodeDate.Add(nodeStat); // // comulate the data from each node. // result.ServiceAmountOfObjects += remoteStat.ServiceAmountOfObjects; result.ServiceTotalSize += remoteStat.ServiceTotalSize; // // if the remote object is not null or empty nothing has to take over and // printout gone be empty then the cache is empty // if (remoteStat.ServiceUsageList != null && remoteStat.ServiceUsageList.Count > 0) { // // init inner list of the local object, first time // this is not initialized. // if (result.ServiceUsageList == null) result.ServiceUsageList = new Dictionary<string, long>(); // // need to iterate over every key value pair and adding it into // general list to support a general overview of top values from // all servers together. // foreach (KeyValuePair<string, long> de in remoteStat.ServiceUsageList) { // // upon replication the key's are available on all server // if (!result.ServiceUsageList.ContainsKey(de.Key)) { result.ServiceUsageList.Add(de.Key, de.Value); } } // // sorting comulated data from each node. // Handler.Generic.Util.SortDictionaryDesc(result.ServiceUsageList); } } return result; } // // ********************************************************************** /// <summary> /// Return the ip server which handles this key by the hashcode of the key. /// </summary> /// <param name="key">The key.</param> /// <returns> /// the specific host ip as a <see cref="string"/> object. /// </returns> // ********************************************************************** // public override string GetServerForKey(string key) { switch (Hashing) { // // option - yes -> 0ms -> hash = Hydra.SharedCache.Common.Hashing.GetHashCodeWrapper.GetHashCode(values[i]); // option - yes -> 1ms -> hash = Hydra.SharedCache.Common.Hashing.Ketama.Generate(values[i]); // option - yes -> 0ms -> hash = BitConverter.ToInt32(Hydra.SharedCache.Common.Hashing.FnvHash32.Create().ComputeHash(Encoding.Unicode.GetBytes(values[i])), 0); // option - yes -> 0ms -> hash = BitConverter.ToInt32(Hydra.SharedCache.Common.Hashing.FnvHash64.Create().ComputeHash(Encoding.Unicode.GetBytes(values[i])), 0); // case Enums.HashingAlgorithm.Hashing: { return Servers[Hydra.SharedCache.Common.Hashing.Hash.Generate(key, Servers.Length)]; } case Enums.HashingAlgorithm.Ketama: { int srv = Math.Abs(Hydra.SharedCache.Common.Hashing.Ketama.Generate(key) % Servers.Length); return Servers[srv]; } case Enums.HashingAlgorithm.FvnHash32: { int srv = Math.Abs(BitConverter.ToInt32(Hydra.SharedCache.Common.Hashing.FnvHash32.Create().ComputeHash(Encoding.UTF8.GetBytes(key)), 0) % Servers.Length); return Servers[srv]; } case Enums.HashingAlgorithm.FvnHash64: { int srv = Math.Abs(BitConverter.ToInt32(Hydra.SharedCache.Common.Hashing.FnvHash64.Create().ComputeHash(Encoding.UTF8.GetBytes(key)), 0) % Servers.Length); return Servers[srv]; } default: return Servers[Hydra.SharedCache.Common.Hashing.Hash.Generate(key, Servers.Length)]; } } } }
//*********************************************\\ // Piece Manipulating Device *\\ // Old Name: Editor Pack *\\ // By: Robert MacGregor *\\ // Version: 0.2 *\\ //*********************************************\\ //*********************************************\\ // DATABLOCKS *\\ //*********************************************\\ datablock StaticShapeData(DeployedEditorPack) : StaticShapeDamageProfile { className = "EditorPack"; shapeFile = "stackable2s.dts"; maxDamage = 2.0; destroyedLevel = 2.0; disabledLevel = 2.0; mass = 1.2; elasticity = 0.1; friction = 0.9; collideable = 1; pickupRadius = 1; sticky = false; explosion = HandGrenadeExplosion; expDmgRadius = 1.0; expDamage = 0.1; expImpulse = 200.0; dynamicType = $TypeMasks::StaticShapeObjectType; deployedObject = true; cmdCategory = "DSupport"; cmdIcon = CMDSensorIcon; cmdMiniIconName = "commander/MiniIcons/com_deploymotionsensor"; targetNameTag = 'Piece Manipulating'; targetTypeTag = 'Device'; deployAmbientThread = true; debrisShapeName = "debris_generic_small.dts"; debris = DeployableDebris; heatSignature = 0; needsPower = true; }; datablock ShapeBaseImageData(EditorPackDeployableImage) { mass = 10; emap = true; shapeFile = "stackable1s.dts"; item = EditorPackDeployable; mountPoint = 1; offset = "0 0 0"; deployed = DeployedEditorPack; heatSignature = 0; collideable = 1; stateName[0] = "Idle"; stateTransitionOnTriggerDown[0] = "Activate"; stateName[1] = "Activate"; stateScript[1] = "onActivate"; stateTransitionOnTriggerUp[1] = "Idle"; isLarge = true; maxDepSlope = 360; deploySound = ItemPickupSound; minDeployDis = 0.5; maxDeployDis = 5.0; }; datablock ItemData(EditorPackDeployable) { className = Pack; catagory = "Deployables"; shapeFile = "stackable1s.dts"; mass = 5.0; elasticity = 0.2; friction = 0.6; pickupRadius = 1; rotate = true; image = "EditorPackDeployableImage"; pickUpName = "a Piece Manipulating Device"; heatSignature = 0; emap = true; }; //*********************************************\\ // CODE *\\ //*********************************************\\ $TeamDeployableMax[EditorPackDeployable] = 9999; //Change To Your Desire function EditorPackDeployableImage::onDeploy(%item, %plyr, %slot) { %className = "StaticShape"; %playerVector = vectorNormalize(getWord(%plyr.getEyeVector(),1) SPC -1 * getWord(%plyr.getEyeVector(),0) SPC "0"); %item.surfaceNrm2 = %playerVector; if (vAbs(floorVec(%item.surfaceNrm,100)) $= "0 0 1") %item.surfaceNrm2 = %playerVector; else %item.surfaceNrm2 = vectorNormalize(vectorCross(%item.surfaceNrm,"0 0 -1")); %rot = fullRot(%item.surfaceNrm,%item.surfaceNrm2); %deplObj = new (%className)() { dataBlock = %item.deployed; scale = "1 1 1"; }; // set orientation %deplObj.setTransform(%item.surfacePt SPC %rot); %deplObj.deploy(); // set team, owner, and handle %deplObj.team = %plyr.client.Team; %deplObj.setOwner(%plyr); %deplObj.paded=1; //Msg Client messageclient(%plyr.client, 'MsgClient', "\c2Type /editor CMD's for a list of device CMDs."); // set the sensor group if it needs one if (%deplObj.getTarget() != -1) setTargetSensorGroup(%deplObj.getTarget(), %plyr.client.team); // place the deployable in the MissionCleanup/Deployables group (AI reasons) addToDeployGroup(%deplObj); //Set the power frequency %deplObj.powerFreq = %plyr.powerFreq; checkPowerObject(%deplObj); //let the AI know as well... AIDeployObject(%plyr.client, %deplObj); // play the deploy sound serverPlay3D(%item.deploySound, %deplObj.getTransform()); // increment the team count for this deployed object $TeamDeployedCount[%plyr.team, %item.item]++; addDSurface(%item.surface,%deplObj); %deplObj.playThread($PowerThread,"Power"); %deplObj.playThread($AmbientThread,"ambient"); // take the deployable off the player's back and out of inventory %plyr.unmountImage(%slot); %plyr.decInventory(%item.item, 1); //Set the slot count %deplobj.slotcount = 1; //For /editor addobj return %deplObj; } function EditorPack::onCollision(%data,%obj,%col) { // created to prevent console errors } function EditorPackDeployable::onPickup(%this, %obj, %shape, %amount) { // created to prevent console errors } function EditorPackDeployableImage::onMount(%data, %obj, %node) { displayPowerFreq(%obj); } function EditorPackDeployableImage::onUnmount(%data, %obj, %node) { // created to prevent console errors } function DeployedEditorPack::gainPower(%data, %obj) { EditorPerform(%obj); %obj.edited = true; } function DeployedEditorPack::losePower(%data, %obj) { EditorPerform(%obj); %obj.edited = false; } function EditorPerform(%obj) { PerformCloak(%obj); PerformFade(%obj); PerformScale(%obj); PerformHide(%obj); PerformName(%obj); } function DeployedEditorPack::onDestroyed(%this, %obj, %prevState) { if (%obj.edited) EditorPerform(%obj); if (%obj.isRemoved) return; %obj.isRemoved = true; Parent::onDestroyed(%this, %obj, %prevState); $TeamDeployedCount[%obj.team, bogypackDeployable]--; remDSurface(%obj); %obj.schedule(500, "delete"); fireBallExplode(%obj,1); } function IsValidClass(%class) { if (%class $="Spine" || %class $="Generator" || %class $="Switch" || %class $="WWall" || %class $="Wall" || %class $="MSpine" || %class $="Station" || %class $="Sensor" || %class $="DeployedTurret" || %class $="LogoProjector" || %class $="DeployedLightBase" || %class $="Tripwire" || %class $="Teleport" || %class $="Jumpad" || %class $="Tree" || %class $="Crate" || %class $="GravityField") return true; else return false; } function ccEditor(%sender,%args) { %f = getword(%args,0); %f = StrLwr(%f); %f = stripchars(%f," "); //Strip spaces. %pos = %sender.player.getMuzzlePoint($WeaponSlot); %vec = %sender.player.getMuzzleVector($WeaponSlot); %targetpos = vectoradd(%pos,vectorscale(%vec,100)); %obj = containerraycast(%pos,%targetpos,$typemasks::staticshapeobjecttype,%sender.player); %obj = getword(%obj,0); if (%f $="") { messageclient(%sender,'msgclient',"\c2No command specified, please type '/Editor Help' for a list of commands."); return 1; } else if (!EvaluateFunction(%f)) { messageclient(%sender,'msgclient','\c2Unknown command: %1.', %f); return 1; } else if (%f $="help" || %f $="cmds") { messageclient(%sender,'msgclient',"\c2/Editor Select - Selects the device you're looking at."); messageclient(%sender,'msgclient',"\c2/Editor DelObj - Removes the object you're looking at from your currently selected device."); messageclient(%sender,'msgclient',"\c2/Editor List - If you own the device you're looking at, this command will list all pieces assigned to it."); messageclient(%sender,'msgclient',"\c2/Editor Cloak - Adds the object you're looking at to your device's currently selected cloak list."); messageclient(%sender,'msgclient',"\c2/Editor Fade - Adds the object you're looking at to your device's currently selected fade list."); messageclient(%sender,'msgclient',"\c2/Editor Name <New Name> - Adds the object you're looking at to your currently selected device's fade list."); messageclient(%sender,'msgclient',"\c2/Editor Scale <New Scale> - Adds the object you're looking at to your currently selected device's scale list."); messageclient(%sender,'msgclient',"\c2/Editor Hide - Adds the object you're looking at to your currently selected device's fade list."); return 1; } else if (!%obj) { messageclient(%sender,'msgclient',"\c2Unable to find an object."); return 1; } else if (IsObject(%obj) && IsValidClass(%obj.getclassname())) { messageclient(%sender,'msgclient','\c2Invalid object. Error: Invalid ClassName - %1.', %obj.getclassname()); return 1; } else if (%f $="delobj") { ProcessDelObj(%sender,%obj,%args); return 1; } else if (%f $="list") { ProcessList(%sender,%obj); return 1; } else if (%f $="addobj") { ProcessAddObj(%sender,%obj); return 1; } else if (%f $="fade") { ProcessFade(%sender,%obj,%args); return 1; } else if (%f $="cloak") { ProcessCloak(%sender,%obj,%args); return 1; } else if (%f $="scale") { ProcessScale(%sender,%obj,%args); return 1; } else if (%f $="name") { ProcessName(%sender,%obj,%args); return 1; } else if (%f $="hide") { ProcessHide(%sender,%obj,%args); return 1; } else { ProcessEditorRequest(%sender,%obj,%f); return 1; } return 1; } function ProcessList(%sender,%obj) { if (IsObject(%obj)) { %count = %obj.slotcount; %count = %count - 1; if (%count > 1) { for (%i = 0; %i < %count; %i++) { %slotobj = %obj.slot[%i]; if (IsObject(%slotobj)) { messageclient(%sender,'msgclient','\c2%1: %2 - %3', %i, %slotobj, %slotobj.getclassname()); } else { messageclient(%sender,'msgclient','\c2%1: %2 - Does not exist. You should not see this error.', %i, %slotobj); } } } else { messageclient(%sender,'msgclient','\c2This device has an invalid slot count: %1. You should not see this error.', %count); return; } } else { messageclient(%sender,'msgclient','\c2Object %1 does not exist. You should not see this error.', %obj); return; } } function ProcessEditorRequest(%sender,%obj,%f) { if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2This editor pack is not yours!"); return; } if (%obj.getdatablock().getname() !$="DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to edit devices!"); return; } if (%f $="select" || %f $="selecteditor" || %f = "seledit") { %sender.currentedit = %obj; %obj.setcloaked(true); schedule(500,0,"SetCloaked",%obj,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); messageclient(%sender,'msgclient',"\c2Current device set."); return; } } function ProcessAddObj(%sender,%obj) { if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2This object is not yours!"); return; } if (!IsObject(%Sender.CurrentEdit)) { messageclient(%sender,'msgclient',"\c2No device selected! You can use '/Editor Select' while pointing at a device to select it."); return; } if (%obj.getdatablock().getname() $= "DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to edit Piece Manipulating Devices!"); return; } %Slots = %sender.currentedit.slotcount; %edit = %sender.currentedit; for (%i=0;%i<%slots;%i++) { if (%edit.slot[%i] $="") { %edit.slot[%i] = %obj; %edit.slotcount++; messageclient(%sender,'msgclient','\c2Object has been added to your current device. (%1)', %i); %obj.slot = %i; %obj.editor = true; %obj.setcloaked(true); schedule(500,0,"SetCloaked",%obj,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); return; } } } function ProcessDelObj(%sender,%obj,%args) { %edit = %sender.currentedit; if (!IsObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return; } if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2Not your object!"); return; } if (!%obj.editor) { messageclient(%sender,'msgclient',"\c2This object is not bound to a device!"); return; } messageclient(%sender,'msgclient','\c2Object deleted from your currently selected device. (%1)', %edit.slot[%obj.slot]); %edit.slot[%obj.slot] = ""; %obj.slot = ""; %obj.editor = false; %obj.setcloaked(true); schedule(500,0,"SetCloaked",%obj,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); if (%edit.slotcount > 1) %edit.slotcount--; } function ProcessScale(%sender,%obj,%args) { %scale = getwords(%args,1); %edit = %sender.currentedit; if (!IsObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return; } else if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2Not your object!"); return; } else if (%obj.getdatablock().getname() $= "DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to scale devices!"); return; } else if (%scale $="" && %obj.istscale == false) { messageclient(%sender,'msgclient',"\c2No scale specified."); return; } else if (getword(%scale,0) > $Editor::MaxScale["X"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The X axis is too big. Max: %2', %scale, $Editor::MaxScale["X"]); return; } else if (getword(%scale,1) > $Editor::MaxScale["Y"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The Y axis is too big. Max: %2', %scale, $Editor::MaxScale["Y"]); return; } else if (getword(%scale,2) > $Editor::MaxScale["Z"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The Z axis is too big. Max: %2', %scale,$Editor::MaxScale["Z"]); return; } else if (getword(%scale,0) < $Editor::MinScale["X"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The X axis is too small. Min: %2', %scale, $Editor::MinScale["X"]); return; } else if (getword(%scale,1) < $Editor::MinScale["Y"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The Y axis is too small. Min:', %scale, $Editor::MinScale["Y"]); return; } else if (getword(%scale,2) < $Editor::MinScale["Z"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The scale %1is invalid. The Z axis is too small. Min:', %scale, $Editor::MinScale["Z"]); return; } else { %scale = CheckScale(%scale); if (!%obj.istscale) { if (!%obj.editor) ProcessAddObj(%Sender,%obj); %obj.istscale = true; %obj.isescaled = false; messageclient(%sender,'msgclient','\c2Object has been added to your currently selected device\'s scale list. This object will be scaled to %1.', %scale); %obj.escale = %scale; %obj.oldscale = %obj.getscale(); %obj.setcloaked(true); schedule(500,0,"SetCloaked",%obj,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); return; } else { %obj.istscale = false; %obj.isescaled = false; messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's scale list. Original scale restored."); %obj.setscale(%obj.oldscale); %obj.setcloaked(true); schedule(500,0,"SetCloaked",%obj,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); } } } function ProcessFade(%sender,%obj,%args) { %edit = %sender.currentedit; if (!isObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return; } if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2This object is not yours!"); return; } if (%obj.getdatablock().getname() $= "DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to fade Piece Manipulating Devices!"); return; } if (!%obj.istfade) { if (!%obj.editor) ProcessAddObj(%Sender,%obj); %obj.istfade = true; %obj.isefaded = false; %obj.setcloaked(true); schedule(500,0,"SetCloaked",%obj, false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); messageclient(%sender,'msgclient',"\c2Object has been added to your currently selected device's fade list."); return; } else { %obj.istfade = false; %obj.isefaded = false; %obj.setcloaked(true); schedule(500,0,"SetCloaked",%obj,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's fade list."); } } function ProcessHide(%sender,%obj,%args) { %edit = %sender.currentedit; if (!isObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return; } if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2This object is not yours!"); return; } if (%obj.getdatablock().getname() $= "DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to fade devices!"); return; } if (!%obj.isthide) { if (!%obj.editor) ProcessAddObj(%Sender,%obj); %obj.isthide = true; %obj.isehidden = false; messageclient(%sender,'msgclient',"\c2Object has been added to your currently selected device's hide list."); %obj.setcloaked(true); schedule(500,0,"SetCloaked",%obj,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); return; } else { %obj.isthide = false; %obj.isehidden = false; messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's hide list."); %obj.setcloaked(true); schedule(500,0,"SetCloaked",%obj,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); } } function ProcessCloak(%sender,%obj,%args) { %edit = %sender.currentedit; if (!isObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return; } if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2This object is not yours!"); return; } if (%obj.getdatablock().getname() $= "DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to cloak devices!"); return; } if (!%obj.istcloak) { if (!%obj.editor) ProcessAddObj(%Sender,%obj); %obj.istcloak = true; %obj.isecloaked = false; messageclient(%sender,'msgclient',"\c2Object has been added to your currently selected device's cloak list."); %obj.setcloaked(true); schedule(500,0,"SetCloaked",%obj,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); return; } else { %obj.istcloak = false; %obj.isecloaked = false; messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's cloak list."); %obj.setcloaked(true); schedule(500,0,"SetCloaked",%obj,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); } } function ProcessName(%sender,%obj,%args) { %edit = %sender.currentedit; %name = getwords(%args,1); if (!isObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return 1; } else if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2This object is not yours!"); return 1; } else if (%obj.getdatablock().getname() $= "DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to name devices!"); return 1; } else if (!%obj.istname) { if (!%obj.editor) ProcessAddObj(%Sender,%obj); %obj.istname = true; %obj.isenamed = false; %obj.oldname = %obj.nametag; %obj.ename = %name; messageclient(%sender,'msgclient',"\c2Object has been added to your currently selected device's name list. This object will be named to: "@%name@""); %obj.setcloaked(true); schedule(500,0,"SetCloaked",%obj,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); return 1; } else { %obj.istname = false; %obj.isename = false; %obj.nametag = %obj.oldname; setTargetName(%obj.target,addTaggedString("\c6"@%obj.oldname@"")); %obj.oldname = ""; messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's cloak list. Old name restored."); %obj.setcloaked(true); schedule(500,0,"SetCloaked",%obj,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); return 1; } else { messageclient(%sender,'msgclient',"\c2An unknown error has occured."); return 1; } } function PerformCloak(%obj) { if (!IsObject(%obj)) return; %c = %obj.slotcount; %c++; for (%i=0;%i<%c;%i++) { %object = %obj.slot[%i]; if (!IsObject(%Object)) return; if (!%object.istcloak) //IsTFade = Is To Fade %object.isecloaked = true; //To Make The System Think It's Already Cloaked if (%object.isecloaked) { %object.setcloaked(false); %object.isecloaked = false; } else { schedule(510,0,"SetCloaked",%object,true); //Somehow Fixed The Cloaking Problem %object.isecloaked = true; } } } function setcloaked(%obj,%bool) { %obj.setcloaked(%bool); } function PerformFade(%obj) { if (!IsObject(%obj)) return; %c = %obj.slotcount; %c = %c++; for (%i=0;%i<%c;%i++) { %object = %obj.slot[%i]; if (!IsObject(%Object)) return; if (!%object.istfade) //IsTFade = Is To Fade %object.isefaded = true; //To Make The System Think It's Already Faded if (%object.isefaded) { %object.startfade(1,0,0); %object.isefaded= false; } else { %object.setcloaked(true); schedule(500,0,"SetCloaked",%object,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); schedule(510,0,"fade",%object); %object.isefaded = true; } } } function PerformHide(%obj) { if (!IsObject(%obj)) return; for (%i=0;%i<%obj.slotcount;%i++) { %object = %obj.slot[%i]; if (!IsObject(%Object)) return; if (!%object.isthide) //IsTFade = Is To Fade %object.isehidden = true; //To Make The System Think It's Already Hidden if (%object.isehidden) { %object.hide(0); %object.isehidden= false; } else { %object.setcloaked(true); schedule(500,0,"SetCloaked",%obj.slot[%slot],false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); schedule(510,0,"Hide",%object); %object.isehidden = true; } } } function Hide(%obj) { %obj.hide(1); } function fade(%obj) { %obj.startfade(1,0,1); } function PerformScale(%obj) { if (!IsObject(%obj)) return; %c = %obj.slotcount; %c = %c++; for (%i=0;%i<%c;%i++) { %object = %obj.slot[%i]; if (!IsObject(%Object)) return; if (!%object.istscale){ //IsTFade = Is To Fade %object.isescaled = true; //To Make The System Think It's Already Scaled %object.oldscale = %object.getscale(); } if (%object.isescaled) { %object.setscale(%object.oldscale); %object.setcloaked(true); schedule(500,0,"SetCloaked",%object,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); %object.isescaled= false; } else { %object.setscale(%object.escale); %object.setcloaked(true); schedule(500,0,"SetCloaked",%object,false); //Couldn't Get It To Work With schedule(1000,0,"SetCloaked",%obj,true); %object.isescaled = true; } } } function PerformName(%obj) { if (!IsObject(%obj)) return; %c = %obj.slotcount; %c = %c++; for (%i=0;%i<%c;%i++) { %object = %obj.slot[%i]; if (!IsObject(%Object)) return; if (!%object.istname){ //IsTFade = Is To Fade %object.isenamed = true; //To Make The System Think It's Already Scaled if (%object.nametag !$="") %object.oldname = %object.nametag; else %object.oldname = %object.getdatablock().targetNameTag; } if (%object.isenamed) { %object.nametag = %obj.oldname; setTargetName(%object.target,addTaggedString("\c6"@%object.oldname@"")); %object.isenamed = false; } else { %object.nametag = %object.ename; setTargetName(%object.target,addTaggedString("\c6"@%object.ename@"")); %object.isenamed = true; } } } function EvaluateFunction(%f) //To Eval The Command { if (%f $="addobj" || %f $= "selecteditor" || %f $="selecteditor" || %f $="seledit" || %f $="select" || %f $="delobj" || %f $="help" || %f $="cmds" || %f $="fade" || %f $="cloak" || %f $="scale" || %f $="getid" || %f $="hide" || %f $="name" || %f $="list") return true; else return false; } function IsMatch(%string1,%string2) { %string1 = StrLwr(%string1); %string2 = StrLwr(%string2); if (%string1 $=%string2) return true; else return false; } function CheckScale(%scale) //Evals The Scale For Any Missing Args, If So, Puts A 1 In The Blank Slot { if (getword(%scale,0) $="") %scale = "1" SPC getword(%scale,1) SPC getword(%scale,2); if (getword(%scale,1) $="") %scale = getword(%scale,0) SPC "1" SPC getword(%scale,2); if (getword(%scale,2) $="") %scale = getword(%scale,0) SPC getword(%scale,1) SPC "1"; return %scale; } //*********************************************\\ // VARIABLES \\ //*********************************************\\ $Editor::MaxScale["X"] = 20; $Editor::MaxScale["Y"] = 20; $Editor::MaxScale["Z"] = 20; $Editor::MinScale["X"] = -20; $Editor::MinScale["Y"] = -20; $Editor::MinScale["Z"] = -20;
/* Copyright 2019 Esri 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 ServiceAreaSolver { partial class frmServiceAreaSolver { /// <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.btnSolve = new System.Windows.Forms.Button(); this.ckbUseRestriction = new System.Windows.Forms.CheckBox(); this.cbCostAttribute = new System.Windows.Forms.ComboBox(); this.lstOutput = new System.Windows.Forms.ListBox(); this.label2 = new System.Windows.Forms.Label(); this.txtCutOff = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.btnLoadMap = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.txtFeatureDataset = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.txtInputFacilities = new System.Windows.Forms.TextBox(); this.txtNetworkDataset = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.txtWorkspacePath = new System.Windows.Forms.TextBox(); this.gbServiceAreaSolver = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.axMapControl = new ESRI.ArcGIS.Controls.AxMapControl(); this.groupBox1.SuspendLayout(); this.gbServiceAreaSolver.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.axMapControl)).BeginInit(); this.SuspendLayout(); // // btnSolve // this.btnSolve.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnSolve.Location = new System.Drawing.Point(54, 243); this.btnSolve.Name = "btnSolve"; this.btnSolve.Size = new System.Drawing.Size(89, 34); this.btnSolve.TabIndex = 1; this.btnSolve.Text = "Solve"; this.btnSolve.UseVisualStyleBackColor = true; this.btnSolve.Click += new System.EventHandler(this.btnSolve_Click); // // ckbUseRestriction // this.ckbUseRestriction.AutoSize = true; this.ckbUseRestriction.Location = new System.Drawing.Point(9, 81); this.ckbUseRestriction.Name = "ckbUseRestriction"; this.ckbUseRestriction.Size = new System.Drawing.Size(98, 17); this.ckbUseRestriction.TabIndex = 3; this.ckbUseRestriction.Text = "Use Restriction"; this.ckbUseRestriction.UseVisualStyleBackColor = true; // // cbCostAttribute // this.cbCostAttribute.FormattingEnabled = true; this.cbCostAttribute.Location = new System.Drawing.Point(78, 27); this.cbCostAttribute.Name = "cbCostAttribute"; this.cbCostAttribute.Size = new System.Drawing.Size(121, 21); this.cbCostAttribute.TabIndex = 4; // // lstOutput // this.lstOutput.FormattingEnabled = true; this.lstOutput.HorizontalScrollbar = true; this.lstOutput.Location = new System.Drawing.Point(9, 108); this.lstOutput.Name = "lstOutput"; this.lstOutput.Size = new System.Drawing.Size(189, 121); this.lstOutput.TabIndex = 5; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(6, 30); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(70, 13); this.label2.TabIndex = 8; this.label2.Text = "Cost Attribute"; // // txtCutOff // this.txtCutOff.Location = new System.Drawing.Point(78, 55); this.txtCutOff.Name = "txtCutOff"; this.txtCutOff.Size = new System.Drawing.Size(120, 20); this.txtCutOff.TabIndex = 9; this.txtCutOff.Text = "0"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(6, 58); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(40, 13); this.label3.TabIndex = 10; this.label3.Text = "Cut Off"; // // btnLoadMap // this.btnLoadMap.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnLoadMap.Location = new System.Drawing.Point(443, 38); this.btnLoadMap.Name = "btnLoadMap"; this.btnLoadMap.Size = new System.Drawing.Size(94, 38); this.btnLoadMap.TabIndex = 11; this.btnLoadMap.Text = "Setup Service Area Problem"; this.btnLoadMap.UseVisualStyleBackColor = true; this.btnLoadMap.Click += new System.EventHandler(this.btnLoadMap_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.txtFeatureDataset); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.txtInputFacilities); this.groupBox1.Controls.Add(this.btnLoadMap); this.groupBox1.Controls.Add(this.txtNetworkDataset); this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.txtWorkspacePath); this.groupBox1.Location = new System.Drawing.Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(555, 125); this.groupBox1.TabIndex = 12; this.groupBox1.TabStop = false; this.groupBox1.Text = "Map Configuration"; // // txtFeatureDataset // this.txtFeatureDataset.Location = new System.Drawing.Point(106, 69); this.txtFeatureDataset.Name = "txtFeatureDataset"; this.txtFeatureDataset.Size = new System.Drawing.Size(308, 20); this.txtFeatureDataset.TabIndex = 15; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(6, 72); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(83, 13); this.label6.TabIndex = 14; this.label6.Text = "Feature Dataset"; // // txtInputFacilities // this.txtInputFacilities.Location = new System.Drawing.Point(106, 95); this.txtInputFacilities.Name = "txtInputFacilities"; this.txtInputFacilities.Size = new System.Drawing.Size(308, 20); this.txtInputFacilities.TabIndex = 13; // // txtNetworkDataset // this.txtNetworkDataset.Location = new System.Drawing.Point(106, 45); this.txtNetworkDataset.Name = "txtNetworkDataset"; this.txtNetworkDataset.Size = new System.Drawing.Size(308, 20); this.txtNetworkDataset.TabIndex = 12; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(6, 98); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(74, 13); this.label5.TabIndex = 11; this.label5.Text = "Input Facilities"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(6, 48); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(87, 13); this.label4.TabIndex = 10; this.label4.Text = "Network Dataset"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(6, 22); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(87, 13); this.label1.TabIndex = 9; this.label1.Text = "Workspace Path"; // // txtWorkspacePath // this.txtWorkspacePath.Location = new System.Drawing.Point(106, 19); this.txtWorkspacePath.Name = "txtWorkspacePath"; this.txtWorkspacePath.Size = new System.Drawing.Size(308, 20); this.txtWorkspacePath.TabIndex = 8; // // gbServiceAreaSolver // this.gbServiceAreaSolver.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.gbServiceAreaSolver.Controls.Add(this.tableLayoutPanel1); this.gbServiceAreaSolver.Controls.Add(this.btnSolve); this.gbServiceAreaSolver.Controls.Add(this.label3); this.gbServiceAreaSolver.Controls.Add(this.label2); this.gbServiceAreaSolver.Controls.Add(this.txtCutOff); this.gbServiceAreaSolver.Controls.Add(this.ckbUseRestriction); this.gbServiceAreaSolver.Controls.Add(this.lstOutput); this.gbServiceAreaSolver.Controls.Add(this.cbCostAttribute); this.gbServiceAreaSolver.Enabled = false; this.gbServiceAreaSolver.Location = new System.Drawing.Point(12, 142); this.gbServiceAreaSolver.Name = "gbServiceAreaSolver"; this.gbServiceAreaSolver.Size = new System.Drawing.Size(555, 295); this.gbServiceAreaSolver.TabIndex = 13; this.gbServiceAreaSolver.TabStop = false; this.gbServiceAreaSolver.Text = "Service Area Solver"; // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 1; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Controls.Add(this.axMapControl, 0, 0); this.tableLayoutPanel1.Location = new System.Drawing.Point(205, 19); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 1; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(332, 258); this.tableLayoutPanel1.TabIndex = 24; // // axMapControl // this.axMapControl.Location = new System.Drawing.Point(2, 2); this.axMapControl.Margin = new System.Windows.Forms.Padding(2); this.axMapControl.Name = "axMapControl"; this.axMapControl.Size = new System.Drawing.Size(265, 254); this.axMapControl.TabIndex = 11; // // frmServiceAreaSolver // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(576, 449); this.Controls.Add(this.gbServiceAreaSolver); this.Controls.Add(this.groupBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.Name = "frmServiceAreaSolver"; this.Text = "ArcGIS Engine Network Analyst Service Area Solver"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.gbServiceAreaSolver.ResumeLayout(false); this.gbServiceAreaSolver.PerformLayout(); this.tableLayoutPanel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.axMapControl)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnSolve; private System.Windows.Forms.CheckBox ckbUseRestriction; public System.Windows.Forms.ComboBox cbCostAttribute; private System.Windows.Forms.ListBox lstOutput; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtCutOff; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button btnLoadMap; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.TextBox txtNetworkDataset; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtWorkspacePath; private System.Windows.Forms.TextBox txtInputFacilities; private System.Windows.Forms.GroupBox gbServiceAreaSolver; private System.Windows.Forms.TextBox txtFeatureDataset; private System.Windows.Forms.Label label6; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private ESRI.ArcGIS.Controls.AxMapControl axMapControl; } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// AuthCallsCredentialListMappingResource /// </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.Api.V2010.Account.Sip.Domain.AuthTypes.AuthTypeCalls { public class AuthCallsCredentialListMappingResource : Resource { private static Request BuildCreateRequest(CreateAuthCallsCredentialListMappingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/SIP/Domains/" + options.PathDomainSid + "/Auth/Calls/CredentialListMappings.json", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Create a new credential list mapping resource /// </summary> /// <param name="options"> Create AuthCallsCredentialListMapping parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AuthCallsCredentialListMapping </returns> public static AuthCallsCredentialListMappingResource Create(CreateAuthCallsCredentialListMappingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Create a new credential list mapping resource /// </summary> /// <param name="options"> Create AuthCallsCredentialListMapping parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AuthCallsCredentialListMapping </returns> public static async System.Threading.Tasks.Task<AuthCallsCredentialListMappingResource> CreateAsync(CreateAuthCallsCredentialListMappingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Create a new credential list mapping resource /// </summary> /// <param name="pathDomainSid"> The SID of the SIP domain that will contain the new resource </param> /// <param name="credentialListSid"> The SID of the CredentialList resource to map to the SIP domain </param> /// <param name="pathAccountSid"> The SID of the Account that will create the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AuthCallsCredentialListMapping </returns> public static AuthCallsCredentialListMappingResource Create(string pathDomainSid, string credentialListSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new CreateAuthCallsCredentialListMappingOptions(pathDomainSid, credentialListSid){PathAccountSid = pathAccountSid}; return Create(options, client); } #if !NET35 /// <summary> /// Create a new credential list mapping resource /// </summary> /// <param name="pathDomainSid"> The SID of the SIP domain that will contain the new resource </param> /// <param name="credentialListSid"> The SID of the CredentialList resource to map to the SIP domain </param> /// <param name="pathAccountSid"> The SID of the Account that will create the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AuthCallsCredentialListMapping </returns> public static async System.Threading.Tasks.Task<AuthCallsCredentialListMappingResource> CreateAsync(string pathDomainSid, string credentialListSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new CreateAuthCallsCredentialListMappingOptions(pathDomainSid, credentialListSid){PathAccountSid = pathAccountSid}; return await CreateAsync(options, client); } #endif private static Request BuildReadRequest(ReadAuthCallsCredentialListMappingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/SIP/Domains/" + options.PathDomainSid + "/Auth/Calls/CredentialListMappings.json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of credential list mappings belonging to the domain used in the request /// </summary> /// <param name="options"> Read AuthCallsCredentialListMapping parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AuthCallsCredentialListMapping </returns> public static ResourceSet<AuthCallsCredentialListMappingResource> Read(ReadAuthCallsCredentialListMappingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<AuthCallsCredentialListMappingResource>.FromJson("contents", response.Content); return new ResourceSet<AuthCallsCredentialListMappingResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of credential list mappings belonging to the domain used in the request /// </summary> /// <param name="options"> Read AuthCallsCredentialListMapping parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AuthCallsCredentialListMapping </returns> public static async System.Threading.Tasks.Task<ResourceSet<AuthCallsCredentialListMappingResource>> ReadAsync(ReadAuthCallsCredentialListMappingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<AuthCallsCredentialListMappingResource>.FromJson("contents", response.Content); return new ResourceSet<AuthCallsCredentialListMappingResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of credential list mappings belonging to the domain used in the request /// </summary> /// <param name="pathDomainSid"> The SID of the SIP domain that contains the resources to read </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources 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 AuthCallsCredentialListMapping </returns> public static ResourceSet<AuthCallsCredentialListMappingResource> Read(string pathDomainSid, string pathAccountSid = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadAuthCallsCredentialListMappingOptions(pathDomainSid){PathAccountSid = pathAccountSid, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of credential list mappings belonging to the domain used in the request /// </summary> /// <param name="pathDomainSid"> The SID of the SIP domain that contains the resources to read </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources 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 AuthCallsCredentialListMapping </returns> public static async System.Threading.Tasks.Task<ResourceSet<AuthCallsCredentialListMappingResource>> ReadAsync(string pathDomainSid, string pathAccountSid = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadAuthCallsCredentialListMappingOptions(pathDomainSid){PathAccountSid = pathAccountSid, 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<AuthCallsCredentialListMappingResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<AuthCallsCredentialListMappingResource>.FromJson("contents", 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<AuthCallsCredentialListMappingResource> NextPage(Page<AuthCallsCredentialListMappingResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<AuthCallsCredentialListMappingResource>.FromJson("contents", 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<AuthCallsCredentialListMappingResource> PreviousPage(Page<AuthCallsCredentialListMappingResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<AuthCallsCredentialListMappingResource>.FromJson("contents", response.Content); } private static Request BuildFetchRequest(FetchAuthCallsCredentialListMappingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/SIP/Domains/" + options.PathDomainSid + "/Auth/Calls/CredentialListMappings/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch a specific instance of a credential list mapping /// </summary> /// <param name="options"> Fetch AuthCallsCredentialListMapping parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AuthCallsCredentialListMapping </returns> public static AuthCallsCredentialListMappingResource Fetch(FetchAuthCallsCredentialListMappingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch a specific instance of a credential list mapping /// </summary> /// <param name="options"> Fetch AuthCallsCredentialListMapping parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AuthCallsCredentialListMapping </returns> public static async System.Threading.Tasks.Task<AuthCallsCredentialListMappingResource> FetchAsync(FetchAuthCallsCredentialListMappingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch a specific instance of a credential list mapping /// </summary> /// <param name="pathDomainSid"> The SID of the SIP domain that contains the resource to fetch </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AuthCallsCredentialListMapping </returns> public static AuthCallsCredentialListMappingResource Fetch(string pathDomainSid, string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchAuthCallsCredentialListMappingOptions(pathDomainSid, pathSid){PathAccountSid = pathAccountSid}; return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch a specific instance of a credential list mapping /// </summary> /// <param name="pathDomainSid"> The SID of the SIP domain that contains the resource to fetch </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AuthCallsCredentialListMapping </returns> public static async System.Threading.Tasks.Task<AuthCallsCredentialListMappingResource> FetchAsync(string pathDomainSid, string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchAuthCallsCredentialListMappingOptions(pathDomainSid, pathSid){PathAccountSid = pathAccountSid}; return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteAuthCallsCredentialListMappingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/SIP/Domains/" + options.PathDomainSid + "/Auth/Calls/CredentialListMappings/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Delete a credential list mapping from the requested domain /// </summary> /// <param name="options"> Delete AuthCallsCredentialListMapping parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AuthCallsCredentialListMapping </returns> public static bool Delete(DeleteAuthCallsCredentialListMappingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Delete a credential list mapping from the requested domain /// </summary> /// <param name="options"> Delete AuthCallsCredentialListMapping parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AuthCallsCredentialListMapping </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteAuthCallsCredentialListMappingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Delete a credential list mapping from the requested domain /// </summary> /// <param name="pathDomainSid"> The SID of the SIP domain that contains the resource to delete </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AuthCallsCredentialListMapping </returns> public static bool Delete(string pathDomainSid, string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new DeleteAuthCallsCredentialListMappingOptions(pathDomainSid, pathSid){PathAccountSid = pathAccountSid}; return Delete(options, client); } #if !NET35 /// <summary> /// Delete a credential list mapping from the requested domain /// </summary> /// <param name="pathDomainSid"> The SID of the SIP domain that contains the resource to delete </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AuthCallsCredentialListMapping </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathDomainSid, string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new DeleteAuthCallsCredentialListMappingOptions(pathDomainSid, pathSid){PathAccountSid = pathAccountSid}; return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a AuthCallsCredentialListMappingResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> AuthCallsCredentialListMappingResource object represented by the provided JSON </returns> public static AuthCallsCredentialListMappingResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<AuthCallsCredentialListMappingResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The string that you assigned to describe the resource /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } private AuthCallsCredentialListMappingResource() { } } }
using System; using System.Text; using Gnu.MP.BrickCoinProtocol.BouncyCastle.Math; namespace Gnu.MP.BrickCoinProtocol.BouncyCastle.Utilities { /// <summary> General array utilities.</summary> internal abstract class Arrays { public static bool AreEqual( bool[] a, bool[] b) { if(a == b) return true; if(a == null || b == null) return false; return HaveSameContents(a, b); } public static bool AreEqual( char[] a, char[] b) { if(a == b) return true; if(a == null || b == null) return false; return HaveSameContents(a, b); } /// <summary> /// Are two arrays equal. /// </summary> /// <param name="a">Left side.</param> /// <param name="b">Right side.</param> /// <returns>True if equal.</returns> public static bool AreEqual( byte[] a, byte[] b) { if(a == b) return true; if(a == null || b == null) return false; return HaveSameContents(a, b); } [Obsolete("Use 'AreEqual' method instead")] public static bool AreSame( byte[] a, byte[] b) { return AreEqual(a, b); } /// <summary> /// A constant time equals comparison - does not terminate early if /// test will fail. /// </summary> /// <param name="a">first array</param> /// <param name="b">second array</param> /// <returns>true if arrays equal, false otherwise.</returns> public static bool ConstantTimeAreEqual( byte[] a, byte[] b) { int i = a.Length; if(i != b.Length) return false; int cmp = 0; while(i != 0) { --i; cmp |= (a[i] ^ b[i]); } return cmp == 0; } public static bool AreEqual( int[] a, int[] b) { if(a == b) return true; if(a == null || b == null) return false; return HaveSameContents(a, b); } public static bool AreEqual(uint[] a, uint[] b) { if(a == b) return true; if(a == null || b == null) return false; return HaveSameContents(a, b); } private static bool HaveSameContents( bool[] a, bool[] b) { int i = a.Length; if(i != b.Length) return false; while(i != 0) { --i; if(a[i] != b[i]) return false; } return true; } private static bool HaveSameContents( char[] a, char[] b) { int i = a.Length; if(i != b.Length) return false; while(i != 0) { --i; if(a[i] != b[i]) return false; } return true; } private static bool HaveSameContents( byte[] a, byte[] b) { int i = a.Length; if(i != b.Length) return false; while(i != 0) { --i; if(a[i] != b[i]) return false; } return true; } private static bool HaveSameContents( int[] a, int[] b) { int i = a.Length; if(i != b.Length) return false; while(i != 0) { --i; if(a[i] != b[i]) return false; } return true; } private static bool HaveSameContents(uint[] a, uint[] b) { int i = a.Length; if(i != b.Length) return false; while(i != 0) { --i; if(a[i] != b[i]) return false; } return true; } public static string ToString( object[] a) { StringBuilder sb = new StringBuilder('['); if(a.Length > 0) { sb.Append(a[0]); for(int index = 1; index < a.Length; ++index) { sb.Append(", ").Append(a[index]); } } sb.Append(']'); return sb.ToString(); } public static int GetHashCode(byte[] data) { if(data == null) { return 0; } int i = data.Length; int hc = i + 1; while(--i >= 0) { hc *= 257; hc ^= data[i]; } return hc; } public static int GetHashCode(byte[] data, int off, int len) { if(data == null) { return 0; } int i = len; int hc = i + 1; while(--i >= 0) { hc *= 257; hc ^= data[off + i]; } return hc; } public static int GetHashCode(int[] data) { if(data == null) return 0; int i = data.Length; int hc = i + 1; while(--i >= 0) { hc *= 257; hc ^= data[i]; } return hc; } public static int GetHashCode(int[] data, int off, int len) { if(data == null) return 0; int i = len; int hc = i + 1; while(--i >= 0) { hc *= 257; hc ^= data[off + i]; } return hc; } public static int GetHashCode(uint[] data) { if(data == null) return 0; int i = data.Length; int hc = i + 1; while(--i >= 0) { hc *= 257; hc ^= (int)data[i]; } return hc; } public static int GetHashCode(uint[] data, int off, int len) { if(data == null) return 0; int i = len; int hc = i + 1; while(--i >= 0) { hc *= 257; hc ^= (int)data[off + i]; } return hc; } public static int GetHashCode(ulong[] data) { if(data == null) return 0; int i = data.Length; int hc = i + 1; while(--i >= 0) { ulong di = data[i]; hc *= 257; hc ^= (int)di; hc *= 257; hc ^= (int)(di >> 32); } return hc; } public static int GetHashCode(ulong[] data, int off, int len) { if(data == null) return 0; int i = len; int hc = i + 1; while(--i >= 0) { ulong di = data[off + i]; hc *= 257; hc ^= (int)di; hc *= 257; hc ^= (int)(di >> 32); } return hc; } public static byte[] Clone( byte[] data) { return data == null ? null : (byte[])data.Clone(); } public static byte[] Clone( byte[] data, byte[] existing) { if(data == null) { return null; } if((existing == null) || (existing.Length != data.Length)) { return Clone(data); } Array.Copy(data, 0, existing, 0, existing.Length); return existing; } public static int[] Clone( int[] data) { return data == null ? null : (int[])data.Clone(); } internal static uint[] Clone(uint[] data) { return data == null ? null : (uint[])data.Clone(); } public static long[] Clone(long[] data) { return data == null ? null : (long[])data.Clone(); } public static ulong[] Clone( ulong[] data) { return data == null ? null : (ulong[])data.Clone(); } public static ulong[] Clone( ulong[] data, ulong[] existing) { if(data == null) { return null; } if((existing == null) || (existing.Length != data.Length)) { return Clone(data); } Array.Copy(data, 0, existing, 0, existing.Length); return existing; } public static bool Contains(byte[] a, byte n) { for(int i = 0; i < a.Length; ++i) { if(a[i] == n) return true; } return false; } public static bool Contains(short[] a, short n) { for(int i = 0; i < a.Length; ++i) { if(a[i] == n) return true; } return false; } public static bool Contains(int[] a, int n) { for(int i = 0; i < a.Length; ++i) { if(a[i] == n) return true; } return false; } public static void Fill( byte[] buf, byte b) { int i = buf.Length; while(i > 0) { buf[--i] = b; } } public static byte[] CopyOf(byte[] data, int newLength) { byte[] tmp = new byte[newLength]; Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length)); return tmp; } public static char[] CopyOf(char[] data, int newLength) { char[] tmp = new char[newLength]; Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length)); return tmp; } public static int[] CopyOf(int[] data, int newLength) { int[] tmp = new int[newLength]; Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length)); return tmp; } public static long[] CopyOf(long[] data, int newLength) { long[] tmp = new long[newLength]; Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length)); return tmp; } public static BigInteger[] CopyOf(BigInteger[] data, int newLength) { BigInteger[] tmp = new BigInteger[newLength]; Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length)); return tmp; } /** * Make a copy of a range of bytes from the passed in data array. The range can * extend beyond the end of the input array, in which case the return array will * be padded with zeroes. * * @param data the array from which the data is to be copied. * @param from the start index at which the copying should take place. * @param to the final index of the range (exclusive). * * @return a new byte array containing the range given. */ public static byte[] CopyOfRange(byte[] data, int from, int to) { int newLength = GetLength(from, to); byte[] tmp = new byte[newLength]; Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from)); return tmp; } public static int[] CopyOfRange(int[] data, int from, int to) { int newLength = GetLength(from, to); int[] tmp = new int[newLength]; Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from)); return tmp; } public static long[] CopyOfRange(long[] data, int from, int to) { int newLength = GetLength(from, to); long[] tmp = new long[newLength]; Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from)); return tmp; } public static BigInteger[] CopyOfRange(BigInteger[] data, int from, int to) { int newLength = GetLength(from, to); BigInteger[] tmp = new BigInteger[newLength]; Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from)); return tmp; } private static int GetLength(int from, int to) { int newLength = to - from; if(newLength < 0) throw new ArgumentException(from + " > " + to); return newLength; } public static byte[] Append(byte[] a, byte b) { if(a == null) return new byte[] { b }; int length = a.Length; byte[] result = new byte[length + 1]; Array.Copy(a, 0, result, 0, length); result[length] = b; return result; } public static short[] Append(short[] a, short b) { if(a == null) return new short[] { b }; int length = a.Length; short[] result = new short[length + 1]; Array.Copy(a, 0, result, 0, length); result[length] = b; return result; } public static int[] Append(int[] a, int b) { if(a == null) return new int[] { b }; int length = a.Length; int[] result = new int[length + 1]; Array.Copy(a, 0, result, 0, length); result[length] = b; return result; } public static byte[] Concatenate(byte[] a, byte[] b) { if(a == null) return Clone(b); if(b == null) return Clone(a); byte[] rv = new byte[a.Length + b.Length]; Array.Copy(a, 0, rv, 0, a.Length); Array.Copy(b, 0, rv, a.Length, b.Length); return rv; } public static byte[] ConcatenateAll(params byte[][] vs) { byte[][] nonNull = new byte[vs.Length][]; int count = 0; int totalLength = 0; for(int i = 0; i < vs.Length; ++i) { byte[] v = vs[i]; if(v != null) { nonNull[count++] = v; totalLength += v.Length; } } byte[] result = new byte[totalLength]; int pos = 0; for(int j = 0; j < count; ++j) { byte[] v = nonNull[j]; Array.Copy(v, 0, result, pos, v.Length); pos += v.Length; } return result; } public static int[] Concatenate(int[] a, int[] b) { if(a == null) return Clone(b); if(b == null) return Clone(a); int[] rv = new int[a.Length + b.Length]; Array.Copy(a, 0, rv, 0, a.Length); Array.Copy(b, 0, rv, a.Length, b.Length); return rv; } public static byte[] Prepend(byte[] a, byte b) { if(a == null) return new byte[] { b }; int length = a.Length; byte[] result = new byte[length + 1]; Array.Copy(a, 0, result, 1, length); result[0] = b; return result; } public static short[] Prepend(short[] a, short b) { if(a == null) return new short[] { b }; int length = a.Length; short[] result = new short[length + 1]; Array.Copy(a, 0, result, 1, length); result[0] = b; return result; } public static int[] Prepend(int[] a, int b) { if(a == null) return new int[] { b }; int length = a.Length; int[] result = new int[length + 1]; Array.Copy(a, 0, result, 1, length); result[0] = b; return result; } public static byte[] Reverse(byte[] a) { if(a == null) return null; int p1 = 0, p2 = a.Length; byte[] result = new byte[p2]; while(--p2 >= 0) { result[p2] = a[p1++]; } return result; } public static int[] Reverse(int[] a) { if(a == null) return null; int p1 = 0, p2 = a.Length; int[] result = new int[p2]; while(--p2 >= 0) { result[p2] = a[p1++]; } return result; } } }
using System.IO.Pipelines; using System.Net.Sockets; using System.Threading.Channels; namespace Tmds.DBus.Protocol; #pragma warning disable VSTHRD100 // Avoid "async void" methods class MessageStream : IMessageStream { private static readonly ReadOnlyMemory<byte> OneByteArray = new[] { (byte)0 }; private readonly Socket _socket; private readonly UnixFdCollection? _fdCollection; private bool _supportsFdPassing; // Messages going out. private readonly ChannelReader<MessageBuffer> _messageReader; private readonly ChannelWriter<MessageBuffer> _messageWriter; // Bytes coming in. private readonly PipeWriter _pipeWriter; private readonly PipeReader _pipeReader; private Exception? _completionException; public MessageStream(Socket socket) { _socket = socket; Channel<MessageBuffer> channel = Channel.CreateUnbounded<MessageBuffer>(); // TODO: review options. _messageReader = channel.Reader; _messageWriter = channel.Writer; var pipe = new Pipe(); // TODO: review options. _pipeReader = pipe.Reader; _pipeWriter = pipe.Writer; if (_supportsFdPassing) { _fdCollection = new(); } } private async void ReadFromSocketIntoPipe() { var writer = _pipeWriter; Exception? exception = null; try { while (true) { Memory<byte> memory = writer.GetMemory(1024); int bytesRead = await _socket.ReceiveAsync(memory, _fdCollection).ConfigureAwait(false); if (bytesRead == 0) { throw new IOException("Connection closed by peer"); } writer.Advance(bytesRead); await writer.FlushAsync().ConfigureAwait(false); } } catch (Exception e) { exception = e; } writer.Complete(exception); } private async void ReadMessagesIntoSocket() { while (true) { if (!await _messageReader.WaitToReadAsync().ConfigureAwait(false)) { // No more messages will be coming. return; } var message = await _messageReader.ReadAsync().ConfigureAwait(false); try { IReadOnlyList<SafeHandle>? handles = _supportsFdPassing ? message.Handles : null; var buffer = message.AsReadOnlySequence(); if (buffer.IsSingleSegment) { await _socket.SendAsync(buffer.First, handles).ConfigureAwait(false); } else { SequencePosition position = buffer.Start; while (buffer.TryGet(ref position, out ReadOnlyMemory<byte> memory)) { await _socket.SendAsync(buffer.First, handles).ConfigureAwait(false); handles = null; } } } catch (Exception exception) { Close(exception); return; } finally { message.ReturnToPool(); } } } public async void ReceiveMessages<T>(IMessageStream.MessageReceivedHandler<T> handler, T state) { var reader = _pipeReader; try { while (true) { ReadResult result = await reader.ReadAsync().ConfigureAwait(false); ReadOnlySequence<byte> buffer = result.Buffer; ReadMessages(ref buffer, _fdCollection, handler, state); reader.AdvanceTo(buffer.Start, buffer.End); } } catch (Exception exception) { exception = CloseCore(exception); OnException(exception, handler, state); } finally { _fdCollection?.Dispose(); } static void ReadMessages<TState>(ref ReadOnlySequence<byte> buffer, UnixFdCollection? fdCollection, IMessageStream.MessageReceivedHandler<TState> handler, TState state) { while (Message.TryReadMessage(ref buffer, out Message message, fdCollection)) { handler(closeReason: null, in message, state); } } static void OnException(Exception exception, IMessageStream.MessageReceivedHandler<T> handler, T state) { Message message = default; handler(exception, in message, state); } } private struct AuthenticationResult { public bool IsAuthenticated; public bool SupportsFdPassing; public Guid Guid; } public async ValueTask DoClientAuthAsync(Guid guid, string? userId, bool supportsFdPassing) { ReadFromSocketIntoPipe(); // send 1 byte await _socket.SendAsync(OneByteArray, SocketFlags.None).ConfigureAwait(false); // auth var authenticationResult = await SendAuthCommandsAsync(userId, supportsFdPassing).ConfigureAwait(false); _supportsFdPassing = authenticationResult.SupportsFdPassing; if (guid != Guid.Empty) { if (guid != authenticationResult.Guid) { throw new ConnectException("Authentication failure: Unexpected GUID"); } } ReadMessagesIntoSocket(); } private async ValueTask<AuthenticationResult> SendAuthCommandsAsync(string? userId, bool supportsFdPassing) { AuthenticationResult result; if (userId is not null) { string command = CreateAuthExternalCommand(userId); result = await SendAuthCommandAsync(command, supportsFdPassing).ConfigureAwait(false); if (result.IsAuthenticated) { return result; } } result = await SendAuthCommandAsync("AUTH ANONYMOUS\r\n", supportsFdPassing).ConfigureAwait(false); if (result.IsAuthenticated) { return result; } throw new ConnectException("Authentication failure"); } private static string CreateAuthExternalCommand(string userId) { const string AuthExternal = "AUTH EXTERNAL "; const string hexchars = "0123456789abcdef"; #if NETSTANDARD2_0 StringBuilder sb = new(); sb.Append(AuthExternal); for (int i = 0; i < userId.Length; i++) { byte b = (byte)userId[i]; sb.Append(hexchars[(int)(b >> 4)]); sb.Append(hexchars[(int)(b & 0xF)]); } sb.Append("\r\n"); return sb.ToString(); #else return string.Create<string>( length: AuthExternal.Length + userId.Length * 2 + 2, userId, static (Span<char> span, string userId) => { AuthExternal.AsSpan().CopyTo(span); span = span.Slice(AuthExternal.Length); for (int i = 0; i < userId.Length; i++) { byte b = (byte)userId[i]; span[i * 2] = hexchars[(int)(b >> 4)]; span[i * 2 + 1] = hexchars[(int)(b & 0xF)]; } span = span.Slice(userId.Length * 2); span[0] = '\r'; span[1] = '\n'; }); #endif } private async ValueTask<AuthenticationResult> SendAuthCommandAsync(string command, bool supportsFdPassing) { byte[] lineBuffer = ArrayPool<byte>.Shared.Rent(512); try { AuthenticationResult result = default(AuthenticationResult); await WriteAsync(command, lineBuffer).ConfigureAwait(false); int lineLength = await ReadLineAsync(lineBuffer).ConfigureAwait(false); if (StartsWithAscii(lineBuffer, lineLength, "OK")) { result.IsAuthenticated = true; result.Guid = ParseGuid(lineBuffer, lineLength); if (supportsFdPassing) { await WriteAsync("NEGOTIATE_UNIX_FD\r\n", lineBuffer).ConfigureAwait(false); lineLength = await ReadLineAsync(lineBuffer).ConfigureAwait(false); result.SupportsFdPassing = StartsWithAscii(lineBuffer, lineLength, "AGREE_UNIX_FD"); } await WriteAsync("BEGIN\r\n", lineBuffer).ConfigureAwait(false); return result; } else if (StartsWithAscii(lineBuffer, lineLength, "REJECTED")) { return result; } else { await WriteAsync("ERROR\r\n", lineBuffer).ConfigureAwait(false); return result; } } finally { ArrayPool<byte>.Shared.Return(lineBuffer); } static bool StartsWithAscii(byte[] line, int length, string expected) { if (length < expected.Length) { return false; } for (int i = 0; i < expected.Length; i++) { if (line[i] != expected[i]) { return false; } } return true; } static Guid ParseGuid(byte[] line, int length) { Span<byte> span = new Span<byte>(line, 0, length); int spaceIndex = span.IndexOf((byte)' '); if (spaceIndex == -1) { return Guid.Empty; } span = span.Slice(spaceIndex + 1); spaceIndex = span.IndexOf((byte)' '); if (spaceIndex != -1) { span = span.Slice(0, spaceIndex); } Span<char> charBuffer = stackalloc char[span.Length]; // TODO: check length for (int i = 0; i < span.Length; i++) { // TODO: validate char charBuffer[i] = (char)span[i]; } #if NETSTANDARD2_0 return Guid.ParseExact(charBuffer.AsString(), "N"); #else return Guid.ParseExact(charBuffer, "N"); #endif } } private async ValueTask WriteAsync(string message, Memory<byte> lineBuffer) { int length = Encoding.ASCII.GetBytes(message.AsSpan(), lineBuffer.Span); lineBuffer = lineBuffer.Slice(0, length); await _socket.SendAsync(lineBuffer, SocketFlags.None).ConfigureAwait(false); } private async ValueTask<int> ReadLineAsync(Memory<byte> lineBuffer) { var reader = _pipeReader; while (true) { ReadResult result = await reader.ReadAsync().ConfigureAwait(false); ReadOnlySequence<byte> buffer = result.Buffer; // TODO: check length. SequencePosition? position = buffer.PositionOf((byte)'\n'); if (!position.HasValue) { reader.AdvanceTo(buffer.Start, buffer.End); continue; } int length = CopyBuffer(buffer.Slice(0, position.Value), lineBuffer); reader.AdvanceTo(buffer.GetPosition(1, position.Value)); return length; } int CopyBuffer(ReadOnlySequence<byte> src, Memory<byte> dst) { Span<byte> span = dst.Span; src.CopyTo(span); span = span.Slice(0, (int)src.Length); if (!span.EndsWith((ReadOnlySpan<byte>)new byte[] { (byte)'\r' })) { throw new ProtocolException("Authentication messages from server must end with '\\r\\n'."); } if (span.Length == 1) { throw new ProtocolException("Received empty authentication message from server."); } return span.Length - 1; } } public async ValueTask<bool> TrySendMessageAsync(MessageBuffer message) { while (await _messageWriter.WaitToWriteAsync().ConfigureAwait(false)) { if (_messageWriter.TryWrite(message)) return true; } return false; } public void Close(Exception closeReason) => CloseCore(closeReason); private Exception CloseCore(Exception closeReason) { Exception? previous = Interlocked.CompareExchange(ref _completionException, closeReason, null); if (previous is null) { _socket?.Dispose(); _messageWriter.Complete(); } return previous ?? closeReason; } }
using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using FluentNHibernate.Automapping.TestFixtures; using FluentNHibernate.Conventions; using FluentNHibernate.Conventions.Inspections; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.Collections; using FluentNHibernate.Utils; using NUnit.Framework; namespace FluentNHibernate.Testing.ConventionsTests.Inspection { [TestFixture, Category("Inspection DSL")] public class ManyToManyInspectorMapsToManyToManyMapping { private ManyToManyMapping mapping; private IManyToManyInspector inspector; [SetUp] public void CreateDsl() { mapping = new ManyToManyMapping(); inspector = new ManyToManyInspector(mapping); } [Test] public void ChildTypeMapped() { mapping.ChildType = typeof(ExampleClass); inspector.ChildType.ShouldEqual(typeof(ExampleClass)); } [Test] public void ChildTypeIsSet() { mapping.ChildType = typeof(ExampleClass); inspector.IsSet(Prop(x => x.ChildType)) .ShouldBeTrue(); } [Test] public void ChildTypeIsNotSet() { inspector.IsSet(Prop(x => x.ChildType)) .ShouldBeFalse(); } [Test] public void ClassMapped() { mapping.Class = new TypeReference(typeof(ExampleClass)); inspector.Class.ShouldEqual(new TypeReference(typeof(ExampleClass))); } [Test] public void ClassIsSet() { mapping.Class = new TypeReference(typeof(ExampleClass)); inspector.IsSet(Prop(x => x.Class)) .ShouldBeTrue(); } [Test] public void ClassIsNotSet() { inspector.IsSet(Prop(x => x.Class)) .ShouldBeFalse(); } [Test] public void ColumnsCollectionHasSameCountAsMapping() { mapping.AddColumn(new ColumnMapping()); inspector.Columns.Count().ShouldEqual(1); } [Test] public void ColumnsCollectionOfInspectors() { mapping.AddColumn(new ColumnMapping()); inspector.Columns.First().ShouldBeOfType<IColumnInspector>(); } [Test] public void ColumnsCollectionIsEmpty() { inspector.Columns.IsEmpty().ShouldBeTrue(); } [Test] public void FetchMapped() { mapping.Fetch = "join"; inspector.Fetch.ShouldEqual(Fetch.Join); } [Test] public void FetchIsSet() { mapping.Fetch = "join"; inspector.IsSet(Prop(x => x.Fetch)) .ShouldBeTrue(); } [Test] public void FetchIsNotSet() { inspector.IsSet(Prop(x => x.Fetch)) .ShouldBeFalse(); } [Test] public void ForeignKeyMapped() { mapping.ForeignKey = "key"; inspector.ForeignKey.ShouldEqual("key"); } [Test] public void ForeignKeyIsSet() { mapping.ForeignKey = "key"; inspector.IsSet(Prop(x => x.ForeignKey)) .ShouldBeTrue(); } [Test] public void ForeignKeyIsNotSet() { inspector.IsSet(Prop(x => x.ForeignKey)) .ShouldBeFalse(); } [Test] public void LazyMapped() { mapping.Lazy = true; inspector.LazyLoad.ShouldEqual(true); } [Test] public void LazyIsSet() { mapping.Lazy = true; inspector.IsSet(Prop(x => x.LazyLoad)) .ShouldBeTrue(); } [Test] public void LazyIsNotSet() { inspector.IsSet(Prop(x => x.LazyLoad)) .ShouldBeFalse(); } [Test] public void NotFoundMapped() { mapping.NotFound = "exception"; inspector.NotFound.ShouldEqual(NotFound.Exception); } [Test] public void NotFoundIsSet() { mapping.NotFound = "exception"; inspector.IsSet(Prop(x => x.NotFound)) .ShouldBeTrue(); } [Test] public void NotFoundIsNotSet() { inspector.IsSet(Prop(x => x.NotFound)) .ShouldBeFalse(); } [Test] public void ParentTypeMapped() { mapping.ParentType = typeof(ExampleClass); inspector.ParentType.ShouldEqual(typeof(ExampleClass)); } [Test] public void ParentTypeIsSet() { mapping.ParentType = typeof(ExampleClass); inspector.IsSet(Prop(x => x.ParentType)) .ShouldBeTrue(); } [Test] public void ParentTypeIsNotSet() { inspector.IsSet(Prop(x => x.ParentType)) .ShouldBeFalse(); } [Test] public void WhereMapped() { mapping.Where = "x = 1"; inspector.Where.ShouldEqual("x = 1"); } [Test] public void WhereIsSet() { mapping.Where = "x = 1"; inspector.IsSet(Prop(x => x.Where)) .ShouldBeTrue(); } [Test] public void WhereIsNotSet() { inspector.IsSet(Prop(x => x.Where)) .ShouldBeFalse(); } #region Helpers private PropertyInfo Prop(Expression<Func<IManyToManyInspector, object>> propertyExpression) { return ReflectionHelper.GetProperty(propertyExpression); } #endregion } }
using System; using System.Drawing; using System.Security.Principal; using Microsoft.Deployment.WindowsInstaller; using WixSharp.CommonTasks; namespace WixSharp.UI.Forms { /// <summary> /// The standard Installation Progress dialog /// </summary> public partial class ProgressDialog : ManagedForm, IManagedDialog, IProgressDialog // change ManagedForm->Form if you want to show it in designer { /// <summary> /// Initializes a new instance of the <see cref="ProgressDialog"/> class. /// </summary> public ProgressDialog() { InitializeComponent(); dialogText.MakeTransparentOn(banner); showWaitPromptTimer = new System.Windows.Forms.Timer() { Interval = 4000 }; showWaitPromptTimer.Tick += (s, e) => { this.waitPrompt.Visible = true; showWaitPromptTimer.Stop(); }; } System.Windows.Forms.Timer showWaitPromptTimer; void ProgressDialog_Load(object sender, EventArgs e) { banner.Image = Runtime.Session.GetResourceBitmap("WixUI_Bmp_Banner"); if (!WindowsIdentity.GetCurrent().IsAdmin() && Uac.IsEnabled()) { this.waitPrompt.Text = Runtime.Session.Property("UAC_WARNING"); showWaitPromptTimer.Start(); } ResetLayout(); Shell.StartExecute(); } void ResetLayout() { // The form controls are properly anchored and will be correctly resized on parent form // resizing. However the initial sizing by WinForm runtime doesn't a do good job with DPI // other than 96. Thus manual resizing is the only reliable option apart from going WPF. float ratio = (float)banner.Image.Width / (float)banner.Image.Height; topPanel.Height = (int)(banner.Width / ratio); topBorder.Top = topPanel.Height + 1; var upShift = (int)(next.Height * 2.3) - bottomPanel.Height; bottomPanel.Top -= upShift; bottomPanel.Height += upShift; var fontSize = waitPrompt.Font.Size; float scaling = 1; waitPrompt.Font = new Font(waitPrompt.Font.Name, fontSize * scaling, FontStyle.Italic); } /// <summary> /// Called when Shell is changed. It is a good place to initialize the dialog to reflect the MSI session /// (e.g. localize the view). /// </summary> protected override void OnShellChanged() { if (Runtime.Session.IsUninstalling()) { dialogText.Text = Text = "[ProgressDlgTitleRemoving]"; description.Text = "[ProgressDlgTextRemoving]"; } else if (Runtime.Session.IsRepairing()) { dialogText.Text = Text = "[ProgressDlgTextRepairing]"; description.Text = "[ProgressDlgTitleRepairing]"; } else if (Runtime.Session.IsInstalling()) { dialogText.Text = Text = "[ProgressDlgTitleInstalling]"; description.Text = "[ProgressDlgTextInstalling]"; } this.Localize(); } /// <summary> /// Processes the message. /// </summary> /// <param name="messageType">Type of the message.</param> /// <param name="messageRecord">The message record.</param> /// <param name="buttons">The buttons.</param> /// <param name="icon">The icon.</param> /// <param name="defaultButton">The default button.</param> /// <returns></returns> public override MessageResult ProcessMessage(InstallMessage messageType, Record messageRecord, MessageButtons buttons, MessageIcon icon, MessageDefaultButton defaultButton) { switch (messageType) { case InstallMessage.InstallStart: case InstallMessage.InstallEnd: { showWaitPromptTimer.Stop(); waitPrompt.Visible = false; } break; case InstallMessage.ActionStart: { try { //messageRecord[0] - is reserved for FormatString value string message = null; bool simple = true; if (simple) { /* messageRecord[2] unconditionally contains the string to display Examples: messageRecord[0] "Action 23:14:50: [1]. [2]" messageRecord[1] "InstallFiles" messageRecord[2] "Copying new files" messageRecord[3] "File: [1], Directory: [9], Size: [6]" messageRecord[0] "Action 23:15:21: [1]. [2]" messageRecord[1] "RegisterUser" messageRecord[2] "Registering user" messageRecord[3] "[1]" */ if (messageRecord.FieldCount >= 3) { message = messageRecord[2].ToString(); } } else { message = messageRecord.FormatString; if (message.IsNotEmpty()) { for (int i = 1; i < messageRecord.FieldCount; i++) { message = message.Replace("[" + i + "]", messageRecord[i].ToString()); } } else { message = messageRecord[messageRecord.FieldCount - 1].ToString(); } } if (message.IsNotEmpty()) currentAction.Text = "{0} {1}".FormatWith(currentActionLabel.Text, message); } catch { //Catch all, we don't want the installer to crash in an //attempt to process message. } } break; } return MessageResult.OK; } /// <summary> /// Called when MSI execution progress is changed. /// </summary> /// <param name="progressPercentage">The progress percentage.</param> public override void OnProgress(int progressPercentage) { progress.Value = progressPercentage; if (progressPercentage > 0) { waitPrompt.Visible = false; } } /// <summary> /// Called when MSI execution is complete. /// </summary> public override void OnExecuteComplete() { currentAction.Text = null; Shell.GoNext(); } /// <summary> /// Handles the Click event of the cancel control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param> void cancel_Click(object sender, EventArgs e) { if (Shell.IsDemoMode) Shell.GoNext(); else Shell.Cancel(); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Linq.JsonPath { internal class JPath { private readonly string _expression; public List<PathFilter> Filters { get; private set; } private int _currentIndex; public JPath(string expression) { ValidationUtils.ArgumentNotNull(expression, "expression"); _expression = expression; Filters = new List<PathFilter>(); ParseMain(); } private void ParseMain() { int currentPartStartIndex = _currentIndex; EatWhitespace(); if (_expression.Length == _currentIndex) { return; } if (_expression[_currentIndex] == '$') { if (_expression.Length == 1) { return; } // only increment position for "$." or "$[" // otherwise assume property that starts with $ char c = _expression[_currentIndex + 1]; if (c == '.' || c == '[') { _currentIndex++; currentPartStartIndex = _currentIndex; } } if (!ParsePath(Filters, currentPartStartIndex, false)) { int lastCharacterIndex = _currentIndex; EatWhitespace(); if (_currentIndex < _expression.Length) { throw new JsonException("Unexpected character while parsing path: " + _expression[lastCharacterIndex]); } } } private bool ParsePath(List<PathFilter> filters, int currentPartStartIndex, bool query) { bool scan = false; bool followingIndexer = false; bool followingDot = false; bool ended = false; while (_currentIndex < _expression.Length && !ended) { char currentChar = _expression[_currentIndex]; switch (currentChar) { case '[': case '(': if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); PathFilter filter = (scan) ? (PathFilter)new ScanFilter() { Name = member } : new FieldFilter() { Name = member }; filters.Add(filter); scan = false; } filters.Add(ParseIndexer(currentChar)); _currentIndex++; currentPartStartIndex = _currentIndex; followingIndexer = true; followingDot = false; break; case ']': case ')': ended = true; break; case ' ': //EatWhitespace(); if (_currentIndex < _expression.Length) { ended = true; } break; case '.': if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); if (member == "*") { member = null; } PathFilter filter = (scan) ? (PathFilter)new ScanFilter() { Name = member } : new FieldFilter() { Name = member }; filters.Add(filter); scan = false; } if (_currentIndex + 1 < _expression.Length && _expression[_currentIndex + 1] == '.') { scan = true; _currentIndex++; } _currentIndex++; currentPartStartIndex = _currentIndex; followingIndexer = false; followingDot = true; break; default: if (query && (currentChar == '=' || currentChar == '<' || currentChar == '!' || currentChar == '>' || currentChar == '|' || currentChar == '&')) { ended = true; } else { if (followingIndexer) { throw new JsonException("Unexpected character following indexer: " + currentChar); } _currentIndex++; } break; } } bool atPathEnd = (_currentIndex == _expression.Length); if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex).TrimEnd(); if (member == "*") { member = null; } PathFilter filter = (scan) ? (PathFilter)new ScanFilter() { Name = member } : new FieldFilter() { Name = member }; filters.Add(filter); } else { // no field name following dot in path and at end of base path/query if (followingDot && (atPathEnd || query)) { throw new JsonException("Unexpected end while parsing path."); } } return atPathEnd; } private PathFilter ParseIndexer(char indexerOpenChar) { _currentIndex++; char indexerCloseChar = (indexerOpenChar == '[') ? ']' : ')'; EnsureLength("Path ended with open indexer."); EatWhitespace(); if (_expression[_currentIndex] == '\'') { return ParseQuotedField(indexerCloseChar); } else if (_expression[_currentIndex] == '?') { return ParseQuery(indexerCloseChar); } else { return ParseArrayIndexer(indexerCloseChar); } } private PathFilter ParseArrayIndexer(char indexerCloseChar) { int start = _currentIndex; int? end = null; List<int> indexes = null; int colonCount = 0; int? startIndex = null; int? endIndex = null; int? step = null; while (_currentIndex < _expression.Length) { char currentCharacter = _expression[_currentIndex]; if (currentCharacter == ' ') { end = _currentIndex; EatWhitespace(); continue; } if (currentCharacter == indexerCloseChar) { int length = (end ?? _currentIndex) - start; if (indexes != null) { if (length == 0) { throw new JsonException("Array index expected."); } string indexer = _expression.Substring(start, length); int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); indexes.Add(index); return new ArrayMultipleIndexFilter { Indexes = indexes }; } else if (colonCount > 0) { if (length > 0) { string indexer = _expression.Substring(start, length); int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); if (colonCount == 1) { endIndex = index; } else { step = index; } } return new ArraySliceFilter { Start = startIndex, End = endIndex, Step = step }; } else { if (length == 0) { throw new JsonException("Array index expected."); } string indexer = _expression.Substring(start, length); int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); return new ArrayIndexFilter { Index = index }; } } else if (currentCharacter == ',') { int length = (end ?? _currentIndex) - start; if (length == 0) { throw new JsonException("Array index expected."); } if (indexes == null) { indexes = new List<int>(); } string indexer = _expression.Substring(start, length); indexes.Add(Convert.ToInt32(indexer, CultureInfo.InvariantCulture)); _currentIndex++; EatWhitespace(); start = _currentIndex; end = null; } else if (currentCharacter == '*') { _currentIndex++; EnsureLength("Path ended with open indexer."); EatWhitespace(); if (_expression[_currentIndex] != indexerCloseChar) { throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); } return new ArrayIndexFilter(); } else if (currentCharacter == ':') { int length = (end ?? _currentIndex) - start; if (length > 0) { string indexer = _expression.Substring(start, length); int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); if (colonCount == 0) { startIndex = index; } else if (colonCount == 1) { endIndex = index; } else { step = index; } } colonCount++; _currentIndex++; EatWhitespace(); start = _currentIndex; end = null; } else if (!char.IsDigit(currentCharacter) && currentCharacter != '-') { throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); } else { if (end != null) { throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); } _currentIndex++; } } throw new JsonException("Path ended with open indexer."); } private void EatWhitespace() { while (_currentIndex < _expression.Length) { if (_expression[_currentIndex] != ' ') { break; } _currentIndex++; } } private PathFilter ParseQuery(char indexerCloseChar) { _currentIndex++; EnsureLength("Path ended with open indexer."); if (_expression[_currentIndex] != '(') { throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]); } _currentIndex++; QueryExpression expression = ParseExpression(); _currentIndex++; EnsureLength("Path ended with open indexer."); EatWhitespace(); if (_expression[_currentIndex] != indexerCloseChar) { throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]); } return new QueryFilter { Expression = expression }; } private QueryExpression ParseExpression() { QueryExpression rootExpression = null; CompositeExpression parentExpression = null; while (_currentIndex < _expression.Length) { EatWhitespace(); if (_expression[_currentIndex] != '@') { throw new JsonException("Unexpected character while parsing path query: " + _expression[_currentIndex]); } _currentIndex++; List<PathFilter> expressionPath = new List<PathFilter>(); if (ParsePath(expressionPath, _currentIndex, true)) { throw new JsonException("Path ended with open query."); } EatWhitespace(); EnsureLength("Path ended with open query."); QueryOperator op; object value = null; if (_expression[_currentIndex] == ')' || _expression[_currentIndex] == '|' || _expression[_currentIndex] == '&') { op = QueryOperator.Exists; } else { op = ParseOperator(); EatWhitespace(); EnsureLength("Path ended with open query."); value = ParseValue(); EatWhitespace(); EnsureLength("Path ended with open query."); } BooleanQueryExpression booleanExpression = new BooleanQueryExpression { Path = expressionPath, Operator = op, Value = (op != QueryOperator.Exists) ? new JValue(value) : null }; if (_expression[_currentIndex] == ')') { if (parentExpression != null) { parentExpression.Expressions.Add(booleanExpression); return rootExpression; } return booleanExpression; } if (_expression[_currentIndex] == '&' && Match("&&")) { if (parentExpression == null || parentExpression.Operator != QueryOperator.And) { CompositeExpression andExpression = new CompositeExpression { Operator = QueryOperator.And }; if (parentExpression != null) { parentExpression.Expressions.Add(andExpression); } parentExpression = andExpression; if (rootExpression == null) { rootExpression = parentExpression; } } parentExpression.Expressions.Add(booleanExpression); } if (_expression[_currentIndex] == '|' && Match("||")) { if (parentExpression == null || parentExpression.Operator != QueryOperator.Or) { CompositeExpression orExpression = new CompositeExpression { Operator = QueryOperator.Or }; if (parentExpression != null) { parentExpression.Expressions.Add(orExpression); } parentExpression = orExpression; if (rootExpression == null) { rootExpression = parentExpression; } } parentExpression.Expressions.Add(booleanExpression); } } throw new JsonException("Path ended with open query."); } private object ParseValue() { char currentChar = _expression[_currentIndex]; if (currentChar == '\'') { return ReadQuotedString(); } else if (char.IsDigit(currentChar) || currentChar == '-') { StringBuilder sb = new StringBuilder(); sb.Append(currentChar); _currentIndex++; while (_currentIndex < _expression.Length) { currentChar = _expression[_currentIndex]; if (currentChar == ' ' || currentChar == ')') { string numberText = sb.ToString(); if (numberText.IndexOfAny(new char[] { '.', 'E', 'e' }) != -1) { double d; if (double.TryParse(numberText, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d)) { return d; } else { throw new JsonException("Could not read query value."); } } else { long l; if (long.TryParse(numberText, NumberStyles.Integer, CultureInfo.InvariantCulture, out l)) { return l; } else { throw new JsonException("Could not read query value."); } } } else { sb.Append(currentChar); _currentIndex++; } } } else if (currentChar == 't') { if (Match("true")) { return true; } } else if (currentChar == 'f') { if (Match("false")) { return false; } } else if (currentChar == 'n') { if (Match("null")) { return null; } } throw new JsonException("Could not read query value."); } private string ReadQuotedString() { StringBuilder sb = new StringBuilder(); _currentIndex++; while (_currentIndex < _expression.Length) { char currentChar = _expression[_currentIndex]; if (currentChar == '\\' && _currentIndex + 1 < _expression.Length) { _currentIndex++; if (_expression[_currentIndex] == '\'') { sb.Append('\''); } else if (_expression[_currentIndex] == '\\') { sb.Append('\\'); } else { throw new JsonException(@"Unknown escape chracter: \" + _expression[_currentIndex]); } _currentIndex++; } else if (currentChar == '\'') { _currentIndex++; { return sb.ToString(); } } else { _currentIndex++; sb.Append(currentChar); } } throw new JsonException("Path ended with an open string."); } private bool Match(string s) { int currentPosition = _currentIndex; foreach (char c in s) { if (currentPosition < _expression.Length && _expression[currentPosition] == c) { currentPosition++; } else { return false; } } _currentIndex = currentPosition; return true; } private QueryOperator ParseOperator() { if (_currentIndex + 1 >= _expression.Length) { throw new JsonException("Path ended with open query."); } if (Match("==")) { return QueryOperator.Equals; } if (Match("!=") || Match("<>")) { return QueryOperator.NotEquals; } if (Match("<=")) { return QueryOperator.LessThanOrEquals; } if (Match("<")) { return QueryOperator.LessThan; } if (Match(">=")) { return QueryOperator.GreaterThanOrEquals; } if (Match(">")) { return QueryOperator.GreaterThan; } throw new JsonException("Could not read query operator."); } private PathFilter ParseQuotedField(char indexerCloseChar) { List<string> fields = null; while (_currentIndex < _expression.Length) { string field = ReadQuotedString(); EatWhitespace(); EnsureLength("Path ended with open indexer."); if (_expression[_currentIndex] == indexerCloseChar) { if (fields != null) { fields.Add(field); return new FieldMultipleFilter { Names = fields }; } else { return new FieldFilter { Name = field }; } } else if (_expression[_currentIndex] == ',') { _currentIndex++; EatWhitespace(); if (fields == null) { fields = new List<string>(); } fields.Add(field); } else { throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]); } } throw new JsonException("Path ended with open indexer."); } private void EnsureLength(string message) { if (_currentIndex >= _expression.Length) { throw new JsonException(message); } } internal IEnumerable<JToken> Evaluate(JToken t, bool errorWhenNoMatch) { return Evaluate(Filters, t, errorWhenNoMatch); } internal static IEnumerable<JToken> Evaluate(List<PathFilter> filters, JToken t, bool errorWhenNoMatch) { IEnumerable<JToken> current = new[] { t }; foreach (PathFilter filter in filters) { current = filter.ExecuteFilter(current, errorWhenNoMatch); } return current; } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoad.Business.ERLevel { /// <summary> /// A06_Country (editable child object).<br/> /// This is a generated base class of <see cref="A06_Country"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="A07_RegionObjects"/> of type <see cref="A07_RegionColl"/> (1:M relation to <see cref="A08_Region"/>)<br/> /// This class is an item of <see cref="A05_CountryColl"/> collection. /// </remarks> [Serializable] public partial class A06_Country : BusinessBase<A06_Country> { #region Static Fields private static int _lastID; #endregion #region State Fields [NotUndoable] private byte[] _rowVersion = new byte[] {}; [NotUndoable] [NonSerialized] internal int parent_SubContinent_ID = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Country_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Country_IDProperty = RegisterProperty<int>(p => p.Country_ID, "Country ID"); /// <summary> /// Gets the Country ID. /// </summary> /// <value>The Country ID.</value> public int Country_ID { get { return GetProperty(Country_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Country_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Country_NameProperty = RegisterProperty<string>(p => p.Country_Name, "Country Name"); /// <summary> /// Gets or sets the Country Name. /// </summary> /// <value>The Country Name.</value> public string Country_Name { get { return GetProperty(Country_NameProperty); } set { SetProperty(Country_NameProperty, value); } } /// <summary> /// Maintains metadata about <see cref="ParentSubContinentID"/> property. /// </summary> public static readonly PropertyInfo<int> ParentSubContinentIDProperty = RegisterProperty<int>(p => p.ParentSubContinentID, "Parent Sub Continent ID"); /// <summary> /// Gets or sets the Parent Sub Continent ID. /// </summary> /// <value>The Parent Sub Continent ID.</value> public int ParentSubContinentID { get { return GetProperty(ParentSubContinentIDProperty); } set { SetProperty(ParentSubContinentIDProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="A07_Country_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<A07_Country_Child> A07_Country_SingleObjectProperty = RegisterProperty<A07_Country_Child>(p => p.A07_Country_SingleObject, "A07 Country Single Object", RelationshipTypes.Child); /// <summary> /// Gets the A07 Country Single Object ("parent load" child property). /// </summary> /// <value>The A07 Country Single Object.</value> public A07_Country_Child A07_Country_SingleObject { get { return GetProperty(A07_Country_SingleObjectProperty); } private set { LoadProperty(A07_Country_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="A07_Country_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<A07_Country_ReChild> A07_Country_ASingleObjectProperty = RegisterProperty<A07_Country_ReChild>(p => p.A07_Country_ASingleObject, "A07 Country ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the A07 Country ASingle Object ("parent load" child property). /// </summary> /// <value>The A07 Country ASingle Object.</value> public A07_Country_ReChild A07_Country_ASingleObject { get { return GetProperty(A07_Country_ASingleObjectProperty); } private set { LoadProperty(A07_Country_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="A07_RegionObjects"/> property. /// </summary> public static readonly PropertyInfo<A07_RegionColl> A07_RegionObjectsProperty = RegisterProperty<A07_RegionColl>(p => p.A07_RegionObjects, "A07 Region Objects", RelationshipTypes.Child); /// <summary> /// Gets the A07 Region Objects ("parent load" child property). /// </summary> /// <value>The A07 Region Objects.</value> public A07_RegionColl A07_RegionObjects { get { return GetProperty(A07_RegionObjectsProperty); } private set { LoadProperty(A07_RegionObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="A06_Country"/> object. /// </summary> /// <returns>A reference to the created <see cref="A06_Country"/> object.</returns> internal static A06_Country NewA06_Country() { return DataPortal.CreateChild<A06_Country>(); } /// <summary> /// Factory method. Loads a <see cref="A06_Country"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="A06_Country"/> object.</returns> internal static A06_Country GetA06_Country(SafeDataReader dr) { A06_Country obj = new A06_Country(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.LoadProperty(A07_RegionObjectsProperty, A07_RegionColl.NewA07_RegionColl()); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="A06_Country"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public A06_Country() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="A06_Country"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Country_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(A07_Country_SingleObjectProperty, DataPortal.CreateChild<A07_Country_Child>()); LoadProperty(A07_Country_ASingleObjectProperty, DataPortal.CreateChild<A07_Country_ReChild>()); LoadProperty(A07_RegionObjectsProperty, DataPortal.CreateChild<A07_RegionColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="A06_Country"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Country_IDProperty, dr.GetInt32("Country_ID")); LoadProperty(Country_NameProperty, dr.GetString("Country_Name")); LoadProperty(ParentSubContinentIDProperty, dr.GetInt32("Parent_SubContinent_ID")); _rowVersion = dr.GetValue("RowVersion") as byte[]; // parent properties parent_SubContinent_ID = dr.GetInt32("Parent_SubContinent_ID"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child <see cref="A07_Country_Child"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(A07_Country_Child child) { LoadProperty(A07_Country_SingleObjectProperty, child); } /// <summary> /// Loads child <see cref="A07_Country_ReChild"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(A07_Country_ReChild child) { LoadProperty(A07_Country_ASingleObjectProperty, child); } /// <summary> /// Inserts a new <see cref="A06_Country"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(A04_SubContinent parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddA06_Country", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Parent_SubContinent_ID", parent.SubContinent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@Country_Name", ReadProperty(Country_NameProperty)).DbType = DbType.String; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(Country_IDProperty, (int) cmd.Parameters["@Country_ID"].Value); _rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value; } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="A06_Country"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateA06_Country", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Country_Name", ReadProperty(Country_NameProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@Parent_SubContinent_ID", ReadProperty(ParentSubContinentIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@RowVersion", _rowVersion).DbType = DbType.Binary; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); _rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value; } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="A06_Country"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("DeleteA06_Country", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(A07_Country_SingleObjectProperty, DataPortal.CreateChild<A07_Country_Child>()); LoadProperty(A07_Country_ASingleObjectProperty, DataPortal.CreateChild<A07_Country_ReChild>()); LoadProperty(A07_RegionObjectsProperty, DataPortal.CreateChild<A07_RegionColl>()); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace Hydra.Framework.Mapping.Gps.NMEA { // // ********************************************************************** /// <summary> /// Global Positioning System Fix Data /// </summary> // ********************************************************************** // public class GPGGA { #region PRivate Member Variables // // ********************************************************************** /// <summary> /// Time of Fix /// </summary> // ********************************************************************** // private TimeSpan m_TimeOfFix; // // ********************************************************************** /// <summary> /// Coordinate Position /// </summary> // ********************************************************************** // private Coordinate m_Position; // // ********************************************************************** /// <summary> /// Fix Quality /// </summary> // ********************************************************************** // private FixQualityEnum m_FixQuality; // // ********************************************************************** /// <summary> /// Number of Satelites /// </summary> // ********************************************************************** // private byte m_NoOfSats; // // ********************************************************************** /// <summary> /// Altitude /// </summary> // ********************************************************************** // private double m_Altitude; // // ********************************************************************** /// <summary> /// Altitude Units /// </summary> // ********************************************************************** // private char m_AltitudeUnits; // // ********************************************************************** /// <summary> /// Dilution /// </summary> // ********************************************************************** // private double m_Dilution; // // ********************************************************************** /// <summary> /// Height /// </summary> // ********************************************************************** // private double m_HeightOfGeoid; // // ********************************************************************** /// <summary> /// GPS Update /// </summary> // ********************************************************************** // private int m_DGPSUpdate; // // ********************************************************************** /// <summary> /// GPS Station ID /// </summary> // ********************************************************************** // private string m_DGPSStationID; #endregion #region Constructors // // ********************************************************************** /// <summary> /// Initializes the NMEA Global Positioning System Fix Data /// </summary> // ********************************************************************** // public GPGGA() { m_Position = new Coordinate(); } // // ********************************************************************** /// <summary> /// Initializes the NMEA Global Positioning System Fix Data and parses an NMEA sentence /// </summary> /// <param name="NMEAsentence">The NME asentence.</param> // ********************************************************************** // public GPGGA(string NMEAsentence) { try { if (NMEAsentence.IndexOf('*') > 0) NMEAsentence = NMEAsentence.Substring(0, NMEAsentence.IndexOf('*')); // // Split into an array of strings. // string[] split = NMEAsentence.Split(new Char[] { ',' }); if (split[1].Length >= 6) m_TimeOfFix = new TimeSpan(GPSHandler.intTryParse(split[1].Substring(0, 2)), GPSHandler.intTryParse(split[1].Substring(2, 2)), GPSHandler.intTryParse(split[1].Substring(4, 2))); m_Position = new Coordinate(GPSHandler.GPSToDecimalDegrees(split[4], split[5]), GPSHandler.GPSToDecimalDegrees(split[2], split[3])); if (split[6] == "1") m_FixQuality = FixQualityEnum.GPS; else if (split[6] == "2") m_FixQuality = FixQualityEnum.DGPS; else m_FixQuality = FixQualityEnum.Invalid; m_NoOfSats = Convert.ToByte(split[7]); GPSHandler.dblTryParse(split[8], out m_Dilution); GPSHandler.dblTryParse(split[9], out m_Altitude); m_AltitudeUnits = split[10][0]; GPSHandler.dblTryParse(split[11], out m_HeightOfGeoid); GPSHandler.intTryParse(split[13], out m_DGPSUpdate); m_DGPSStationID = split[14]; } catch { } } #endregion #region Properties // // ********************************************************************** /// <summary> /// time of fix (hhmmss). /// </summary> /// <value>The time of fix.</value> // ********************************************************************** // public TimeSpan TimeOfFix { get { return m_TimeOfFix; } set { m_TimeOfFix = value; } } // // ********************************************************************** /// <summary> /// Coordinate of recieved position /// </summary> /// <value>The position.</value> // ********************************************************************** // public Coordinate Position { get { return m_Position; } set { m_Position = value; } } // // ********************************************************************** /// <summary> /// Fix quality (0=invalid, 1=GPS fix, 2=DGPS fix) /// </summary> /// <value>The fix quality.</value> // ********************************************************************** // public FixQualityEnum FixQuality { get { return m_FixQuality; } internal set { m_FixQuality = value; } } // // ********************************************************************** /// <summary> /// number of satellites being tracked. /// </summary> /// <value>The no of sats.</value> // ********************************************************************** // public byte NoOfSats { get { return m_NoOfSats; } set { m_NoOfSats = value; } } // // ********************************************************************** /// <summary> /// Altitude above sea level. /// </summary> /// <value>The altitude.</value> // ********************************************************************** // public double Altitude { get { return m_Altitude; } set { m_Altitude = value; } } // // ********************************************************************** /// <summary> /// Altitude Units - M (meters). /// </summary> /// <value>The altitude units.</value> // ********************************************************************** // public char AltitudeUnits { get { return m_AltitudeUnits; } set { m_AltitudeUnits = value; } } // // ********************************************************************** /// <summary> /// Horizontal dilution of position (HDOP). /// </summary> /// <value>The dilution.</value> // ********************************************************************** // public double Dilution { get { return m_Dilution; } set { m_Dilution = value; } } // // ********************************************************************** /// <summary> /// Height of geoid (mean sea level) above WGS84 ellipsoid. /// </summary> /// <value>The height of geoid.</value> // ********************************************************************** // public double HeightOfGeoid { get { return m_HeightOfGeoid; } set { m_HeightOfGeoid = value; } } // // ********************************************************************** /// <summary> /// Time in seconds since last DGPS update. /// </summary> /// <value>The DGPS update.</value> // ********************************************************************** // public int DGPSUpdate { get { return m_DGPSUpdate; } set { m_DGPSUpdate = value; } } // // ********************************************************************** /// <summary> /// DGPS station ID number. /// </summary> /// <value>The DGPS station ID.</value> // ********************************************************************** // public string DGPSStationID { get { return m_DGPSStationID; } set { m_DGPSStationID = value; } } #endregion } }
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 HackathonBackend.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.IO; using System.Runtime.InteropServices; using SharpDX.Mathematics.Interop; namespace SharpDX.Direct3D9 { public partial class CubeTexture { /// <summary> /// Initializes a new instance of the <see cref="CubeTexture"/> class. /// </summary> /// <param name="device">The device.</param> /// <param name="edgeLength">Length of the edge.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> public CubeTexture(Device device, int edgeLength, int levelCount, Usage usage, Format format, Pool pool = Pool.Managed) : base(IntPtr.Zero) { device.CreateCubeTexture(edgeLength, levelCount, (int)usage, format, pool, this, IntPtr.Zero); } /// <summary> /// Initializes a new instance of the <see cref="CubeTexture"/> class. /// </summary> /// <param name="device">The device.</param> /// <param name="edgeLength">Length of the edge.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="sharedHandle">The shared handle.</param> public CubeTexture(Device device, int edgeLength, int levelCount, Usage usage, Format format, Pool pool, ref IntPtr sharedHandle) : base(IntPtr.Zero) { unsafe { fixed (void* pSharedHandle = &sharedHandle) device.CreateCubeTexture(edgeLength, levelCount, (int)usage, format, pool, this, (IntPtr)pSharedHandle); } } /// <summary> /// Checks texture-creation parameters. /// </summary> /// <param name="device">Device associated with the texture.</param> /// <param name="size">Requested size of the texture. Null if </param> /// <param name="mipLevelCount">Requested number of mipmap levels for the texture.</param> /// <param name="usage">The requested usage for the texture.</param> /// <param name="format">Requested format for the texture.</param> /// <param name="pool">Memory class where the resource will be placed.</param> /// <returns>A value type containing the proposed values to pass to the texture creation functions.</returns> /// <unmanaged>HRESULT D3DXCheckCubeTextureRequirements([In] IDirect3DDevice9* pDevice,[InOut] unsigned int* pSize,[InOut] unsigned int* pNumMipLevels,[In] unsigned int Usage,[InOut] D3DFORMAT* pFormat,[In] D3DPOOL Pool)</unmanaged> public static CubeTextureRequirements CheckRequirements(Device device, int size, int mipLevelCount, Usage usage, Format format, Pool pool) { var result = new CubeTextureRequirements { Size = size, MipLevelCount = mipLevelCount, Format = format }; D3DX9.CheckCubeTextureRequirements(device, ref result.Size, ref result.MipLevelCount, (int)usage, ref result.Format, pool); return result; } /// <summary> /// Uses a user-provided function to fill each texel of each mip level of a given cube texture. /// </summary> /// <param name="callback">A function that is used to fill the texture.</param> /// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns> public void Fill(Fill3DCallback callback) { var handle = GCHandle.Alloc(callback); try { D3DX9.FillCubeTexture(this, FillCallbackHelper.Native3DCallbackPtr, GCHandle.ToIntPtr(handle)); } finally { handle.Free(); } } /// <summary> /// Uses a compiled high-level shader language (HLSL) function to fill each texel of each mipmap level of a texture. /// </summary> /// <param name="shader">A texture shader object that is used to fill the texture.</param> /// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns> public void Fill(TextureShader shader) { D3DX9.FillCubeTextureTX(this, shader); } /// <summary> /// Locks a rectangle on a cube texture resource. /// </summary> /// <param name="faceType">Type of the face.</param> /// <param name="level">The level.</param> /// <param name="flags">The flags.</param> /// <returns> /// A <see cref="DataRectangle"/> describing the region locked. /// </returns> /// <unmanaged>HRESULT IDirect3DCubeTexture9::LockRect([In] D3DCUBEMAP_FACES FaceType,[In] unsigned int Level,[In] D3DLOCKED_RECT* pLockedRect,[In] const void* pRect,[In] D3DLOCK Flags)</unmanaged> public DataRectangle LockRectangle(SharpDX.Direct3D9.CubeMapFace faceType, int level, SharpDX.Direct3D9.LockFlags flags) { LockedRectangle lockedRect; LockRectangle(faceType, level, out lockedRect, IntPtr.Zero, flags); return new DataRectangle(lockedRect.PBits, lockedRect.Pitch); } /// <summary> /// Locks a rectangle on a cube texture resource. /// </summary> /// <param name="faceType">Type of the face.</param> /// <param name="level">The level.</param> /// <param name="flags">The flags.</param> /// <param name="stream">The stream pointing to the locked region.</param> /// <returns> /// A <see cref="DataRectangle"/> describing the region locked. /// </returns> /// <unmanaged>HRESULT IDirect3DCubeTexture9::LockRect([In] D3DCUBEMAP_FACES FaceType,[In] unsigned int Level,[In] D3DLOCKED_RECT* pLockedRect,[In] const void* pRect,[In] D3DLOCK Flags)</unmanaged> public DataRectangle LockRectangle(SharpDX.Direct3D9.CubeMapFace faceType, int level, SharpDX.Direct3D9.LockFlags flags, out DataStream stream) { LockedRectangle lockedRect; LockRectangle(faceType, level, out lockedRect, IntPtr.Zero, flags); stream = new DataStream(lockedRect.PBits, lockedRect.Pitch * GetLevelDescription(level).Height, true, (flags & LockFlags.ReadOnly) == 0); return new DataRectangle(lockedRect.PBits, lockedRect.Pitch); } /// <summary> /// Locks a rectangle on a cube texture resource. /// </summary> /// <param name="faceType">Type of the face.</param> /// <param name="level">The level.</param> /// <param name="rectangle">The rectangle.</param> /// <param name="flags">The flags.</param> /// <returns> /// A <see cref="DataRectangle"/> describing the region locked. /// </returns> /// <unmanaged>HRESULT IDirect3DCubeTexture9::LockRect([In] D3DCUBEMAP_FACES FaceType,[In] unsigned int Level,[In] D3DLOCKED_RECT* pLockedRect,[In] const void* pRect,[In] D3DLOCK Flags)</unmanaged> public DataRectangle LockRectangle(SharpDX.Direct3D9.CubeMapFace faceType, int level, RawRectangle rectangle, SharpDX.Direct3D9.LockFlags flags) { unsafe { LockedRectangle lockedRect; LockRectangle(faceType, level, out lockedRect, new IntPtr(&rectangle), flags); return new DataRectangle(lockedRect.PBits, lockedRect.Pitch); } } /// <summary> /// Locks a rectangle on a cube texture resource. /// </summary> /// <param name="faceType">Type of the face.</param> /// <param name="level">The level.</param> /// <param name="rectangle">The rectangle.</param> /// <param name="flags">The flags.</param> /// <param name="stream">The stream pointing to the locked region.</param> /// <returns> /// A <see cref="DataRectangle"/> describing the region locked. /// </returns> /// <unmanaged>HRESULT IDirect3DCubeTexture9::LockRect([In] D3DCUBEMAP_FACES FaceType,[In] unsigned int Level,[In] D3DLOCKED_RECT* pLockedRect,[In] const void* pRect,[In] D3DLOCK Flags)</unmanaged> public DataRectangle LockRectangle(SharpDX.Direct3D9.CubeMapFace faceType, int level, RawRectangle rectangle, SharpDX.Direct3D9.LockFlags flags, out DataStream stream) { unsafe { LockedRectangle lockedRect; LockRectangle(faceType, level, out lockedRect, new IntPtr(&rectangle), flags); stream = new DataStream(lockedRect.PBits, lockedRect.Pitch * GetLevelDescription(level).Height, true, (flags & LockFlags.ReadOnly) == 0); return new DataRectangle(lockedRect.PBits, lockedRect.Pitch); } } /// <summary> /// Adds a dirty region to a cube texture resource. /// </summary> /// <param name="faceType">Type of the face.</param> /// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns> /// <unmanaged>HRESULT IDirect3DCubeTexture9::AddDirtyRect([In] D3DCUBEMAP_FACES FaceType,[In] const void* pDirtyRect)</unmanaged> public void AddDirtyRectangle(SharpDX.Direct3D9.CubeMapFace faceType) { AddDirtyRectangle(faceType, IntPtr.Zero); } /// <summary> /// Adds a dirty region to a cube texture resource. /// </summary> /// <param name="faceType">Type of the face.</param> /// <param name="dirtyRectRef">The dirty rect ref.</param> /// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns> /// <unmanaged>HRESULT IDirect3DCubeTexture9::AddDirtyRect([In] D3DCUBEMAP_FACES FaceType,[In] const void* pDirtyRect)</unmanaged> public void AddDirtyRectangle(SharpDX.Direct3D9.CubeMapFace faceType, RawRectangle dirtyRectRef) { unsafe { AddDirtyRectangle(faceType, new IntPtr(&dirtyRectRef)); } } /// <summary> /// Creates a <see cref="CubeTexture"/> from a file /// </summary> /// <param name="device">The device.</param> /// <param name="filename">The filename.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static CubeTexture FromFile(Device device, string filename) { CubeTexture cubeTexture; D3DX9.CreateCubeTextureFromFileW(device, filename, out cubeTexture); return cubeTexture; } /// <summary> /// Creates a <see cref="CubeTexture"/> from a file /// </summary> /// <param name="device">The device.</param> /// <param name="filename">The filename.</param> /// <param name="usage">The usage.</param> /// <param name="pool">The pool.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static CubeTexture FromFile(Device device, string filename, Usage usage, Pool pool) { return FromFile(device, filename, -1, -1, usage, Format.Unknown, pool, Filter.Default, Filter.Default, 0); } /// <summary> /// Creates a <see cref="CubeTexture"/> from a file /// </summary> /// <param name="device">The device.</param> /// <param name="filename">The filename.</param> /// <param name="size">The size.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static CubeTexture FromFile(Device device, string filename, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey) { return CreateFromFile(device, filename, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, IntPtr.Zero, null); } /// <summary> /// Creates a <see cref="CubeTexture"/> from a file /// </summary> /// <param name="device">The device.</param> /// <param name="filename">The filename.</param> /// <param name="size">The size.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static unsafe CubeTexture FromFile(Device device, string filename, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation) { fixed (void* pImageInfo = &imageInformation) return CreateFromFile(device, filename, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, null); } /// <summary> /// Creates a <see cref="CubeTexture"/> from a file /// </summary> /// <param name="device">The device.</param> /// <param name="filename">The filename.</param> /// <param name="size">The size.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <param name="palette">The palette.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static unsafe CubeTexture FromFile(Device device, string filename, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation, out PaletteEntry[] palette) { palette = new PaletteEntry[256]; fixed (void* pImageInfo = &imageInformation) return CreateFromFile(device, filename, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, palette); } /// <summary> /// Creates a <see cref="CubeTexture"/> from a memory buffer. /// </summary> /// <param name="device">The device.</param> /// <param name="buffer">The buffer.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemory([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static CubeTexture FromMemory(Device device, byte[] buffer) { CubeTexture cubeTexture; unsafe { fixed (void* pData = buffer) D3DX9.CreateCubeTextureFromFileInMemory(device, (IntPtr)pData, buffer.Length, out cubeTexture); } return cubeTexture; } /// <summary> /// Creates a <see cref="CubeTexture"/> from a memory buffer. /// </summary> /// <param name="device">The device.</param> /// <param name="buffer">The buffer.</param> /// <param name="usage">The usage.</param> /// <param name="pool">The pool.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static CubeTexture FromMemory(Device device, byte[] buffer, Usage usage, Pool pool) { return FromMemory(device, buffer, -1, -1, usage, Format.Unknown, pool, Filter.Default, Filter.Default, 0); } /// <summary> /// Creates a <see cref="CubeTexture"/> from a memory buffer. /// </summary> /// <param name="device">The device.</param> /// <param name="buffer">The buffer.</param> /// <param name="size">The size.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static CubeTexture FromMemory(Device device, byte[] buffer, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey) { return CreateFromMemory(device, buffer, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, IntPtr.Zero, null); } /// <summary> /// Creates a <see cref="CubeTexture"/> from a memory buffer. /// </summary> /// <param name="device">The device.</param> /// <param name="buffer">The buffer.</param> /// <param name="size">The size.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static unsafe CubeTexture FromMemory(Device device, byte[] buffer, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation) { fixed (void* pImageInfo = &imageInformation) return CreateFromMemory(device, buffer, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, null); } /// <summary> /// Creates a <see cref="CubeTexture"/> from a memory buffer. /// </summary> /// <param name="device">The device.</param> /// <param name="buffer">The buffer.</param> /// <param name="size">The size.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <param name="palette">The palette.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static unsafe CubeTexture FromMemory(Device device, byte[] buffer, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation, out PaletteEntry[] palette) { palette = new PaletteEntry[256]; fixed (void* pImageInfo = &imageInformation) return CreateFromMemory(device, buffer, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, palette); } /// <summary> /// Creates a <see cref="CubeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="stream">The stream.</param> /// <returns>A <see cref="CubeTexture"/></returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemory([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static CubeTexture FromStream(Device device, Stream stream) { CubeTexture cubeTexture; if (stream is DataStream) { D3DX9.CreateCubeTextureFromFileInMemory(device, ((DataStream)stream).PositionPointer, (int)(stream.Length - stream.Position), out cubeTexture); } else { unsafe { var data = Utilities.ReadStream(stream); fixed (void* pData = data) D3DX9.CreateCubeTextureFromFileInMemory(device, (IntPtr)pData, data.Length, out cubeTexture); } } return cubeTexture; } /// <summary> /// Creates a <see cref="CubeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="stream">The stream.</param> /// <param name="usage">The usage.</param> /// <param name="pool">The pool.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static CubeTexture FromStream(Device device, Stream stream, Usage usage, Pool pool) { return FromStream(device, stream, 0, -1, -1, usage, Format.Unknown, pool, Filter.Default, Filter.Default, 0); } /// <summary> /// Creates a <see cref="CubeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="stream">The stream.</param> /// <param name="size">The size.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static CubeTexture FromStream(Device device, Stream stream, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey) { return FromStream(device, stream, 0, size, levelCount, usage, format, pool, filter, mipFilter, colorKey); } /// <summary> /// Creates a <see cref="CubeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="stream">The stream.</param> /// <param name="sizeBytes">The size bytes.</param> /// <param name="size">The size.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static CubeTexture FromStream(Device device, Stream stream, int sizeBytes, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey) { return CreateFromStream(device, stream, sizeBytes, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, IntPtr.Zero, null); } /// <summary> /// Creates a <see cref="CubeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="stream">The stream.</param> /// <param name="sizeBytes">The size bytes.</param> /// <param name="size">The size.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static unsafe CubeTexture FromStream(Device device, Stream stream, int sizeBytes, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation) { fixed (void* pImageInfo = &imageInformation) return CreateFromStream(device, stream, sizeBytes, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, null); } /// <summary> /// Creates a <see cref="CubeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="stream">The stream.</param> /// <param name="sizeBytes">The size bytes.</param> /// <param name="size">The size.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <param name="palette">The palette.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> public static unsafe CubeTexture FromStream(Device device, Stream stream, int sizeBytes, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation, out PaletteEntry[] palette) { palette = new PaletteEntry[256]; fixed (void* pImageInfo = &imageInformation) return CreateFromStream(device, stream, sizeBytes, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, palette); } /// <summary> /// Creates a <see cref="CubeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="buffer">The buffer.</param> /// <param name="size">The size.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <param name="palette">The palette.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> private static unsafe CubeTexture CreateFromMemory(Device device, byte[] buffer, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette) { CubeTexture cubeTexture; fixed (void* pBuffer = buffer) cubeTexture = CreateFromPointer( device, (IntPtr)pBuffer, buffer.Length, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, imageInformation, palette ); return cubeTexture; } /// <summary> /// Creates a <see cref="CubeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="stream">The stream.</param> /// <param name="sizeBytes">The size bytes.</param> /// <param name="size">The size.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <param name="palette">The palette.</param> /// <returns>A <see cref="CubeTexture"/></returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> private static unsafe CubeTexture CreateFromStream(Device device, Stream stream, int sizeBytes, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette) { CubeTexture cubeTexture; sizeBytes = sizeBytes == 0 ? (int)(stream.Length - stream.Position) : sizeBytes; if (stream is DataStream) { cubeTexture = CreateFromPointer( device, ((DataStream)stream).PositionPointer, sizeBytes, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, imageInformation, palette ); } else { var data = Utilities.ReadStream(stream); fixed (void* pData = data) cubeTexture = CreateFromPointer( device, (IntPtr)pData, data.Length, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, imageInformation, palette ); } stream.Position = sizeBytes; return cubeTexture; } /// <summary> /// Creates a <see cref="CubeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="pointer">The pointer.</param> /// <param name="sizeInBytes">The size in bytes.</param> /// <param name="size">The size.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <param name="palette">The palette.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> private static unsafe CubeTexture CreateFromPointer(Device device, IntPtr pointer, int sizeInBytes, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette) { CubeTexture cubeTexture; D3DX9.CreateCubeTextureFromFileInMemoryEx( device, pointer, sizeInBytes, size, levelCount, (int)usage, format, pool, (int)filter, (int)mipFilter, *(RawColorBGRA*)&colorKey, imageInformation, palette, out cubeTexture); return cubeTexture; } /// <summary> /// Creates a <see cref="CubeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="fileName">Name of the file.</param> /// <param name="size">The size.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <param name="palette">The palette.</param> /// <returns> /// A <see cref="CubeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged> private unsafe static CubeTexture CreateFromFile(Device device, string fileName, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette) { CubeTexture cubeTexture; D3DX9.CreateCubeTextureFromFileExW( device, fileName, size, levelCount, (int)usage, format, pool, (int)filter, (int)mipFilter, *(RawColorBGRA*)&colorKey, imageInformation, palette, out cubeTexture); return cubeTexture; } } }
// // CryptoConvert.cs - Crypto Convertion Routines // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // (C) 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004-2006 Novell Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; using System.Security.Cryptography; using System.Text; namespace Mono.Security.Cryptography { #if INSIDE_CORLIB internal #else public #endif sealed class CryptoConvert { private CryptoConvert () { } static private int ToInt32LE (byte [] bytes, int offset) { return (bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset]; } static private uint ToUInt32LE (byte [] bytes, int offset) { return (uint)((bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset]); } static private byte [] GetBytesLE (int val) { return new byte [] { (byte) (val & 0xff), (byte) ((val >> 8) & 0xff), (byte) ((val >> 16) & 0xff), (byte) ((val >> 24) & 0xff) }; } static private byte[] Trim (byte[] array) { for (int i=0; i < array.Length; i++) { if (array [i] != 0x00) { byte[] result = new byte [array.Length - i]; Buffer.BlockCopy (array, i, result, 0, result.Length); return result; } } return null; } // convert the key from PRIVATEKEYBLOB to RSA // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/security/Security/private_key_blobs.asp // e.g. SNK files, PVK files static public RSA FromCapiPrivateKeyBlob (byte[] blob) { return FromCapiPrivateKeyBlob (blob, 0); } static public RSA FromCapiPrivateKeyBlob (byte[] blob, int offset) { if (blob == null) throw new ArgumentNullException ("blob"); if (offset >= blob.Length) throw new ArgumentException ("blob is too small."); RSAParameters rsap = new RSAParameters (); try { if ((blob [offset] != 0x07) || // PRIVATEKEYBLOB (0x07) (blob [offset+1] != 0x02) || // Version (0x02) (blob [offset+2] != 0x00) || // Reserved (word) (blob [offset+3] != 0x00) || (ToUInt32LE (blob, offset+8) != 0x32415352)) // DWORD magic = RSA2 throw new CryptographicException ("Invalid blob header"); // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...) // int algId = ToInt32LE (blob, offset+4); // DWORD bitlen int bitLen = ToInt32LE (blob, offset+12); // DWORD public exponent byte[] exp = new byte [4]; Buffer.BlockCopy (blob, offset+16, exp, 0, 4); Array.Reverse (exp); rsap.Exponent = Trim (exp); int pos = offset+20; // BYTE modulus[rsapubkey.bitlen/8]; int byteLen = (bitLen >> 3); rsap.Modulus = new byte [byteLen]; Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen); Array.Reverse (rsap.Modulus); pos += byteLen; // BYTE prime1[rsapubkey.bitlen/16]; int byteHalfLen = (byteLen >> 1); rsap.P = new byte [byteHalfLen]; Buffer.BlockCopy (blob, pos, rsap.P, 0, byteHalfLen); Array.Reverse (rsap.P); pos += byteHalfLen; // BYTE prime2[rsapubkey.bitlen/16]; rsap.Q = new byte [byteHalfLen]; Buffer.BlockCopy (blob, pos, rsap.Q, 0, byteHalfLen); Array.Reverse (rsap.Q); pos += byteHalfLen; // BYTE exponent1[rsapubkey.bitlen/16]; rsap.DP = new byte [byteHalfLen]; Buffer.BlockCopy (blob, pos, rsap.DP, 0, byteHalfLen); Array.Reverse (rsap.DP); pos += byteHalfLen; // BYTE exponent2[rsapubkey.bitlen/16]; rsap.DQ = new byte [byteHalfLen]; Buffer.BlockCopy (blob, pos, rsap.DQ, 0, byteHalfLen); Array.Reverse (rsap.DQ); pos += byteHalfLen; // BYTE coefficient[rsapubkey.bitlen/16]; rsap.InverseQ = new byte [byteHalfLen]; Buffer.BlockCopy (blob, pos, rsap.InverseQ, 0, byteHalfLen); Array.Reverse (rsap.InverseQ); pos += byteHalfLen; // ok, this is hackish but CryptoAPI support it so... // note: only works because CRT is used by default // http://bugzilla.ximian.com/show_bug.cgi?id=57941 rsap.D = new byte [byteLen]; // must be allocated if (pos + byteLen + offset <= blob.Length) { // BYTE privateExponent[rsapubkey.bitlen/8]; Buffer.BlockCopy (blob, pos, rsap.D, 0, byteLen); Array.Reverse (rsap.D); } } catch (Exception e) { throw new CryptographicException ("Invalid blob.", e); } #if INSIDE_CORLIB && MOBILE RSA rsa = RSA.Create (); rsa.ImportParameters (rsap); #else RSA rsa = null; try { rsa = RSA.Create (); rsa.ImportParameters (rsap); } catch (CryptographicException ce) { // this may cause problem when this code is run under // the SYSTEM identity on Windows (e.g. ASP.NET). See // http://bugzilla.ximian.com/show_bug.cgi?id=77559 try { CspParameters csp = new CspParameters (); csp.Flags = CspProviderFlags.UseMachineKeyStore; rsa = new RSACryptoServiceProvider (csp); rsa.ImportParameters (rsap); } catch { // rethrow original, not the later, exception if this fails throw ce; } } #endif return rsa; } static public DSA FromCapiPrivateKeyBlobDSA (byte[] blob) { return FromCapiPrivateKeyBlobDSA (blob, 0); } static public DSA FromCapiPrivateKeyBlobDSA (byte[] blob, int offset) { if (blob == null) throw new ArgumentNullException ("blob"); if (offset >= blob.Length) throw new ArgumentException ("blob is too small."); DSAParameters dsap = new DSAParameters (); try { if ((blob [offset] != 0x07) || // PRIVATEKEYBLOB (0x07) (blob [offset + 1] != 0x02) || // Version (0x02) (blob [offset + 2] != 0x00) || // Reserved (word) (blob [offset + 3] != 0x00) || (ToUInt32LE (blob, offset + 8) != 0x32535344)) // DWORD magic throw new CryptographicException ("Invalid blob header"); int bitlen = ToInt32LE (blob, offset + 12); int bytelen = bitlen >> 3; int pos = offset + 16; dsap.P = new byte [bytelen]; Buffer.BlockCopy (blob, pos, dsap.P, 0, bytelen); Array.Reverse (dsap.P); pos += bytelen; dsap.Q = new byte [20]; Buffer.BlockCopy (blob, pos, dsap.Q, 0, 20); Array.Reverse (dsap.Q); pos += 20; dsap.G = new byte [bytelen]; Buffer.BlockCopy (blob, pos, dsap.G, 0, bytelen); Array.Reverse (dsap.G); pos += bytelen; dsap.X = new byte [20]; Buffer.BlockCopy (blob, pos, dsap.X, 0, 20); Array.Reverse (dsap.X); pos += 20; dsap.Counter = ToInt32LE (blob, pos); pos += 4; dsap.Seed = new byte [20]; Buffer.BlockCopy (blob, pos, dsap.Seed, 0, 20); Array.Reverse (dsap.Seed); pos += 20; } catch (Exception e) { throw new CryptographicException ("Invalid blob.", e); } #if INSIDE_CORLIB && MOBILE DSA dsa = (DSA)DSA.Create (); dsa.ImportParameters (dsap); #else DSA dsa = null; try { dsa = (DSA)DSA.Create (); dsa.ImportParameters (dsap); } catch (CryptographicException ce) { // this may cause problem when this code is run under // the SYSTEM identity on Windows (e.g. ASP.NET). See // http://bugzilla.ximian.com/show_bug.cgi?id=77559 try { CspParameters csp = new CspParameters (); csp.Flags = CspProviderFlags.UseMachineKeyStore; dsa = new DSACryptoServiceProvider (csp); dsa.ImportParameters (dsap); } catch { // rethrow original, not the later, exception if this fails throw ce; } } #endif return dsa; } static public byte[] ToCapiPrivateKeyBlob (RSA rsa) { RSAParameters p = rsa.ExportParameters (true); int keyLength = p.Modulus.Length; // in bytes byte[] blob = new byte [20 + (keyLength << 2) + (keyLength >> 1)]; blob [0] = 0x07; // Type - PRIVATEKEYBLOB (0x07) blob [1] = 0x02; // Version - Always CUR_BLOB_VERSION (0x02) // [2], [3] // RESERVED - Always 0 blob [5] = 0x24; // ALGID - Always 00 24 00 00 (for CALG_RSA_SIGN) blob [8] = 0x52; // Magic - RSA2 (ASCII in hex) blob [9] = 0x53; blob [10] = 0x41; blob [11] = 0x32; byte[] bitlen = GetBytesLE (keyLength << 3); blob [12] = bitlen [0]; // bitlen blob [13] = bitlen [1]; blob [14] = bitlen [2]; blob [15] = bitlen [3]; // public exponent (DWORD) int pos = 16; int n = p.Exponent.Length; while (n > 0) blob [pos++] = p.Exponent [--n]; // modulus pos = 20; byte[] part = p.Modulus; int len = part.Length; Array.Reverse (part, 0, len); Buffer.BlockCopy (part, 0, blob, pos, len); pos += len; // private key part = p.P; len = part.Length; Array.Reverse (part, 0, len); Buffer.BlockCopy (part, 0, blob, pos, len); pos += len; part = p.Q; len = part.Length; Array.Reverse (part, 0, len); Buffer.BlockCopy (part, 0, blob, pos, len); pos += len; part = p.DP; len = part.Length; Array.Reverse (part, 0, len); Buffer.BlockCopy (part, 0, blob, pos, len); pos += len; part = p.DQ; len = part.Length; Array.Reverse (part, 0, len); Buffer.BlockCopy (part, 0, blob, pos, len); pos += len; part = p.InverseQ; len = part.Length; Array.Reverse (part, 0, len); Buffer.BlockCopy (part, 0, blob, pos, len); pos += len; part = p.D; len = part.Length; Array.Reverse (part, 0, len); Buffer.BlockCopy (part, 0, blob, pos, len); return blob; } static public byte[] ToCapiPrivateKeyBlob (DSA dsa) { DSAParameters p = dsa.ExportParameters (true); int keyLength = p.P.Length; // in bytes // header + P + Q + G + X + count + seed byte[] blob = new byte [16 + keyLength + 20 + keyLength + 20 + 4 + 20]; blob [0] = 0x07; // Type - PRIVATEKEYBLOB (0x07) blob [1] = 0x02; // Version - Always CUR_BLOB_VERSION (0x02) // [2], [3] // RESERVED - Always 0 blob [5] = 0x22; // ALGID blob [8] = 0x44; // Magic blob [9] = 0x53; blob [10] = 0x53; blob [11] = 0x32; byte[] bitlen = GetBytesLE (keyLength << 3); blob [12] = bitlen [0]; blob [13] = bitlen [1]; blob [14] = bitlen [2]; blob [15] = bitlen [3]; int pos = 16; byte[] part = p.P; Array.Reverse (part); Buffer.BlockCopy (part, 0, blob, pos, keyLength); pos += keyLength; part = p.Q; Array.Reverse (part); Buffer.BlockCopy (part, 0, blob, pos, 20); pos += 20; part = p.G; Array.Reverse (part); Buffer.BlockCopy (part, 0, blob, pos, keyLength); pos += keyLength; part = p.X; Array.Reverse (part); Buffer.BlockCopy (part, 0, blob, pos, 20); pos += 20; Buffer.BlockCopy (GetBytesLE (p.Counter), 0, blob, pos, 4); pos += 4; part = p.Seed; Array.Reverse (part); Buffer.BlockCopy (part, 0, blob, pos, 20); return blob; } static public RSA FromCapiPublicKeyBlob (byte[] blob) { return FromCapiPublicKeyBlob (blob, 0); } static public RSA FromCapiPublicKeyBlob (byte[] blob, int offset) { if (blob == null) throw new ArgumentNullException ("blob"); if (offset >= blob.Length) throw new ArgumentException ("blob is too small."); try { if ((blob [offset] != 0x06) || // PUBLICKEYBLOB (0x06) (blob [offset+1] != 0x02) || // Version (0x02) (blob [offset+2] != 0x00) || // Reserved (word) (blob [offset+3] != 0x00) || (ToUInt32LE (blob, offset+8) != 0x31415352)) // DWORD magic = RSA1 throw new CryptographicException ("Invalid blob header"); // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...) // int algId = ToInt32LE (blob, offset+4); // DWORD bitlen int bitLen = ToInt32LE (blob, offset+12); // DWORD public exponent RSAParameters rsap = new RSAParameters (); rsap.Exponent = new byte [3]; rsap.Exponent [0] = blob [offset+18]; rsap.Exponent [1] = blob [offset+17]; rsap.Exponent [2] = blob [offset+16]; int pos = offset+20; // BYTE modulus[rsapubkey.bitlen/8]; int byteLen = (bitLen >> 3); rsap.Modulus = new byte [byteLen]; Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen); Array.Reverse (rsap.Modulus); #if INSIDE_CORLIB && MOBILE RSA rsa = RSA.Create (); rsa.ImportParameters (rsap); #else RSA rsa = null; try { rsa = RSA.Create (); rsa.ImportParameters (rsap); } catch (CryptographicException) { // this may cause problem when this code is run under // the SYSTEM identity on Windows (e.g. ASP.NET). See // http://bugzilla.ximian.com/show_bug.cgi?id=77559 CspParameters csp = new CspParameters (); csp.Flags = CspProviderFlags.UseMachineKeyStore; rsa = new RSACryptoServiceProvider (csp); rsa.ImportParameters (rsap); } #endif return rsa; } catch (Exception e) { throw new CryptographicException ("Invalid blob.", e); } } static public DSA FromCapiPublicKeyBlobDSA (byte[] blob) { return FromCapiPublicKeyBlobDSA (blob, 0); } static public DSA FromCapiPublicKeyBlobDSA (byte[] blob, int offset) { if (blob == null) throw new ArgumentNullException ("blob"); if (offset >= blob.Length) throw new ArgumentException ("blob is too small."); try { if ((blob [offset] != 0x06) || // PUBLICKEYBLOB (0x06) (blob [offset + 1] != 0x02) || // Version (0x02) (blob [offset + 2] != 0x00) || // Reserved (word) (blob [offset + 3] != 0x00) || (ToUInt32LE (blob, offset + 8) != 0x31535344)) // DWORD magic throw new CryptographicException ("Invalid blob header"); int bitlen = ToInt32LE (blob, offset + 12); DSAParameters dsap = new DSAParameters (); int bytelen = bitlen >> 3; int pos = offset + 16; dsap.P = new byte [bytelen]; Buffer.BlockCopy (blob, pos, dsap.P, 0, bytelen); Array.Reverse (dsap.P); pos += bytelen; dsap.Q = new byte [20]; Buffer.BlockCopy (blob, pos, dsap.Q, 0, 20); Array.Reverse (dsap.Q); pos += 20; dsap.G = new byte [bytelen]; Buffer.BlockCopy (blob, pos, dsap.G, 0, bytelen); Array.Reverse (dsap.G); pos += bytelen; dsap.Y = new byte [bytelen]; Buffer.BlockCopy (blob, pos, dsap.Y, 0, bytelen); Array.Reverse (dsap.Y); pos += bytelen; dsap.Counter = ToInt32LE (blob, pos); pos += 4; dsap.Seed = new byte [20]; Buffer.BlockCopy (blob, pos, dsap.Seed, 0, 20); Array.Reverse (dsap.Seed); pos += 20; DSA dsa = (DSA)DSA.Create (); dsa.ImportParameters (dsap); return dsa; } catch (Exception e) { throw new CryptographicException ("Invalid blob.", e); } } static public byte[] ToCapiPublicKeyBlob (RSA rsa) { RSAParameters p = rsa.ExportParameters (false); int keyLength = p.Modulus.Length; // in bytes byte[] blob = new byte [20 + keyLength]; blob [0] = 0x06; // Type - PUBLICKEYBLOB (0x06) blob [1] = 0x02; // Version - Always CUR_BLOB_VERSION (0x02) // [2], [3] // RESERVED - Always 0 blob [5] = 0x24; // ALGID - Always 00 24 00 00 (for CALG_RSA_SIGN) blob [8] = 0x52; // Magic - RSA1 (ASCII in hex) blob [9] = 0x53; blob [10] = 0x41; blob [11] = 0x31; byte[] bitlen = GetBytesLE (keyLength << 3); blob [12] = bitlen [0]; // bitlen blob [13] = bitlen [1]; blob [14] = bitlen [2]; blob [15] = bitlen [3]; // public exponent (DWORD) int pos = 16; int n = p.Exponent.Length; while (n > 0) blob [pos++] = p.Exponent [--n]; // modulus pos = 20; byte[] part = p.Modulus; int len = part.Length; Array.Reverse (part, 0, len); Buffer.BlockCopy (part, 0, blob, pos, len); pos += len; return blob; } static public byte[] ToCapiPublicKeyBlob (DSA dsa) { DSAParameters p = dsa.ExportParameters (false); int keyLength = p.P.Length; // in bytes // header + P + Q + G + Y + count + seed byte[] blob = new byte [16 + keyLength + 20 + keyLength + keyLength + 4 + 20]; blob [0] = 0x06; // Type - PUBLICKEYBLOB (0x06) blob [1] = 0x02; // Version - Always CUR_BLOB_VERSION (0x02) // [2], [3] // RESERVED - Always 0 blob [5] = 0x22; // ALGID blob [8] = 0x44; // Magic blob [9] = 0x53; blob [10] = 0x53; blob [11] = 0x31; byte[] bitlen = GetBytesLE (keyLength << 3); blob [12] = bitlen [0]; blob [13] = bitlen [1]; blob [14] = bitlen [2]; blob [15] = bitlen [3]; int pos = 16; byte[] part; part = p.P; Array.Reverse (part); Buffer.BlockCopy (part, 0, blob, pos, keyLength); pos += keyLength; part = p.Q; Array.Reverse (part); Buffer.BlockCopy (part, 0, blob, pos, 20); pos += 20; part = p.G; Array.Reverse (part); Buffer.BlockCopy (part, 0, blob, pos, keyLength); pos += keyLength; part = p.Y; Array.Reverse (part); Buffer.BlockCopy (part, 0, blob, pos, keyLength); pos += keyLength; Buffer.BlockCopy (GetBytesLE (p.Counter), 0, blob, pos, 4); pos += 4; part = p.Seed; Array.Reverse (part); Buffer.BlockCopy (part, 0, blob, pos, 20); return blob; } // PRIVATEKEYBLOB // PUBLICKEYBLOB static public RSA FromCapiKeyBlob (byte[] blob) { return FromCapiKeyBlob (blob, 0); } static public RSA FromCapiKeyBlob (byte[] blob, int offset) { if (blob == null) throw new ArgumentNullException ("blob"); if (offset >= blob.Length) throw new ArgumentException ("blob is too small."); switch (blob [offset]) { case 0x00: // this could be a public key inside an header // like "sn -e" would produce if (blob [offset + 12] == 0x06) { return FromCapiPublicKeyBlob (blob, offset + 12); } break; case 0x06: return FromCapiPublicKeyBlob (blob, offset); case 0x07: return FromCapiPrivateKeyBlob (blob, offset); } throw new CryptographicException ("Unknown blob format."); } static public DSA FromCapiKeyBlobDSA (byte[] blob) { return FromCapiKeyBlobDSA (blob, 0); } static public DSA FromCapiKeyBlobDSA (byte[] blob, int offset) { if (blob == null) throw new ArgumentNullException ("blob"); if (offset >= blob.Length) throw new ArgumentException ("blob is too small."); switch (blob [offset]) { case 0x06: return FromCapiPublicKeyBlobDSA (blob, offset); case 0x07: return FromCapiPrivateKeyBlobDSA (blob, offset); } throw new CryptographicException ("Unknown blob format."); } static public byte[] ToCapiKeyBlob (AsymmetricAlgorithm keypair, bool includePrivateKey) { if (keypair == null) throw new ArgumentNullException ("keypair"); // check between RSA and DSA (and potentially others like DH) if (keypair is RSA) return ToCapiKeyBlob ((RSA)keypair, includePrivateKey); else if (keypair is DSA) return ToCapiKeyBlob ((DSA)keypair, includePrivateKey); else return null; // TODO } static public byte[] ToCapiKeyBlob (RSA rsa, bool includePrivateKey) { if (rsa == null) throw new ArgumentNullException ("rsa"); if (includePrivateKey) return ToCapiPrivateKeyBlob (rsa); else return ToCapiPublicKeyBlob (rsa); } static public byte[] ToCapiKeyBlob (DSA dsa, bool includePrivateKey) { if (dsa == null) throw new ArgumentNullException ("dsa"); if (includePrivateKey) return ToCapiPrivateKeyBlob (dsa); else return ToCapiPublicKeyBlob (dsa); } static public string ToHex (byte[] input) { if (input == null) return null; StringBuilder sb = new StringBuilder (input.Length * 2); foreach (byte b in input) { sb.Append (b.ToString ("X2", CultureInfo.InvariantCulture)); } return sb.ToString (); } static private byte FromHexChar (char c) { if ((c >= 'a') && (c <= 'f')) return (byte) (c - 'a' + 10); if ((c >= 'A') && (c <= 'F')) return (byte) (c - 'A' + 10); if ((c >= '0') && (c <= '9')) return (byte) (c - '0'); throw new ArgumentException ("invalid hex char"); } static public byte[] FromHex (string hex) { if (hex == null) return null; if ((hex.Length & 0x1) == 0x1) throw new ArgumentException ("Length must be a multiple of 2"); byte[] result = new byte [hex.Length >> 1]; int n = 0; int i = 0; while (n < result.Length) { result [n] = (byte) (FromHexChar (hex [i++]) << 4); result [n++] += FromHexChar (hex [i++]); } return result; } } }
using System; using System.Collections.Generic; using Machine.Fakes.ReSharperAnnotations; using Machine.Fakes.Sdk; using Machine.Specifications; namespace Machine.Fakes { /// <summary> /// Base class for specifications. /// </summary> /// <typeparam name="TSubject">The subject of the specification</typeparam> /// <typeparam name="TFakeEngine"> /// Specifies the concrete fake engine that will be used for creating fake instances. /// This must be a class with a parameterless constructor that implements <see cref="IFakeEngine"/>. /// </typeparam> [UsedImplicitly(ImplicitUseTargetFlags.WithMembers)] public abstract class WithFakes<TSubject, TFakeEngine> where TSubject : class where TFakeEngine : IFakeEngine, new() { /// <summary> /// The specification controller /// </summary> protected static SpecificationController<TSubject, TFakeEngine> _specificationController; /// <summary> /// Creates a new instance of the <see cref="WithFakes{TSubject, TFakeEngine}"/> class. /// </summary> protected WithFakes() { _specificationController = new SpecificationController<TSubject, TFakeEngine>(); } /// <summary> /// Creates a fake of the type specified by <typeparamref name = "TInterfaceType" />. /// </summary> /// <typeparam name = "TInterfaceType">The type to create a fake for. (Should be an interface or an abstract class)</typeparam> /// <param name="args"> /// Optional constructor parameters for abstract base classes as fakes. /// </param> /// <returns> /// An newly created fake implementing <typeparamref name = "TInterfaceType" />. /// </returns> public static TInterfaceType An<TInterfaceType>(params object[] args) where TInterfaceType : class { GuardAgainstStaticContext(); return _specificationController.An<TInterfaceType>(args); } /// <summary> /// Creates a list containing 3 fake instances of the type specified /// via <typeparamref name = "TInterfaceType" />. /// </summary> /// <typeparam name = "TInterfaceType">Specifies the item type of the list. This should be an interface or an abstract class.</typeparam> /// <returns>An <see cref = "IList{T}" />.</returns> public static IList<TInterfaceType> Some<TInterfaceType>() where TInterfaceType : class { GuardAgainstStaticContext(); return _specificationController.Some<TInterfaceType>(); } /// <summary> /// Creates a list of fakes. /// </summary> /// <typeparam name="TInterfaceType"> /// Specifies the item type of the list. This should be an interface or an abstract class. /// </typeparam> /// <param name="amount"> /// Specifies the amount of fakes that have to be created and inserted into the list. /// </param> /// <returns> /// An <see cref="IList{TInterfaceType}"/>. /// </returns> public static IList<TInterfaceType> Some<TInterfaceType>(int amount) where TInterfaceType : class { GuardAgainstStaticContext(); return _specificationController.Some<TInterfaceType>(amount); } /// <summary> /// Configures the specification to execute a behavior config before the action on the subject /// is executed (<see cref="Because"/>). /// </summary> /// <typeparam name="TBehaviorConfig">Specifies the type of the config to be executed.</typeparam> /// <returns>The behavior config instance.</returns> /// <remarks> /// The class specified by <typeparamref name="TBehaviorConfig"/> /// needs to have private fields assigned with either <see cref="OnEstablish"/> /// or <see cref="OnCleanup"/> delegates. /// </remarks> protected static TBehaviorConfig With<TBehaviorConfig>() where TBehaviorConfig : new() { GuardAgainstStaticContext(); return _specificationController.With<TBehaviorConfig>(); } /// <summary> /// Configures the specification to execute the behavior config specified /// by <paramref name = "behaviorConfig" /> before the action on the sut is executed (<see cref = "Because" />). /// </summary> /// <param name = "behaviorConfig"> /// Specifies the behavior config to be executed. /// </param> /// <remarks> /// The object specified by <see paramref="behaviorConfig"/> /// needs to have private fields assigned with either <see cref="OnEstablish"/> /// or <see cref="OnCleanup"/> delegates. /// </remarks> protected static void With(object behaviorConfig) { GuardAgainstStaticContext(); _specificationController.With(behaviorConfig); } /// <summary> /// Creates a fake of the type specified by <typeparamref name = "TInterfaceType" />. /// This method reuses existing instances. If an instance of <typeparamref name = "TInterfaceType" /> /// was already requested it's returned here. (You can say this is kind of a singleton behavior) /// Besides that, you can obtain a reference to automatically injected fakes with this /// method. /// </summary> /// <typeparam name = "TInterfaceType">The type to create a fake for. (Should be an interface or an abstract class)</typeparam> /// <returns> /// An instance implementing <typeparamref name="TInterfaceType" />. /// </returns> protected static TInterfaceType The<TInterfaceType>() where TInterfaceType : class { GuardAgainstStaticContext(); return _specificationController.The<TInterfaceType>(); } /// <summary> /// Uses the instance supplied by <paramref name = "instance" /> during the /// build process of the subject. The specified instance will be injected into the constructor. /// </summary> /// <typeparam name = "TInterfaceType">Specifies the interface type.</typeparam> /// <param name = "instance">Specifies the instance to be used for the specification.</param> protected static void Configure<TInterfaceType>(TInterfaceType instance) { GuardAgainstStaticContext(); _specificationController.Configure(instance); } /// <summary> /// Registered the type specified via <typeparamref name="TImplementationType"/> as the default type /// for the interface specified via <typeparamref name="TInterfaceType"/>. With this the type gets automatically /// build when the subject is resolved. /// </summary> /// <typeparam name="TInterfaceType"> /// Specifies the interface type. /// </typeparam> /// <typeparam name="TImplementationType"> /// Specifies the implementation type. /// </typeparam> protected static void Configure<TInterfaceType, TImplementationType>() where TImplementationType : TInterfaceType { GuardAgainstStaticContext(); _specificationController.Configure<TInterfaceType, TImplementationType>(); } /// <summary> /// Applies the configuration embedded in the registar to the underlying container. /// </summary> /// <param name="registrar"> /// Specifies the registrar. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when the supplied registrar is <c>null</c>. /// </exception> protected static void Configure(Registrar registrar) { Guard.AgainstArgumentNull(registrar, "registar"); GuardAgainstStaticContext(); _specificationController.Configure(registrar); } /// <summary> /// Applies the configuration embedded in the registar to the underlying container. /// Shortcut for <see cref="Configure(Registrar)"/> so that you don't have to create the /// registrar manually. /// </summary> /// <typeparam name="TRegistrar">The registrar type.</typeparam> /// <returns>The registrar.</returns> protected static TRegistrar Configure<TRegistrar>() where TRegistrar : Registrar, new() { GuardAgainstStaticContext(); var registrar = new TRegistrar(); _specificationController.Configure(registrar); return registrar; } /// <summary> /// Shortcut for <see cref="Configure(Machine.Fakes.Registrar)"/>. This one will create /// a registrar for you and allow configuration via the delegate passed /// in via <paramref name="registrarExpression"/>. /// </summary> /// <param name="registrarExpression"> /// Specifies the configuration for the registrar. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when the supplied registrar is <c>null</c>. /// </exception> protected static void Configure(Action<Registrar> registrarExpression) { Guard.AgainstArgumentNull(registrarExpression, "registar"); GuardAgainstStaticContext(); _specificationController.Configure(registrarExpression); } /// <summary> /// Throws when the constructor has not been called /// </summary> protected static void GuardAgainstStaticContext() { if (_specificationController == null) throw new InvalidOperationException( "WithFakes has not been initialized yet. Are you calling it from a static initializer?"); } Cleanup after = () => { _specificationController.Dispose(); _specificationController = null; }; } /// <summary> /// Base class for the simpler cases than <see cref="WithSubject{TSubject, TFakeEngine}"/>. /// </summary> /// <typeparam name="TFakeEngine"> /// Specifies the concrete fake engine that will be used for creating fake instances. /// This must be a class with a parameterless constructor that implements <see cref="IFakeEngine"/>. /// </typeparam> public abstract class WithFakes<TFakeEngine> : WithFakes<object, TFakeEngine> where TFakeEngine : IFakeEngine, new() { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; namespace Internal.TypeSystem { /// <summary> /// Represents an array type - either a multidimensional array, or a vector /// (a one-dimensional array with a zero lower bound). /// </summary> public sealed partial class ArrayType : ParameterizedType { private int _rank; // -1 for regular single dimensional arrays, > 0 for multidimensional arrays internal ArrayType(TypeDesc elementType, int rank) : base(elementType) { _rank = rank; } public override int GetHashCode() { // ComputeArrayTypeHashCode expects -1 for an SzArray return Internal.NativeFormat.TypeHashingAlgorithms.ComputeArrayTypeHashCode(this.ElementType.GetHashCode(), _rank); } public override DefType BaseType { get { return this.Context.GetWellKnownType(WellKnownType.Array); } } /// <summary> /// Gets the type of the element of this array. /// </summary> public TypeDesc ElementType { get { return this.ParameterType; } } internal MethodDesc[] _methods; /// <summary> /// Gets a value indicating whether this type is a vector. /// </summary> public new bool IsSzArray { get { return _rank < 0; } } /// <summary> /// Gets a value indicating whether this type is an mdarray. /// </summary> public new bool IsMdArray { get { return _rank > 0; } } /// <summary> /// Gets the rank of this array. Note this returns "1" for both vectors, and /// for general arrays of rank 1. Use <see cref="IsSzArray"/> to disambiguate. /// </summary> public int Rank { get { return (_rank < 0) ? 1 : _rank; } } private void InitializeMethods() { int numCtors; if (IsSzArray) { numCtors = 1; // Jagged arrays have constructor for each possible depth var t = this.ElementType; while (t.IsSzArray) { t = ((ArrayType)t).ElementType; numCtors++; } } else { // Multidimensional arrays have two ctors, one with and one without lower bounds numCtors = 2; } MethodDesc[] methods = new MethodDesc[(int)ArrayMethodKind.Ctor + numCtors]; for (int i = 0; i < methods.Length; i++) methods[i] = new ArrayMethod(this, (ArrayMethodKind)i); Interlocked.CompareExchange(ref _methods, methods, null); } public override IEnumerable<MethodDesc> GetMethods() { if (_methods == null) InitializeMethods(); return _methods; } public MethodDesc GetArrayMethod(ArrayMethodKind kind) { if (_methods == null) InitializeMethods(); return _methods[(int)kind]; } public override TypeDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation) { TypeDesc elementType = this.ElementType; TypeDesc instantiatedElementType = elementType.InstantiateSignature(typeInstantiation, methodInstantiation); if (instantiatedElementType != elementType) return Context.GetArrayType(instantiatedElementType, _rank); return this; } protected override TypeFlags ComputeTypeFlags(TypeFlags mask) { TypeFlags flags = _rank == -1 ? TypeFlags.SzArray : TypeFlags.Array; if ((mask & TypeFlags.ContainsGenericVariablesComputed) != 0) { flags |= TypeFlags.ContainsGenericVariablesComputed; if (this.ParameterType.ContainsGenericVariables) flags |= TypeFlags.ContainsGenericVariables; } flags |= TypeFlags.HasGenericVarianceComputed; return flags; } public override string ToString() { return this.ElementType.ToString() + "[" + new String(',', Rank - 1) + "]"; } } public enum ArrayMethodKind { Get, Set, Address, AddressWithHiddenArg, Ctor } /// <summary> /// Represents one of the methods on array types. While array types are not typical /// classes backed by metadata, they do have methods that can be referenced from the IL /// and the type system needs to provide a way to represent them. /// </summary> /// <remarks> /// There are two array Address methods (<see cref="ArrayMethodKind.Address"/> and /// <see cref="ArrayMethodKind.AddressWithHiddenArg"/>). One is used when referencing Address /// method from IL, the other is used when *compiling* the method body. /// The reason we need to do this is that the Address method is required to do a type check using a type /// that is only known at the callsite. The trick we use is that we tell codegen that the /// <see cref="ArrayMethodKind.Address"/> method requires a hidden instantiation parameter (even though it doesn't). /// The instantiation parameter is where we capture the type at the callsite. /// When we compile the method body, we compile it as <see cref="ArrayMethodKind.AddressWithHiddenArg"/> that /// has the hidden argument explicitly listed in it's signature and is available as a regular parameter. /// </remarks> public sealed partial class ArrayMethod : MethodDesc { private ArrayType _owningType; private ArrayMethodKind _kind; internal ArrayMethod(ArrayType owningType, ArrayMethodKind kind) { _owningType = owningType; _kind = kind; } public override TypeSystemContext Context { get { return _owningType.Context; } } public override TypeDesc OwningType { get { return _owningType; } } public ArrayType OwningArray { get { return _owningType; } } public ArrayMethodKind Kind { get { return _kind; } } private MethodSignature _signature; public override MethodSignature Signature { get { if (_signature == null) { switch (_kind) { case ArrayMethodKind.Get: { var parameters = new TypeDesc[_owningType.Rank]; for (int i = 0; i < _owningType.Rank; i++) parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32); _signature = new MethodSignature(0, 0, _owningType.ElementType, parameters); break; } case ArrayMethodKind.Set: { var parameters = new TypeDesc[_owningType.Rank + 1]; for (int i = 0; i < _owningType.Rank; i++) parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32); parameters[_owningType.Rank] = _owningType.ElementType; _signature = new MethodSignature(0, 0, this.Context.GetWellKnownType(WellKnownType.Void), parameters); break; } case ArrayMethodKind.Address: { var parameters = new TypeDesc[_owningType.Rank]; for (int i = 0; i < _owningType.Rank; i++) parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32); _signature = new MethodSignature(0, 0, _owningType.ElementType.MakeByRefType(), parameters); } break; case ArrayMethodKind.AddressWithHiddenArg: { var parameters = new TypeDesc[_owningType.Rank + 1]; parameters[0] = Context.SystemModule.GetType("System", "EETypePtr"); for (int i = 0; i < _owningType.Rank; i++) parameters[i + 1] = _owningType.Context.GetWellKnownType(WellKnownType.Int32); _signature = new MethodSignature(0, 0, _owningType.ElementType.MakeByRefType(), parameters); } break; default: { int numArgs; if (_owningType.IsSzArray) { numArgs = 1 + (int)_kind - (int)ArrayMethodKind.Ctor; } else { numArgs = (_kind == ArrayMethodKind.Ctor) ? _owningType.Rank : 2 * _owningType.Rank; } var argTypes = new TypeDesc[numArgs]; for (int i = 0; i < argTypes.Length; i++) argTypes[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32); _signature = new MethodSignature(0, 0, this.Context.GetWellKnownType(WellKnownType.Void), argTypes); } break; } } return _signature; } } public override string Name { get { switch (_kind) { case ArrayMethodKind.Get: return "Get"; case ArrayMethodKind.Set: return "Set"; case ArrayMethodKind.Address: case ArrayMethodKind.AddressWithHiddenArg: return "Address"; default: return ".ctor"; } } } public override bool HasCustomAttribute(string attributeNamespace, string attributeName) { return false; } public override MethodDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation) { TypeDesc owningType = this.OwningType; TypeDesc instantiatedOwningType = owningType.InstantiateSignature(typeInstantiation, methodInstantiation); if (owningType != instantiatedOwningType) return ((ArrayType)instantiatedOwningType).GetArrayMethod(_kind); else return this; } public override string ToString() { return _owningType.ToString() + "." + Name; } } }
//=========================================================================== // // File : GenTrafficDialog.cs // //--------------------------------------------------------------------------- // // The contents of this file are subject to the "END USER LICENSE AGREEMENT FOR F5 // Software Development Kit for iControl"; you may not use this file except in // compliance with the License. The License is included in the iControl // Software Development Kit. // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See // the License for the specific language governing rights and limitations // under the License. // // The Original Code is iControl Code and related documentation // distributed by F5. // // The Initial Developer of the Original Code is F5 Networks, Inc. // Seattle, WA, USA. // Portions created by F5 are Copyright (C) 2006 F5 Networks, Inc. // All Rights Reserved. // iControl (TM) is a registered trademark of F5 Networks, Inc. // // Alternatively, the contents of this file may be used under the terms // of the GNU General Public License (the "GPL"), in which case the // provisions of GPL are applicable instead of those above. If you wish // to allow use of your version of this file only under the terms of the // GPL and not to allow others to use your version of this file under the // License, indicate your decision by deleting the provisions above and // replace them with the notice and other provisions required by the GPL. // If you do not delete the provisions above, a recipient may use your // version of this file under either the License or the GPL. // //=========================================================================== using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using iRuler.Utility; using System.Web; namespace iRuler.Dialogs { public partial class GenTrafficDialog : Form { iControl.CommonIPPortDefinition m_vs_def = null; public GenTrafficDialog() { InitializeComponent(); } private bool validateHTTP() { bool bValid = true; if (bValid && (null == m_vs_def)) { statusMessage("You must select a Virtual Server from the list"); bValid = false; } if (bValid && (0 == comboBox_HTTPMethod.Text.Length)) { statusMessage("You must select a HTTP Method"); bValid = false; } if (bValid && UseProxyCheckBox.Checked && (0 == ProxyServerTextBox.Text.Trim().Length)) { statusMessage("If you are going to use a proxy server, please specify an address"); bValid = false; } if (bValid && UseProxyCheckBox.Checked && (0 == ProxyPortTextBox.Text.Trim().Length)) { statusMessage("If you are going to use a proxy server, please specify a port"); bValid = false; } if (bValid) { statusMessage(""); } return bValid; } private void statusMessage(String sMessage) { String sMessageText = ""; if (sMessage.Length > 0) { String sTimestamp = System.DateTime.Now.ToString(); sMessageText = richTextBox_Status.Text; if ( sMessageText.Length > 0 ) { sMessageText = sMessageText + "\n"; } sMessageText = sMessageText + sTimestamp + ":" + sMessage; } richTextBox_Status.Text = sMessageText; } private void setError(String sMessage) { label_Error.Text = sMessage; } private void DoStart() { button_StartStop.Text = "Stop"; statusMessage(""); generateTraffic(); if (numericUpDown_Interval.Value > 0) { timer_GenTraffic.Enabled = true; } else { timer_GenTraffic.Enabled = false; button_StartStop.Text = "Start"; } } private void DoStop() { cancelTraffic(); timer_GenTraffic.Enabled = false; button_StartStop.Text = "Start"; } private void generateTraffic() { if (validateHTTP()) { if (!backgroundWorker_traffic.IsBusy) { ThreadInfo ti = new ThreadInfo(); ti.vs_def = m_vs_def; ti.uri = textBox_URI.Text; ti.method = comboBox_HTTPMethod.Text; ti.username = textBox_HTTPUsername.Text; ti.password = textBox_HTTPPassword.Text; ti.param_names = new String[listView_HTTPParameters.Items.Count]; ti.param_values = new String[listView_HTTPParameters.Items.Count]; for (int i = 0; i < listView_HTTPParameters.Items.Count; i++) { ti.param_names[i] = listView_HTTPParameters.Items[i].Text; ti.param_values[i] = listView_HTTPParameters.Items[i].SubItems[1].Text; } ti.header_names = new String[listView_HTTPHeaders.Items.Count]; ti.header_values = new String[listView_HTTPHeaders.Items.Count]; for (int i = 0; i < listView_HTTPHeaders.Items.Count; i++) { ti.header_names[i] = listView_HTTPHeaders.Items[i].Text; ti.header_values[i] = listView_HTTPHeaders.Items[i].SubItems[1].Text; } if (UseProxyCheckBox.Checked) { if ((0 != ProxyServerTextBox.Text.Trim().Length) && (0 != ProxyPortTextBox.Text.Trim().Length)) { ti.proxy = new System.Net.WebProxy(ProxyServerTextBox.Text, Convert.ToInt32(ProxyPortTextBox.Text)); } } richTextBox_Status.Text = ""; richTextBox_Status.Refresh(); backgroundWorker_traffic.RunWorkerAsync(ti); } } else { DoStop(); } } private void cancelTraffic() { if (backgroundWorker_traffic.IsBusy) { backgroundWorker_traffic.CancelAsync(); } } private void GenTrafficDialog_Load(object sender, System.EventArgs e) { if ( Clients.Connected ) { String [] vs_list = Clients.VirtualServer.get_list(); for (int i = 0; i < vs_list.Length; i++) { comboBox_VirtualServer.Items.Add(vs_list[i]); } comboBox_VirtualServer.SelectedIndex = 0; comboBox_HTTPMethod.SelectedIndex = 1; } } private void comboBox_VirtualServer_SelectedIndexChanged(object sender, System.EventArgs e) { String vs = comboBox_VirtualServer.Items[comboBox_VirtualServer.SelectedIndex].ToString(); iControl.CommonIPPortDefinition[] vs_def_list = Clients.VirtualServer.get_destination(new string[] { vs }); if (vs_def_list.Length > 0) { m_vs_def = vs_def_list[0]; } else { // user typed in address/port String[] sSplit = vs.Split(new char[] { ':' }); if (sSplit.Length == 2) { m_vs_def = new iControl.CommonIPPortDefinition(); m_vs_def.address = sSplit[0]; m_vs_def.port = Convert.ToInt32(sSplit[1]); } else { MessageBox.Show("Virtual Server must either exist on the BIG-IP or you must enter a addr:port combination"); m_vs_def = null; } } } private void comboBox_VirtualServer_TextChanged(object sender, EventArgs e) { } private void comboBox_VirtualServer_Leave(object sender, EventArgs e) { String vs = comboBox_VirtualServer.Text; if (comboBox_VirtualServer.SelectedIndex >= 0) { iControl.CommonIPPortDefinition[] vs_def_list = Clients.VirtualServer.get_destination(new string[] { vs }); if (vs_def_list.Length > 0) { m_vs_def = vs_def_list[0]; } } else { // user typed in address/port String[] sSplit = vs.Split(new char[] { ':' }); if (sSplit.Length == 2) { m_vs_def = new iControl.CommonIPPortDefinition(); m_vs_def.address = sSplit[0]; m_vs_def.port = Convert.ToInt32(sSplit[1]); } else { MessageBox.Show("Virtual Server must either exist on the BIG-IP or you must enter a addr:port combination"); comboBox_VirtualServer.Focus(); m_vs_def = null; } } } private void listView_HTTPHeaders_SelectedIndexChanged(object sender, EventArgs e) { button_HTTPHeaderRemove.Enabled = true; } private void listView_HTTPParameters_SelectedIndexChanged(object sender, EventArgs e) { button_HTTPParamRemove.Enabled = true; } private void textBox_HTTPHeaderName_TextChanged(object sender, EventArgs e) { if (textBox_HTTPHeaderName.Text.Length > 0) { button_HTTPHeaderAdd.Enabled = true; } } private void textBox_HTTPParamName_TextChanged(object sender, EventArgs e) { if (textBox_HTTPParamName.Text.Length > 0) { button_HTTPParamAdd.Enabled = true; } } private void textBox_HTTPParamValue_TextChanged(object sender, EventArgs e) { } private void button_HTTPHeaderAdd_Click(object sender, EventArgs e) { String sName = ""; String sValue = ""; if (textBox_HTTPHeaderName.Text.Length > 0) { sName = textBox_HTTPHeaderName.Text; sValue = textBox_HTTPHeaderValue.Text; ListViewItem lvi = new ListViewItem(); lvi.Text = sName; lvi.SubItems.Add(sValue); listView_HTTPHeaders.Items.Add(lvi); textBox_HTTPHeaderName.Text = ""; textBox_HTTPHeaderValue.Text = ""; } } private void button_HTTPHeaderRemove_Click(object sender, EventArgs e) { if (0 != listView_HTTPHeaders.SelectedIndices.Count) { int index = listView_HTTPHeaders.SelectedIndices[0]; ListViewItem lvi = listView_HTTPHeaders.Items[index]; textBox_HTTPHeaderName.Text = lvi.Text; textBox_HTTPHeaderValue.Text = lvi.SubItems[1].Text; listView_HTTPHeaders.Items.RemoveAt(index); } if (0 == listView_HTTPHeaders.SelectedIndices.Count) { button_HTTPHeaderRemove.Enabled = false; } } private void button_HTTPParamAdd_Click(object sender, System.EventArgs e) { String sName = ""; String sValue = ""; if (textBox_HTTPParamName.Text.Length > 0) { sName = textBox_HTTPParamName.Text; sValue = textBox_HTTPParamValue.Text; ListViewItem lvi = new ListViewItem(); lvi.Text = sName; lvi.SubItems.Add(sValue); listView_HTTPParameters.Items.Add(lvi); textBox_HTTPParamName.Text = ""; textBox_HTTPParamValue.Text = ""; } } private void button_HTTPParamRemove_Click(object sender, System.EventArgs e) { if (0 != listView_HTTPParameters.SelectedIndices.Count) { int index = listView_HTTPParameters.SelectedIndices[0]; ListViewItem lvi = listView_HTTPParameters.Items[index]; textBox_HTTPParamName.Text = lvi.Text; textBox_HTTPParamValue.Text = lvi.SubItems[1].Text; listView_HTTPParameters.Items.RemoveAt(index); } if (0 == listView_HTTPParameters.SelectedIndices.Count) { button_HTTPParamRemove.Enabled = false; } } private void button_StartStop_Click(object sender, EventArgs e) { if (button_StartStop.Text.Equals("Start")) { DoStart(); } else { DoStop(); } } private void button_Cancel_Click(object sender, EventArgs e) { DoStop(); this.DialogResult = DialogResult.Cancel; this.Close(); } private void backgroundWorker_traffic_DoWork(object sender, DoWorkEventArgs e) { ThreadInfo ti = (ThreadInfo)e.Argument; if (null != ti) { BackgroundWorker worker = sender as BackgroundWorker; worker.ReportProgress(0); System.Net.WebClient webClient = new System.Net.WebClient(); System.Collections.Specialized.NameValueCollection coll = new System.Collections.Specialized.NameValueCollection(); String sUrl = ""; String sMethod = ti.method; // build uri String sProtocol = (checkBox_SSL.Checked) ? "https" : "http"; sUrl = sProtocol + "://" + ti.vs_def.address + ":" + ti.vs_def.port.ToString() + ti.uri; if (sMethod.Equals("GET")) { } // add headers for (int i = 0; i < ti.header_names.Length; i++) { webClient.Headers.Add(ti.header_names[i], ti.header_values[i]); } // Loop through the listview items for (int i = 0; i < ti.param_names.Length; i++) { if (sMethod.Equals("POST")) { // add the name value pairs to the value collection coll.Add(ti.param_names[i], ti.param_values[i]); } else { // for GET's let's build the parameter list onto the URL. if (0 == i) { sUrl = sUrl + "?"; } else { sUrl = sUrl + "&"; } sUrl = sUrl + ti.param_names[i] + "=" + ti.param_values[i]; } } worker.ReportProgress(25); System.Net.NetworkCredential creds = new System.Net.NetworkCredential(ti.username, ti.password); webClient.Credentials = creds; if (null != ti.proxy) { webClient.Proxy = ti.proxy; } try { worker.ReportProgress(50); byte[] responseArray = null; if (sMethod.Equals("POST")) { responseArray = webClient.UploadValues(sUrl, sMethod, coll); } else { responseArray = webClient.DownloadData(sUrl); } worker.ReportProgress(75); String sResponse = ""; if (null != responseArray) { for (int i = 0; i < responseArray.Length; i++) { sResponse += (char)responseArray[i]; } } if (sResponse.Length > 0) { e.Result = "Request Succeeded\n" + sResponse; } } catch (Exception ex) { e.Result = ex.Message.ToString(); } webClient.Dispose(); worker.ReportProgress(100); } } private void backgroundWorker_traffic_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar_Status.Value = e.ProgressPercentage; progressBar_Status.Focus(); progressBar_Status.Refresh(); } private void backgroundWorker_traffic_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (null != e.Error) { statusMessage(e.Error.Message.ToString()); DoStop(); } else if (e.Cancelled) { statusMessage("Request cancelled by user"); DoStop(); } else if (null != e.Result) { statusMessage(e.Result.ToString()); if (!e.Result.ToString().StartsWith("Request Succeeded")) { DoStop(); } } else { statusMessage("Request succeeded."); } progressBar_Status.Value = 0; } private void numericUpDown_Interval_ValueChanged(object sender, EventArgs e) { if (numericUpDown_Interval.Value > 0) { timer_GenTraffic.Interval = Convert.ToInt32(numericUpDown_Interval.Value * 1000); } } private void timer_GenTraffic_Tick(object sender, EventArgs e) { generateTraffic(); } private void UseProxyCheckBox_CheckedChanged(object sender, EventArgs e) { ProxyServerTextBox.Enabled = UseProxyCheckBox.Checked; ProxyPortTextBox.Enabled = UseProxyCheckBox.Checked; } } public class ThreadInfo { //public ListView.ListViewItemCollection paramCollection = null; public String[] param_names = null; public String[] param_values = null; public String[] header_names = null; public String[] header_values = null; public iControl.CommonIPPortDefinition vs_def = null; public String uri = ""; public String method = ""; public String username = ""; public String password = ""; public System.Net.WebProxy proxy = null; }; }
using System; using System.Linq; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Forms; using Composite.C1Console.Forms.DataServices; using Composite.Core.Xml; using Composite.Data; using CompositeC1Contrib.FormBuilder.Configuration; using CompositeC1Contrib.FormBuilder.Data.Types; using CompositeC1Contrib.FormBuilder.Dynamic.Configuration; using CompositeC1Contrib.Localization; using CompositeC1Contrib.Workflows; namespace CompositeC1Contrib.FormBuilder.Dynamic.C1Console.Workflows { public abstract class BaseEditFormWorkflow : Basic1StepDocumentWorkflow { private readonly string _formFile; protected BaseEditFormWorkflow(string formFile) { _formFile = formFile; } protected void SetupFormData(IDynamicDefinition definition, IModel model) { Bindings.Add("Name", definition.Name); Bindings.Add("RequiresCaptcha", model.RequiresCaptcha); Bindings.Add("ForceHttpsConnection", model.ForceHttps); Bindings.Add("IntroText", GetValue("IntroText")); Bindings.Add("SuccessResponse", GetValue("SuccessResponse")); var markupProvider = new FormDefinitionFileMarkupProvider(_formFile); var formDocument = XDocument.Load(markupProvider.GetReader()); var root = formDocument.Root; var tabPanelElements = root?.Element(Namespaces.BindingForms10 + FormKeyTagNames.Layout)?.Element(Namespaces.BindingFormsStdUiControls10 + "TabPanels"); if (tabPanelElements == null) { return; } var bindingsXElement = root.Element(Namespaces.BindingForms10 + FormKeyTagNames.Bindings); var lastTabElement = tabPanelElements.Elements().Last(); LoadExtraSettings(definition, bindingsXElement, lastTabElement); DeliverFormData("EditForm", StandardUiContainerTypes.Document, formDocument.ToString(), Bindings, BindingsValidationRules); } private void LoadExtraSettings(IDynamicDefinition definition, XElement bindingsXElement, XElement lastTabElement) { var config = FormBuilderConfiguration.GetSection(); var plugin = (DynamicFormBuilderConfiguration)config.Plugins["dynamic"]; var settingsType = plugin.SettingsHandler; if (settingsType == null) { return; } var formFile = "\\InstalledPackages\\" + settingsType.Namespace + "\\" + settingsType.Name + ".xml"; var settingsMarkupProvider = new FormDefinitionFileMarkupProvider(formFile); var formDefinitionElement = XElement.Load(settingsMarkupProvider.GetReader()); var settingsTab = new XElement(Namespaces.BindingFormsStdUiControls10 + "PlaceHolder"); var layout = formDefinitionElement.Element(Namespaces.BindingForms10 + FormKeyTagNames.Layout); if (layout == null) { return; } var bindings = formDefinitionElement.Element(Namespaces.BindingForms10 + FormKeyTagNames.Bindings); if (bindings == null) { return; } settingsTab.Add(new XAttribute("Label", "Extra Settings")); settingsTab.Add(layout.Elements()); bindingsXElement.Add(bindings.Elements()); lastTabElement.AddAfterSelf(settingsTab); var settings = definition.Settings ?? (IFormSettings)Activator.CreateInstance(settingsType); foreach (var prop in settingsType.GetProperties()) { var value = prop.GetValue(settings, null); Bindings.Add(prop.Name, value); } } public override bool Validate() { var token = GetBinding<DataEntityToken>("BoundToken"); var modelReference = (IModelReference)token.Data; var name = GetBinding<string>("Name"); if (name == modelReference.Name) { return true; } if (!FormModel.IsValidName(name)) { ShowFieldMessage("Name", "Invalid form name, only a-z, 0-9 and symbols - is allowed"); return false; } var isNameInUse = DefinitionsFacade.GetDefinitions().Any(m => m.Name == name); if (!isNameInUse) { return true; } ShowFieldMessage("Name", "Form name already exists"); return false; } protected void Save(IDynamicDefinition definition) { SaveExtraSettings(definition); var token = GetBinding<DataEntityToken>("BoundToken"); var modelReference = (IModelReference)token.Data; var name = GetBinding<string>("Name"); var introText = GetBinding<string>("IntroText"); var successResponse = GetBinding<string>("SuccessResponse"); using (var writer = ResourceFacade.GetResourceWriter()) { writer.AddResource(GetKey("IntroText"), introText); writer.AddResource(GetKey("SuccessResponse"), successResponse); } var isNewName = name != modelReference.Name; if (isNewName) { LocalizationsFacade.RenameNamespace(Localization.KeyPrefix + "." + modelReference.Name, Localization.KeyPrefix + "." + name, Localization.ResourceSet); DefinitionsFacade.Copy(definition, name); DefinitionsFacade.Delete(definition); modelReference = ModelReferenceFacade.GetModelReference(name); token = modelReference.GetDataEntityToken(); UpdateBinding("BoundToken", token); SetSaveStatus(true, token); } else { DefinitionsFacade.Save(definition); SetSaveStatus(true); } CreateParentTreeRefresher().PostRefreshMessages(EntityToken); } private void SaveExtraSettings(IDynamicDefinition definition) { var config = FormBuilderConfiguration.GetSection(); var plugin = (DynamicFormBuilderConfiguration)config.Plugins["dynamic"]; var settingsType = plugin.SettingsHandler; if (settingsType == null) { definition.Settings = null; return; } definition.Settings = (IFormSettings)Activator.CreateInstance(settingsType); foreach (var prop in settingsType.GetProperties().Where(p => BindingExist(p.Name))) { var value = GetBinding<object>(prop.Name); prop.SetValue(definition.Settings, value, null); } } protected string GetValue(string setting) { var key = GetKey(setting); return Localization.T(key); } protected string GetKey(string setting) { var formToken = GetBinding<DataEntityToken>("BoundToken"); var modelReference = (IModelReference)formToken.Data; return Localization.GenerateKey(modelReference.Name, setting); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: Contains the business logic for symbology layers and symbol categories. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 5/21/2009 12:37:32 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Drawing; using System.Drawing.Drawing2D; using DotSpatial.Serialization; namespace DotSpatial.Symbology { public class GradientPattern : Pattern, IGradientPattern { #region Private Variables private double _angle; private Color[] _colors; private GradientType _gradientType; private float[] _positions; #endregion #region Constructors /// <summary> /// Creates a new instance of GradientPattern /// </summary> public GradientPattern() { _gradientType = GradientType.Linear; _colors = new Color[2]; _colors[0] = SymbologyGlobal.RandomLightColor(1F); _colors[1] = _colors[0].Darker(.3F); _positions = new[] { 0F, 1F }; _angle = -45; } /// <summary> /// Creates a new instance of a Gradient Pattern using the specified colors /// </summary> /// <param name="startColor"></param> /// <param name="endColor"></param> public GradientPattern(Color startColor, Color endColor) { _gradientType = GradientType.Linear; _colors = new Color[2]; _colors[0] = startColor; _colors[1] = endColor; _positions = new[] { 0F, 1F }; _angle = -45; } /// <summary> /// Creates a new instance of a Gradient Pattern using the specified colors and angle /// </summary> /// <param name="startColor">The start color</param> /// <param name="endColor">The end color</param> /// <param name="angle">The direction of the gradient, measured in degrees clockwise from the x-axis</param> public GradientPattern(Color startColor, Color endColor, double angle) { _gradientType = GradientType.Linear; _colors = new Color[2]; _colors[0] = startColor; _colors[1] = endColor; _positions = new[] { 0F, 1F }; _angle = angle; } /// <summary> /// Creates a new instance of a Gradient Pattern using the specified colors and angle /// </summary> /// <param name="startColor">The start color</param> /// <param name="endColor">The end color</param> /// <param name="angle">The direction of the gradient, measured in degrees clockwise from the x-axis</param> /// <param name="style">Controls how the gradient is drawn</param> public GradientPattern(Color startColor, Color endColor, double angle, GradientType style) { _gradientType = style; _colors = new Color[2]; _colors[0] = startColor; _colors[1] = endColor; _positions = new[] { 0F, 1F }; _angle = angle; } #endregion #region Methods /// <summary> /// Gets a color that can be used to represent this pattern. In some cases, a color is not /// possible, in which case, this returns Gray. /// </summary> /// <returns>A single System.Color that can be used to represent this pattern.</returns> public override Color GetFillColor() { Color l = _colors[0]; Color h = _colors[_colors.Length - 1]; int a = (l.A + h.A) / 2; int r = (l.R + h.R) / 2; int g = (l.G + h.G) / 2; int b = (l.B + h.B) / 2; return Color.FromArgb(a, r, g, b); } /// <summary> /// Sets the fill color, keeping the approximate gradiant RGB changes the same, but adjusting /// the mean color to the specifeid color. /// </summary> /// <param name="color">The mean color to apply.</param> public override void SetFillColor(Color color) { if (_colors == null || _colors.Length == 0) return; if (_colors.Length == 1) { _colors[0] = color; return; } Color l = _colors[0]; Color h = _colors[_colors.Length - 1]; int da = (h.A - l.A) / 2; int dr = (h.R - l.R) / 2; int dg = (h.G - l.G) / 2; int db = (h.B - l.B) / 2; _colors[0] = Color.FromArgb(ByteSize(color.A - da), ByteSize(color.R - dr), ByteSize(color.G - dg), ByteSize(color.B - db)); _colors[_colors.Length - 1] = Color.FromArgb(ByteSize(color.A + da), ByteSize(color.R + dr), ByteSize(color.G + dg), ByteSize(color.B + db)); } private static int ByteSize(int value) { if (value > 255) return 255; return value < 0 ? 0 : value; } #endregion #region Properties /// <summary> /// Gets or sets the angle for the gradient pattern. /// </summary> [Serialize("Angle")] public double Angle { get { return _angle; } set { _angle = value; } } /// <summary> /// Gets or sets the end color /// </summary> [Serialize("Colors")] public Color[] Colors { get { return _colors; } set { _colors = value; } } /// <summary> /// Gets or sets the start color /// </summary> [Serialize("Positions")] public float[] Positions { get { return _positions; } set { _positions = value; } } /// <summary> /// Gets or sets the gradient type /// </summary> [Serialize("GradientTypes")] public GradientType GradientType { get { return _gradientType; } set { _gradientType = value; } } #endregion #region Protected Methods /// <summary> /// Handles the drawing code for linear gradient paths. /// </summary> /// <param name="g"></param> /// <param name="gp"></param> public override void FillPath(Graphics g, GraphicsPath gp) { RectangleF bounds = Bounds; if (bounds.IsEmpty) bounds = gp.GetBounds(); if (bounds.Width == 0 || bounds.Height == 0) return; //also don't draw gradient for very small polygons if (bounds.Width < 0.01 || bounds.Height < 0.01) return; if (_gradientType == GradientType.Linear) { LinearGradientBrush b = new LinearGradientBrush(bounds, _colors[0], _colors[_colors.Length - 1], (float)-_angle); ColorBlend cb = new ColorBlend(); cb.Positions = _positions; cb.Colors = _colors; b.InterpolationColors = cb; g.FillPath(b, gp); b.Dispose(); } else if (_gradientType == GradientType.Circular) { GraphicsPath round = new GraphicsPath(); PointF center = new PointF(bounds.X + bounds.Width / 2, bounds.Y + bounds.Height / 2); float x = (float)(center.X - Math.Sqrt(2) * bounds.Width / 2); float y = (float)(center.Y - Math.Sqrt(2) * bounds.Height / 2); float w = (float)(bounds.Width * Math.Sqrt(2)); float h = (float)(bounds.Height * Math.Sqrt(2)); RectangleF circum = new RectangleF(x, y, w, h); round.AddEllipse(circum); PathGradientBrush pgb = new PathGradientBrush(round); ColorBlend cb = new ColorBlend(); cb.Colors = _colors; cb.Positions = _positions; pgb.InterpolationColors = cb; g.FillPath(pgb, gp); pgb.Dispose(); } else if (_gradientType == GradientType.Rectangular) { GraphicsPath rect = new GraphicsPath(); PointF[] points = new PointF[5]; PointF center = new PointF(bounds.X + bounds.Width / 2, bounds.Y + bounds.Height / 2); double a = bounds.Width / 2; double b = bounds.Height / 2; double angle = _angle; if (angle < 0) angle = 360 + angle; angle = angle % 90; angle = 2 * (Math.PI * angle / 180); double x = a * Math.Cos(angle); double y = -b - a * Math.Sin(angle); points[0] = new PointF((float)x + center.X, (float)y + center.Y); x = a + b * Math.Sin(angle); y = b * Math.Cos(angle); points[1] = new PointF((float)x + center.X, (float)y + center.Y); x = -a * Math.Cos(angle); y = b + a * Math.Sin(angle); points[2] = new PointF((float)x + center.X, (float)y + center.Y); x = -a - b * Math.Sin(angle); y = -b * Math.Cos(angle); points[3] = new PointF((float)x + center.X, (float)y + center.Y); points[4] = points[0]; rect.AddPolygon(points); PathGradientBrush pgb = new PathGradientBrush(rect); ColorBlend cb = new ColorBlend(); cb.Colors = _colors; cb.Positions = _positions; pgb.InterpolationColors = cb; g.FillPath(pgb, gp); pgb.Dispose(); } } #endregion } }
// Copyright 2018 Esri. // // 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 Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.Xamarin.Forms; using System; using System.Collections.Generic; using Xamarin.Forms; using Color = System.Drawing.Color; namespace ArcGISRuntime.Samples.BufferList { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Buffer list", category: "Geometry", description: "Generate multiple individual buffers or a single unioned buffer around multiple points.", instructions: "Click/tap on the map to add points. Tap the \"Create Buffer(s)\" button to draw buffer(s) around the points (the size of the buffer is determined by the value entered by the user). Check the check box if you want the result to union (combine) the buffers. Tap the \"Clear\" button to start over. The red dashed envelope shows the area where you can expect reasonable results for planar buffer operations with the North Central Texas State Plane spatial reference.", tags: new[] { "analysis", "buffer", "geometry", "planar" })] public partial class BufferList : ContentPage { // A polygon that defines the valid area of the spatial reference used. private Polygon _spatialReferenceArea; // A Random object to create RGB color values. private Random _random = new Random(); public BufferList() { InitializeComponent(); // Bind the view to this page. BindingContext = this; // Create the map and graphics overlays. Initialize(); } private void Initialize() { // Create a spatial reference that's suitable for creating planar buffers in north central Texas (State Plane). SpatialReference statePlaneNorthCentralTexas = new SpatialReference(32038); // Define a polygon that represents the valid area of use for the spatial reference. // This information is available at https://developers.arcgis.com/net/latest/wpf/guide/pdf/projected_coordinate_systems_rt100_3_0.pdf List<MapPoint> spatialReferenceExtentCoords = new List<MapPoint> { new MapPoint(-103.070, 31.720, SpatialReferences.Wgs84), new MapPoint(-103.070, 34.580, SpatialReferences.Wgs84), new MapPoint(-94.000, 34.580, SpatialReferences.Wgs84), new MapPoint(-94.00, 31.720, SpatialReferences.Wgs84) }; _spatialReferenceArea = new Polygon(spatialReferenceExtentCoords); _spatialReferenceArea = GeometryEngine.Project(_spatialReferenceArea, statePlaneNorthCentralTexas) as Polygon; // Create a map that uses the North Central Texas state plane spatial reference. Map bufferMap = new Map(statePlaneNorthCentralTexas); // Add some base layers (counties, cities, and highways). Uri usaLayerSource = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer"); ArcGISMapImageLayer usaLayer = new ArcGISMapImageLayer(usaLayerSource); bufferMap.Basemap.BaseLayers.Add(usaLayer); // Use a new EnvelopeBuilder to expand the spatial reference extent 120%. EnvelopeBuilder envBuilder = new EnvelopeBuilder(_spatialReferenceArea.Extent); envBuilder.Expand(1.2); // Set the map's initial extent to the expanded envelope. Envelope startingEnvelope = envBuilder.ToGeometry(); bufferMap.InitialViewpoint = new Viewpoint(startingEnvelope); // Assign the map to the MapView. MyMapView.Map = bufferMap; // Create a graphics overlay to show the buffer polygon graphics. GraphicsOverlay bufferGraphicsOverlay = new GraphicsOverlay { // Give the overlay an ID so it can be found later. Id = "buffers" }; // Create a graphic to show the spatial reference's valid extent (envelope) with a dashed red line. SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.Red, 5); Graphic spatialReferenceExtentGraphic = new Graphic(_spatialReferenceArea, lineSymbol); // Add the graphic to a new overlay. GraphicsOverlay spatialReferenceGraphicsOverlay = new GraphicsOverlay(); spatialReferenceGraphicsOverlay.Graphics.Add(spatialReferenceExtentGraphic); // Add the graphics overlays to the MapView. MyMapView.GraphicsOverlays.Add(bufferGraphicsOverlay); MyMapView.GraphicsOverlays.Add(spatialReferenceGraphicsOverlay); // Wire up the MapView's GeoViewTapped event handler. MyMapView.GeoViewTapped += MyMapView_GeoViewTapped; } private void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e) { try { // Get the input map point (in the map's coordinate system, State Plane for North Central Texas). MapPoint tapMapPoint = e.Location; // Check if the point coordinates are within the spatial reference envelope. bool withinValidExent = GeometryEngine.Contains(_spatialReferenceArea, tapMapPoint); // If the input point is not within the valid extent for the spatial reference, warn the user and return. if (!withinValidExent) { DisplayAlert("Out of bounds", "Location is not valid to buffer using the defined spatial reference.", "OK"); return; } // Get the buffer radius (in miles) from the text box. double bufferDistanceMiles = Convert.ToDouble(BufferDistanceMilesEntry.Text); // Use a helper method to get the buffer distance in feet (unit that's used by the spatial reference). double bufferDistanceFeet = LinearUnits.Miles.ConvertTo(LinearUnits.Feet, bufferDistanceMiles); // Create a simple marker symbol (red circle) to display where the user tapped/clicked on the map. SimpleMarkerSymbol tapSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Red, 10); // Create a new graphic to show the tap location. Graphic tapGraphic = new Graphic(tapMapPoint, tapSymbol) { // Specify a z-index value on the point graphic to make sure it draws on top of the buffer polygons. ZIndex = 2 }; // Store the specified buffer distance as an attribute with the graphic. tapGraphic.Attributes["distance"] = bufferDistanceFeet; // Add the tap point graphic to the buffer graphics overlay. MyMapView.GraphicsOverlays["buffers"].Graphics.Add(tapGraphic); } catch (Exception ex) { // Display an error message. DisplayAlert("Error creating buffer point", ex.Message, "OK"); } } private void BufferButton_Click(object sender, EventArgs e) { try { // Call a function to delete any existing buffer polygons so they can be recreated. ClearBufferPolygons(); // Check if the user wants to create a single unioned buffer or independent buffers around each map point. bool areBuffersUnioned = UnionSwitch.IsToggled; // Iterate all point graphics and create a list of map points and buffer distances for each. List<MapPoint> bufferMapPoints = new List<MapPoint>(); List<double> bufferDistances = new List<double>(); foreach (Graphic bufferGraphic in MyMapView.GraphicsOverlays["buffers"].Graphics) { // Only use point graphics. if (bufferGraphic.Geometry.GeometryType == GeometryType.Point) { // Get the geometry (map point) from the graphic. MapPoint bufferLocation = bufferGraphic.Geometry as MapPoint; // Read the "distance" attribute to get the buffer distance entered when the point was tapped. double bufferDistanceFeet = (double)bufferGraphic.Attributes["distance"]; // Add the point and the corresponding distance to the lists. bufferMapPoints.Add(bufferLocation); bufferDistances.Add(bufferDistanceFeet); } } // Call GeometryEngine.Buffer with a list of map points and a list of buffered distances. IEnumerable<Geometry> bufferPolygons = GeometryEngine.Buffer(bufferMapPoints, bufferDistances, areBuffersUnioned); // Create the outline for the buffered polygons. SimpleLineSymbol bufferPolygonOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.DarkBlue, 3); // Loop through all the geometries in the buffer results. There will be one buffered polygon if // the result geometries were unioned. Otherwise, there will be one buffer per input geometry. foreach (Geometry poly in bufferPolygons) { // Create a random color to use for buffer polygon fill. Color bufferPolygonColor = GetRandomColor(); // Create simple fill symbol for the buffered polygon using the fill color and outline. SimpleFillSymbol bufferPolygonFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, bufferPolygonColor, bufferPolygonOutlineSymbol); // Create a new graphic for the buffered polygon using the fill symbol. Graphic bufferPolygonGraphic = new Graphic(poly, bufferPolygonFillSymbol) { // Specify a z-index of 0 to ensure the polygons draw below the tap points. ZIndex = 0 }; // Add the buffered polygon graphic to the graphics overlay. MyMapView.GraphicsOverlays[0].Graphics.Add(bufferPolygonGraphic); } } catch (Exception ex) { // Display an error message if there is a problem generating the buffers. DisplayAlert("Unable to create buffer polygons", ex.Message, "OK"); } } private Color GetRandomColor() { // Get a byte array with three random values. var colorBytes = new byte[3]; _random.NextBytes(colorBytes); // Use the random bytes to define red, green, and blue values for a new color. return Color.FromArgb(155, colorBytes[0], colorBytes[1], colorBytes[2]); } private void ClearButton_Click(object sender, EventArgs e) { // Clear all graphics (tap points and buffer polygons). MyMapView.GraphicsOverlays["buffers"].Graphics.Clear(); } private void ClearBufferPolygons() { // Get the collection of graphics in the graphics overlay (points and buffer polygons). GraphicCollection bufferGraphics = MyMapView.GraphicsOverlays["buffers"].Graphics; // Loop (backwards) through all graphics. for (int i = bufferGraphics.Count - 1; i >= 0; i--) { // If the graphic is a polygon, remove it from the overlay. Graphic thisGraphic = bufferGraphics[i]; if (thisGraphic.Geometry.GeometryType == GeometryType.Polygon) { bufferGraphics.RemoveAt(i); } } } } }
// 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 AndUInt32() { var test = new SimpleBinaryOpTest__AndUInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // 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(); // 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(); // 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__AndUInt32 { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[ElementCount]; private static UInt32[] _data2 = new UInt32[ElementCount]; private static Vector256<UInt32> _clsVar1; private static Vector256<UInt32> _clsVar2; private Vector256<UInt32> _fld1; private Vector256<UInt32> _fld2; private SimpleBinaryOpTest__DataTable<UInt32> _dataTable; static SimpleBinaryOpTest__AndUInt32() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__AndUInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt32>(_data1, _data2, new UInt32[ElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.And( Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.And( Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.And( Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr); var result = Avx2.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AndUInt32(); var result = Avx2.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.And(_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(Vector256<UInt32> left, Vector256<UInt32> right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[ElementCount]; UInt32[] inArray2 = new UInt32[ElementCount]; UInt32[] outArray = new UInt32[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, 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 = "") { UInt32[] inArray1 = new UInt32[ElementCount]; UInt32[] inArray2 = new UInt32[ElementCount]; UInt32[] outArray = new UInt32[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { if ((uint)(left[0] & right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((uint)(left[i] & right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.And)}<UInt32>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// 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 Test.Cryptography; namespace System.Security.Cryptography.Tests { // Note to contributors: // Keys contained in this file should be randomly generated for the purpose of inclusion here, // or obtained from some fixed set of test data. (Please) DO NOT use any key that has ever been // used for any real purpose. // // Note to readers: // The keys contained in this file should all be treated as compromised. That means that you // absolutely SHOULD NOT use these keys on anything that you actually want to be protected. internal static class EccTestData { internal static readonly byte[] s_hashSha512 = ("a232cec7be26319e53db0d48470232d37793b06b99e8ed82fac1996b3d1596449087769927d64af657cce62d853c4cf7ff4c" + "d069eda230d1c524d225756ffbaf").HexToByteArray(); internal static ECCurve GetNistP256ExplicitCurve() { // SEC2-Ver-1.0, 2.7.2 return new ECCurve { CurveType = ECCurve.ECCurveType.PrimeShortWeierstrass, Prime = "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF".HexToByteArray(), A = "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC".HexToByteArray(), B = "5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B".HexToByteArray(), Seed = "C49D360886E704936A6678E1139D26B7819F7E90".HexToByteArray(), Hash = HashAlgorithmName.SHA1, G = new ECPoint { X = "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296".HexToByteArray(), Y = "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5".HexToByteArray(), }, Order = "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551".HexToByteArray(), Cofactor = new byte[] { 0x01 }, }; } internal static ECCurve GetNistP384ExplicitCurve() { // SEC2-Ver-1.0, 2.8.1 return new ECCurve { CurveType = ECCurve.ECCurveType.PrimeShortWeierstrass, Prime = ("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" + "FFFFFFFEFFFFFFFF0000000000000000FFFFFFFF").HexToByteArray(), A = ("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" + "FFFFFFFEFFFFFFFF0000000000000000FFFFFFFC").HexToByteArray(), B = ("B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F" + "5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF").HexToByteArray(), Seed = "A335926AA319A27A1D00896A6773A4827ACDAC73".HexToByteArray(), Hash = HashAlgorithmName.SHA1, G = new ECPoint { X = ("AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E0" + "82542A385502F25DBF55296C3A545E3872760AB7").HexToByteArray(), Y = ("3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113" + "B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F").HexToByteArray(), }, Order = ("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81" + "F4372DDF581A0DB248B0A77AECEC196ACCC52973").HexToByteArray(), Cofactor = new byte[] { 0x01 }, }; } internal static ECCurve GetNistP521ExplicitCurve() { // SEC2-Ver-1.0, 2.9.1 return new ECCurve { CurveType = ECCurve.ECCurveType.PrimeShortWeierstrass, Prime = ("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" + "FFFFFFFFFFFFFFFFFFFFFFFF").HexToByteArray(), A = ("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" + "FFFFFFFFFFFFFFFFFFFFFFFC").HexToByteArray(), B = ("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3" + "B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF88" + "3D2C34F1EF451FD46B503F00").HexToByteArray(), Seed = "D09E8800291CB85396CC6717393284AAA0DA64BA".HexToByteArray(), Hash = HashAlgorithmName.SHA1, G = new ECPoint { // The formatting in the document is the full binary G, with the // last 2 bytes of X sharing a 4 byte clustering with the first // 2 bytes of Y; hence the odd formatting. X = ("00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828" + "AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A" + "429BF97E7E31C2E5" + "BD66").HexToByteArray(), Y = ("0118" + "39296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17" + "273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C240" + "88BE94769FD16650").HexToByteArray(), }, Order = ("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" + "FFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8" + "899C47AEBB6FB71E91386409").HexToByteArray(), Cofactor = new byte[] { 0x01 }, }; } internal static ECParameters GetNistP256ExplicitTestData() { // explicit values for s_Ecc256Key (nistP256) ECParameters p = new ECParameters(); p.Q = new ECPoint { X = ("96E476F7473CB17C5B38684DAAE437277AE1EFADCEB380FAD3D7072BE2FFE5F0").HexToByteArray(), Y = ("B54A94C2D6951F073BFC25E7B81AC2A4C41317904929D167C3DFC99122175A94").HexToByteArray() }; ECCurve c = p.Curve; c.CurveType = ECCurve.ECCurveType.PrimeShortWeierstrass; c.A = ("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC").HexToByteArray(); c.B = ("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B").HexToByteArray(); c.G = new ECPoint() { X = ("6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296").HexToByteArray(), Y = ("4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5").HexToByteArray(), }; c.Cofactor = ("01").HexToByteArray(); c.Order = ("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551").HexToByteArray(); c.Prime = ("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF").HexToByteArray(); c.Seed = null; c.Hash = null; p.Curve = c; return p; } internal static ECParameters GetNistP224KeyTestData() { // key values for nistP224 ECParameters p = new ECParameters(); p.Q = new ECPoint { X = ("00B6C6FA7EFF084CEF007B414690027085173AAB846906C964D900C0").HexToByteArray(), Y = ("845213F2A07DDE66EE0B19021E62C721A0FBF41E878FB2A34C40C872").HexToByteArray() }; p.D = ("CE57F5C60F208819DC5FB994FF4EB4E11D40694B5E79564C2688B756").HexToByteArray(); p.Curve = ECCurve.CreateFromOid(new Oid("1.3.132.0.33", "nistP224")); return p; } internal static ECParameters GetNistP521DiminishedCoordsParameters() { return new ECParameters { Curve = ECCurve.NamedCurves.nistP521, // Qx, Qy, and d start with 0x00, which should be preserved. Q = new ECPoint { X = ( "00DCB499D2B8174A2A2E74F23D2EA6C5F8BC8B311574E94B7E590B1EBC28665E5A" + "2C021183F10A0B23E34EC9BED2F59525CC45CFB0E6870FD61EA4FFEAFBD08CDF73").HexToByteArray(), Y = ( "008EA45062A8CEF4A4CE10449281D98B74A7EBBA9B5597DF842A9B1FA73B46A0E7" + "22C005FD49C141E43A5C10E77F1185C5233E6BE016998EF5CE09FC3936E3208B87").HexToByteArray(), }, D = ( "0029B61CD0B8670DCFA6B2ED44677C23D134C4A802D8E2B4D6FF563BE1F010EDA7" + "956FA22DD3C8682751296C129D55F8F8C15483103D99899446E13285998B7E0F05").HexToByteArray(), }; } internal static ECParameters GetNistP521Key2() { return new ECParameters { Curve = ECCurve.NamedCurves.nistP521, Q = { X = ( "00751F26324C73CEF5D45EBB32937E3060E351960A57594AD03EB1CA0C5EA747" + "1213366BA991D24406717F86FDEFDE086E09B954A57DC0F5E9459756D60C2AAE" + "6DE0").HexToByteArray(), Y = ( "01A8DDBB3F02C8C23524729F548B7E23325233EF67DD30752B924F297459E3C2" + "E12AE8D8F4FE4454E3847C18B255CACEF59737B918E1DE40F95E9FFE4F57B791" + "53A0").HexToByteArray(), }, D = ( "01A55F8785A5730BAEE1D6B3D301069F7FD64D8B04CCEA57EFD5961E68F33FAB" + "43545166CA6553CD38FF713D1289C698BD7D086B55E01B5BD5ED27E3630376B1" + "1666").HexToByteArray(), }; } internal static ECParameters GetNistP256ReferenceKey() { // From Suite B Implementers's Guide to FIPS 186-3 (ECDSA) // Section D.1.1 return new ECParameters { Curve = ECCurve.NamedCurves.nistP256, Q = { X = "8101ECE47464A6EAD70CF69A6E2BD3D88691A3262D22CBA4F7635EAFF26680A8".HexToByteArray(), Y = "D8A12BA61D599235F67D9CB4D58F1783D3CA43E78F0A5ABAA624079936C0C3A9".HexToByteArray(), }, D = "70A12C2DB16845ED56FF68CFC21A472B3F04D7D6851BF6349F2D7D5B3452B38A".HexToByteArray(), }; } internal static ECParameters GetNistP256ReferenceKeyExplicit() { // From Suite B Implementers's Guide to FIPS 186-3 (ECDSA) // Section D.1.1 return new ECParameters { Curve = GetNistP256ExplicitCurve(), Q = { X = "8101ECE47464A6EAD70CF69A6E2BD3D88691A3262D22CBA4F7635EAFF26680A8".HexToByteArray(), Y = "D8A12BA61D599235F67D9CB4D58F1783D3CA43E78F0A5ABAA624079936C0C3A9".HexToByteArray(), }, D = "70A12C2DB16845ED56FF68CFC21A472B3F04D7D6851BF6349F2D7D5B3452B38A".HexToByteArray(), }; } internal static readonly ECParameters BrainpoolP160r1Key1 = new ECParameters { Curve = ECCurve.NamedCurves.brainpoolP160r1, Q = { X = "8E628F0939C7629276CADBFE99C01C36509354E2".HexToByteArray(), Y = "72D2C8EEF1F6CC3205D0057EB9DE6CA9E3105096".HexToByteArray(), }, D = "C5D944547DE115DB2588DC6FDEBA3B473E9C4D96".HexToByteArray(), }; internal static readonly ECParameters Sect163k1Key1 = new ECParameters { Curve = ECCurve.CreateFromValue("1.3.132.0.1"), Q = { X = "06179E3719CC8125435FE64589D5FCA6DC1887551D".HexToByteArray(), Y = "0788FEBB62FFC9248D8B398AFE3E0B5C3C02B3FE37".HexToByteArray(), }, D = "03C1995ADFAE8C0518DC13DFE6304BB01017E6A412".HexToByteArray(), }; internal static readonly ECParameters Sect163k1Key1Explicit = new ECParameters { Curve = { CurveType = ECCurve.ECCurveType.Characteristic2, Polynomial = "0800000000000000000000000000000000000000C9".HexToByteArray(), A = "000000000000000000000000000000000000000001".HexToByteArray(), B = "000000000000000000000000000000000000000001".HexToByteArray(), G = { X = "02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8".HexToByteArray(), Y = "0289070FB05D38FF58321F2E800536D538CCDAA3D9".HexToByteArray(), }, Order = "04000000000000000000020108A2E0CC0D99F8A5EF".HexToByteArray(), Cofactor = new byte[] { 2 }, }, Q = { X = "06179E3719CC8125435FE64589D5FCA6DC1887551D".HexToByteArray(), Y = "0788FEBB62FFC9248D8B398AFE3E0B5C3C02B3FE37".HexToByteArray(), }, D = "03C1995ADFAE8C0518DC13DFE6304BB01017E6A412".HexToByteArray(), }; internal static readonly ECParameters Sect283k1Key1 = new ECParameters { Curve = ECCurve.CreateFromValue("1.3.132.0.16"), Q = { X = "0752770BD33E6A6EE2096CB6B120E7497B47B6C077A147CB57DAF693909D840716EEA7AA".HexToByteArray(), Y = "047DB9995C35603C5E6B2F8CDFF0EB71D37AE3431BA0849EBAB13A4C9003C7969F55CD90".HexToByteArray(), }, D = "00B4F1AE1E7FDCD4B0E82053C08A908852B26231E6C01670FCC6C3EA2C5D3FED40EDF037".HexToByteArray(), }; internal static readonly ECParameters C2pnb163v1Key1 = new ECParameters { Curve = ECCurve.CreateFromValue("1.2.840.10045.3.0.1"), Q = { X = "0211272F1C5582426888E91BD692577494232248AA".HexToByteArray(), Y = "04270830F7A1009AD670A88DE92BD59248CC813B45".HexToByteArray(), }, D = "00F4D24A1407122F445967BE1D93C0093A65367986".HexToByteArray(), }; internal static readonly ECParameters C2pnb163v1Key1Explicit = new ECParameters { Curve = { CurveType = ECCurve.ECCurveType.Characteristic2, Polynomial = "080000000000000000000000000000000000000107".HexToByteArray(), A = "072546B5435234A422E0789675F432C89435DE5242".HexToByteArray(), B = "00C9517D06D5240D3CFF38C74B20B6CD4D6F9DD4D9".HexToByteArray(), G = { X = "07AF69989546103D79329FCC3D74880F33BBE803CB".HexToByteArray(), Y = "01EC23211B5966ADEA1D3F87F7EA5848AEF0B7CA9F".HexToByteArray(), }, Order = "0400000000000000000001E60FC8821CC74DAEAFC1".HexToByteArray(), Cofactor = new byte[] { 2 }, }, Q = { X = "0211272F1C5582426888E91BD692577494232248AA".HexToByteArray(), Y = "04270830F7A1009AD670A88DE92BD59248CC813B45".HexToByteArray(), }, D = "00F4D24A1407122F445967BE1D93C0093A65367986".HexToByteArray(), }; } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Text.RegularExpressions; public class SquareCovering { int n, c1, c2, k1, k2; int[] px, py; public int getMinimalSide(int[] x, int[] y) { px = x; py = y; n = px.Length; c1 = c2 = px[0]; k1 = k2 = py[0]; for (int i = 0; i < n; i++) { if (c1 > px[i]) c1 = px[i]; if (c2 < px[i]) c2 = px[i]; if (k1 > py[i]) k1 = py[i]; if (k2 < py[i]) k2 = py[i]; } if (k2 - k1 < c2 - c1) { int t = k1; k1 = k2 - (c2 - c1); if (!check()) { k1 = t; t = k2; k2 = (c2 - c1) + k1; if (!check()) return -1; else return c2 - c1; } else { return c2 - c1; } } else if (k2 - k1 > c2 - c1) { int t = c1; c1 = c2 - (k2 - k1); if (!check()) { c1 = t; t = c2; c2 = (k2 - k1) + c1; if (!check()) return -1; else return k2 - k1; } else { return k2 - k1; } } else { if (!check()) return -1; else return c2 - c1; } } private bool check() { for (int i = 0; i < n; i++) { if (px[i] == c1 || px[i] == c2) { if (py[i] > k2 || py[i] < k1) return false; } if (py[i] == k1 || py[i] == k2) { if (px[i] > c2 || px[i] < c1) return false; } if (!(px[i] == c1 || px[i] == c2) && !(py[i] == k1 || py[i] == k2)) { return false; } } return true; } // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.4 (beta) modified by pivanof #region Testing code generated by KawigiEdit [STAThread] private static Boolean KawigiEdit_RunTest(int testNum, int[] p0, int[] p1, Boolean hasAnswer, int p2) { Console.Write("Test " + testNum + ": [" + "{"); for (int i = 0; p0.Length > i; ++i) { if (i > 0) { Console.Write(","); } Console.Write(p0[i]); } Console.Write("}" + "," + "{"); for (int i = 0; p1.Length > i; ++i) { if (i > 0) { Console.Write(","); } Console.Write(p1[i]); } Console.Write("}"); Console.WriteLine("]"); SquareCovering obj; int answer; obj = new SquareCovering(); DateTime startTime = DateTime.Now; answer = obj.getMinimalSide(p0, p1); DateTime endTime = DateTime.Now; Boolean res; res = true; Console.WriteLine("Time: " + (endTime - startTime).TotalSeconds + " seconds"); if (hasAnswer) { Console.WriteLine("Desired answer:"); Console.WriteLine("\t" + p2); } Console.WriteLine("Your answer:"); Console.WriteLine("\t" + answer); if (hasAnswer) { res = answer == p2; } if (!res) { Console.WriteLine("DOESN'T MATCH!!!!"); } else if ((endTime - startTime).TotalSeconds >= 2) { Console.WriteLine("FAIL the timeout"); res = false; } else if (hasAnswer) { Console.WriteLine("Match :-)"); } else { Console.WriteLine("OK, but is it right?"); } Console.WriteLine(""); return res; } public static void Main(string[] args) { Boolean all_right; all_right = true; int[] p0; int[] p1; int p2; // ----- test 0 ----- p0 = new int[]{0,1}; p1 = new int[]{0,1}; p2 = 1; all_right = KawigiEdit_RunTest(0, p0, p1, true, p2) && all_right; // ------------------ // ----- test 1 ----- p0 = new int[]{0,1,2}; p1 = new int[]{0,1,2}; p2 = -1; all_right = KawigiEdit_RunTest(1, p0, p1, true, p2) && all_right; // ------------------ // ----- test 2 ----- p0 = new int[]{1,-3,2}; p1 = new int[]{1,0,-4}; p2 = 5; all_right = KawigiEdit_RunTest(2, p0, p1, true, p2) && all_right; // ------------------ // ----- test 3 ----- p0 = new int[]{-10,0,3,-1}; p1 = new int[]{0,-1,3,4}; p2 = -1; all_right = KawigiEdit_RunTest(3, p0, p1, true, p2) && all_right; // ------------------ // ----- test 4 ----- p0 = new int[]{1,2,3,4,5,6,7,8,9,10}; p1 = new int[]{1000,1000,1000,1000,1000,1000,1000,1000,1000,1000}; p2 = 9; all_right = KawigiEdit_RunTest(4, p0, p1, true, p2) && all_right; // ------------------ // ----- test 5 ----- p0 = new int[]{0,0,0,1,2,3,4,4,4}; p1 = new int[]{3,2,1,4,4,4,1,2,3}; p2 = 4; all_right = KawigiEdit_RunTest(5, p0, p1, true, p2) && all_right; // ------------------ if (all_right) { Console.WriteLine("You're a stud (at least on the example cases)!"); } else { Console.WriteLine("Some of the test cases had errors."); } Console.ReadKey(); } #endregion // END KAWIGIEDIT TESTING } //Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: A representation of an IEEE double precision ** floating point number. ** ** ===========================================================*/ using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System { [StructLayout(LayoutKind.Sequential)] public struct Double : IComparable, IFormattable, IComparable<Double>, IEquatable<Double>, IConvertible { internal double m_value; // // Public Constants // public const double MinValue = -1.7976931348623157E+308; public const double MaxValue = 1.7976931348623157E+308; // Note Epsilon should be a double whose hex representation is 0x1 // on little endian machines. public const double Epsilon = 4.9406564584124654E-324; public const double NegativeInfinity = (double)-1.0 / (double)(0.0); public const double PositiveInfinity = (double)1.0 / (double)(0.0); public const double NaN = (double)0.0 / (double)0.0; // 0x8000000000000000 is exactly same as -0.0. We use this explicit definition to avoid the confusion between 0.0 and -0.0. internal static double NegativeZero = Int64BitsToDouble(unchecked((long)0x8000000000000000)); private static unsafe double Int64BitsToDouble(long value) { return *((double*)&value); } [Pure] public static unsafe bool IsInfinity(double d) { return (*(long*)(&d) & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000; } [Pure] public static bool IsPositiveInfinity(double d) { //Jit will generate inlineable code with this if (d == double.PositiveInfinity) { return true; } else { return false; } } [Pure] public static bool IsNegativeInfinity(double d) { //Jit will generate inlineable code with this if (d == double.NegativeInfinity) { return true; } else { return false; } } [Pure] internal static unsafe bool IsNegative(double d) { return (*(UInt64*)(&d) & 0x8000000000000000) == 0x8000000000000000; } [Pure] public static unsafe bool IsNaN(double d) { return (*(UInt64*)(&d) & 0x7FFFFFFFFFFFFFFFL) > 0x7FF0000000000000L; } // Compares this object to another object, returning an instance of System.Relation. // Null is considered less than any instance. // // If object is not of type Double, this method throws an ArgumentException. // // Returns a value less than zero if this object // int IComparable.CompareTo(Object value) { if (value == null) { return 1; } if (value is Double) { double d = (double)value; if (m_value < d) return -1; if (m_value > d) return 1; if (m_value == d) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(d) ? 0 : -1); else return 1; } throw new ArgumentException(SR.Arg_MustBeDouble); } public int CompareTo(Double value) { if (m_value < value) return -1; if (m_value > value) return 1; if (m_value == value) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(value) ? 0 : -1); else return 1; } // True if obj is another Double with the same value as the current instance. This is // a method of object equality, that only returns true if obj is also a double. public override bool Equals(Object obj) { if (!(obj is Double)) { return false; } double temp = ((Double)obj).m_value; // This code below is written this way for performance reasons i.e the != and == check is intentional. if (temp == m_value) { return true; } return IsNaN(temp) && IsNaN(m_value); } [NonVersionable] public static bool operator ==(Double left, Double right) { return left == right; } [NonVersionable] public static bool operator !=(Double left, Double right) { return left != right; } [NonVersionable] public static bool operator <(Double left, Double right) { return left < right; } [NonVersionable] public static bool operator >(Double left, Double right) { return left > right; } [NonVersionable] public static bool operator <=(Double left, Double right) { return left <= right; } [NonVersionable] public static bool operator >=(Double left, Double right) { return left >= right; } public bool Equals(Double obj) { if (obj == m_value) { return true; } return IsNaN(obj) && IsNaN(m_value); } //The hashcode for a double is the absolute value of the integer representation //of that double. // public unsafe override int GetHashCode() { double d = m_value; if (d == 0) { // Ensure that 0 and -0 have the same hash code return 0; } long value = *(long*)(&d); return unchecked((int)value) ^ ((int)(value >> 32)); } public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatDouble(m_value, null, null); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatDouble(m_value, format, null); } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatDouble(m_value, null, provider); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatDouble(m_value, format, provider); } public static double Parse(String s) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, null); } public static double Parse(String s, NumberStyles style) { Decimal.ValidateParseStyleFloatingPoint(style); return Parse(s, style, null); } public static double Parse(String s, IFormatProvider provider) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, provider); } public static double Parse(String s, NumberStyles style, IFormatProvider provider) { Decimal.ValidateParseStyleFloatingPoint(style); return FormatProvider.ParseDouble(s, style, provider); } // Parses a double from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // // This method will not throw an OverflowException, but will return // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. // public static bool TryParse(String s, out double result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, null, out result); } public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out double result) { Decimal.ValidateParseStyleFloatingPoint(style); if (s == null) { result = 0; return false; } bool success = FormatProvider.TryParseDouble(s, style, provider, out result); if (!success) { String sTrim = s.Trim(); if (FormatProvider.IsPositiveInfinity(sTrim, provider)) { result = PositiveInfinity; } else if (FormatProvider.IsNegativeInfinity(sTrim, provider)) { result = NegativeInfinity; } else if (FormatProvider.IsNaNSymbol(sTrim, provider)) { result = NaN; } else return false; // We really failed } return true; } // // IConvertible implementation // TypeCode IConvertible.GetTypeCode() { return TypeCode.Double; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Double", "Char")); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return m_value; } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Double", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion #pragma warning disable 618 using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Utilities; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #elif DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json.Schema; using System.IO; using Newtonsoft.Json.Linq; using System.Text; using Extensions = Newtonsoft.Json.Schema.Extensions; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Tests.Schema { [TestFixture] public class JsonSchemaGeneratorTests : TestFixtureBase { [Test] public void Generate_GenericDictionary() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(Dictionary<string, List<string>>)); string json = schema.ToString(); StringAssert.AreEqual(@"{ ""type"": ""object"", ""additionalProperties"": { ""type"": [ ""array"", ""null"" ], ""items"": { ""type"": [ ""string"", ""null"" ] } } }", json); Dictionary<string, List<string>> value = new Dictionary<string, List<string>> { { "HasValue", new List<string>() { "first", "second", null } }, { "NoValue", null } }; string valueJson = JsonConvert.SerializeObject(value, Formatting.Indented); JObject o = JObject.Parse(valueJson); Assert.IsTrue(o.IsValid(schema)); } #if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40) [Test] public void Generate_DefaultValueAttributeTestClass() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(DefaultValueAttributeTestClass)); string json = schema.ToString(); StringAssert.AreEqual(@"{ ""description"": ""DefaultValueAttributeTestClass description!"", ""type"": ""object"", ""additionalProperties"": false, ""properties"": { ""TestField1"": { ""required"": true, ""type"": ""integer"", ""default"": 21 }, ""TestProperty1"": { ""required"": true, ""type"": [ ""string"", ""null"" ], ""default"": ""TestProperty1Value"" } } }", json); } #endif [Test] public void Generate_Person() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(Person)); string json = schema.ToString(); StringAssert.AreEqual(@"{ ""id"": ""Person"", ""title"": ""Title!"", ""description"": ""JsonObjectAttribute description!"", ""type"": ""object"", ""properties"": { ""Name"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""BirthDate"": { ""required"": true, ""type"": ""string"" }, ""LastModified"": { ""required"": true, ""type"": ""string"" } } }", json); } [Test] public void Generate_UserNullable() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(UserNullable)); string json = schema.ToString(); StringAssert.AreEqual(@"{ ""type"": ""object"", ""properties"": { ""Id"": { ""required"": true, ""type"": ""string"" }, ""FName"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""LName"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""RoleId"": { ""required"": true, ""type"": ""integer"" }, ""NullableRoleId"": { ""required"": true, ""type"": [ ""integer"", ""null"" ] }, ""NullRoleId"": { ""required"": true, ""type"": [ ""integer"", ""null"" ] }, ""Active"": { ""required"": true, ""type"": [ ""boolean"", ""null"" ] } } }", json); } [Test] public void Generate_RequiredMembersClass() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(RequiredMembersClass)); Assert.AreEqual(JsonSchemaType.String, schema.Properties["FirstName"].Type); Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["MiddleName"].Type); Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["LastName"].Type); Assert.AreEqual(JsonSchemaType.String, schema.Properties["BirthDate"].Type); } [Test] public void Generate_Store() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(Store)); Assert.AreEqual(11, schema.Properties.Count); JsonSchema productArraySchema = schema.Properties["product"]; JsonSchema productSchema = productArraySchema.Items[0]; Assert.AreEqual(4, productSchema.Properties.Count); } [Test] public void MissingSchemaIdHandlingTest() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(Store)); Assert.AreEqual(null, schema.Id); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; schema = generator.Generate(typeof(Store)); Assert.AreEqual(typeof(Store).FullName, schema.Id); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseAssemblyQualifiedName; schema = generator.Generate(typeof(Store)); Assert.AreEqual(typeof(Store).AssemblyQualifiedName, schema.Id); } [Test] public void CircularReferenceError() { ExceptionAssert.Throws<Exception>(() => { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.Generate(typeof(CircularReferenceClass)); }, @"Unresolved circular reference for type 'Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property."); } [Test] public void CircularReferenceWithTypeNameId() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(CircularReferenceClass), true); Assert.AreEqual(JsonSchemaType.String, schema.Properties["Name"].Type); Assert.AreEqual(typeof(CircularReferenceClass).FullName, schema.Id); Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type); Assert.AreEqual(schema, schema.Properties["Child"]); } [Test] public void CircularReferenceWithExplicitId() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(CircularReferenceWithIdClass)); Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["Name"].Type); Assert.AreEqual("MyExplicitId", schema.Id); Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type); Assert.AreEqual(schema, schema.Properties["Child"]); } [Test] public void GenerateSchemaForType() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(Type)); Assert.AreEqual(JsonSchemaType.String, schema.Type); string json = JsonConvert.SerializeObject(typeof(Version), Formatting.Indented); JValue v = new JValue(json); Assert.IsTrue(v.IsValid(schema)); } #if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40) [Test] public void GenerateSchemaForISerializable() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(Exception)); Assert.AreEqual(JsonSchemaType.Object, schema.Type); Assert.AreEqual(true, schema.AllowAdditionalProperties); Assert.AreEqual(null, schema.Properties); } #endif #if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40) [Test] public void GenerateSchemaForDBNull() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(DBNull)); Assert.AreEqual(JsonSchemaType.Null, schema.Type); } public class CustomDirectoryInfoMapper : DefaultContractResolver { public CustomDirectoryInfoMapper() #pragma warning disable 612 : base(true) #pragma warning restore 612 { } protected override JsonContract CreateContract(Type objectType) { if (objectType == typeof(DirectoryInfo)) { return base.CreateObjectContract(objectType); } return base.CreateContract(objectType); } protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization); JsonPropertyCollection c = new JsonPropertyCollection(type); c.AddRange(properties.Where(m => m.PropertyName != "Root")); return c; } } [Test] public void GenerateSchemaForDirectoryInfo() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; generator.ContractResolver = new CustomDirectoryInfoMapper { #if !(NETFX_CORE || PORTABLE || DNXCORE50) IgnoreSerializableAttribute = true #endif }; JsonSchema schema = generator.Generate(typeof(DirectoryInfo), true); string json = schema.ToString(); StringAssert.AreEqual(@"{ ""id"": ""System.IO.DirectoryInfo"", ""required"": true, ""type"": [ ""object"", ""null"" ], ""additionalProperties"": false, ""properties"": { ""Name"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""Parent"": { ""$ref"": ""System.IO.DirectoryInfo"" }, ""Exists"": { ""required"": true, ""type"": ""boolean"" }, ""FullName"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""Extension"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""CreationTime"": { ""required"": true, ""type"": ""string"" }, ""CreationTimeUtc"": { ""required"": true, ""type"": ""string"" }, ""LastAccessTime"": { ""required"": true, ""type"": ""string"" }, ""LastAccessTimeUtc"": { ""required"": true, ""type"": ""string"" }, ""LastWriteTime"": { ""required"": true, ""type"": ""string"" }, ""LastWriteTimeUtc"": { ""required"": true, ""type"": ""string"" }, ""Attributes"": { ""required"": true, ""type"": ""integer"" } } }", json); DirectoryInfo temp = new DirectoryInfo(@"c:\temp"); JTokenWriter jsonWriter = new JTokenWriter(); JsonSerializer serializer = new JsonSerializer(); serializer.Converters.Add(new IsoDateTimeConverter()); serializer.ContractResolver = new CustomDirectoryInfoMapper { #if !(NETFX_CORE || PORTABLE || DNXCORE50) IgnoreSerializableInterface = true #endif }; serializer.Serialize(jsonWriter, temp); List<string> errors = new List<string>(); jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message)); Assert.AreEqual(0, errors.Count); } #endif [Test] public void GenerateSchemaCamelCase() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; generator.ContractResolver = new CamelCasePropertyNamesContractResolver() { #if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40) IgnoreSerializableAttribute = true #endif }; JsonSchema schema = generator.Generate(typeof(Version), true); string json = schema.ToString(); StringAssert.AreEqual(@"{ ""id"": ""System.Version"", ""type"": [ ""object"", ""null"" ], ""additionalProperties"": false, ""properties"": { ""major"": { ""required"": true, ""type"": ""integer"" }, ""minor"": { ""required"": true, ""type"": ""integer"" }, ""build"": { ""required"": true, ""type"": ""integer"" }, ""revision"": { ""required"": true, ""type"": ""integer"" }, ""majorRevision"": { ""required"": true, ""type"": ""integer"" }, ""minorRevision"": { ""required"": true, ""type"": ""integer"" } } }", json); } #if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40) [Test] public void GenerateSchemaSerializable() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.ContractResolver = new DefaultContractResolver { IgnoreSerializableAttribute = false }; generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(Version), true); string json = schema.ToString(); StringAssert.AreEqual(@"{ ""id"": ""System.Version"", ""type"": [ ""object"", ""null"" ], ""additionalProperties"": false, ""properties"": { ""_Major"": { ""required"": true, ""type"": ""integer"" }, ""_Minor"": { ""required"": true, ""type"": ""integer"" }, ""_Build"": { ""required"": true, ""type"": ""integer"" }, ""_Revision"": { ""required"": true, ""type"": ""integer"" } } }", json); JTokenWriter jsonWriter = new JTokenWriter(); JsonSerializer serializer = new JsonSerializer(); serializer.ContractResolver = new DefaultContractResolver { IgnoreSerializableAttribute = false }; serializer.Serialize(jsonWriter, new Version(1, 2, 3, 4)); List<string> errors = new List<string>(); jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message)); Assert.AreEqual(0, errors.Count); StringAssert.AreEqual(@"{ ""_Major"": 1, ""_Minor"": 2, ""_Build"": 3, ""_Revision"": 4 }", jsonWriter.Token.ToString()); Version version = jsonWriter.Token.ToObject<Version>(serializer); Assert.AreEqual(1, version.Major); Assert.AreEqual(2, version.Minor); Assert.AreEqual(3, version.Build); Assert.AreEqual(4, version.Revision); } #endif public enum SortTypeFlag { No = 0, Asc = 1, Desc = -1 } public class X { public SortTypeFlag x; } [Test] public void GenerateSchemaWithNegativeEnum() { JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); JsonSchema schema = jsonSchemaGenerator.Generate(typeof(X)); string json = schema.ToString(); StringAssert.AreEqual(@"{ ""type"": ""object"", ""properties"": { ""x"": { ""required"": true, ""type"": ""integer"", ""enum"": [ 0, 1, -1 ] } } }", json); } [Test] public void CircularCollectionReferences() { Type type = typeof(Workspace); JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema jsonSchema = jsonSchemaGenerator.Generate(type); // should succeed Assert.IsNotNull(jsonSchema); } [Test] public void CircularReferenceWithMixedRequires() { JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(CircularReferenceClass)); string json = jsonSchema.ToString(); StringAssert.AreEqual(@"{ ""id"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass"", ""type"": [ ""object"", ""null"" ], ""properties"": { ""Name"": { ""required"": true, ""type"": ""string"" }, ""Child"": { ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass"" } } }", json); } [Test] public void JsonPropertyWithHandlingValues() { JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(JsonPropertyWithHandlingValues)); string json = jsonSchema.ToString(); StringAssert.AreEqual(@"{ ""id"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"", ""required"": true, ""type"": [ ""object"", ""null"" ], ""properties"": { ""DefaultValueHandlingIgnoreProperty"": { ""type"": [ ""string"", ""null"" ], ""default"": ""Default!"" }, ""DefaultValueHandlingIncludeProperty"": { ""required"": true, ""type"": [ ""string"", ""null"" ], ""default"": ""Default!"" }, ""DefaultValueHandlingPopulateProperty"": { ""required"": true, ""type"": [ ""string"", ""null"" ], ""default"": ""Default!"" }, ""DefaultValueHandlingIgnoreAndPopulateProperty"": { ""type"": [ ""string"", ""null"" ], ""default"": ""Default!"" }, ""NullValueHandlingIgnoreProperty"": { ""type"": [ ""string"", ""null"" ] }, ""NullValueHandlingIncludeProperty"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""ReferenceLoopHandlingErrorProperty"": { ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"" }, ""ReferenceLoopHandlingIgnoreProperty"": { ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"" }, ""ReferenceLoopHandlingSerializeProperty"": { ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"" } } }", json); } [Test] public void GenerateForNullableInt32() { JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(NullableInt32TestClass)); string json = jsonSchema.ToString(); StringAssert.AreEqual(@"{ ""type"": ""object"", ""properties"": { ""Value"": { ""required"": true, ""type"": [ ""integer"", ""null"" ] } } }", json); } [JsonConverter(typeof(StringEnumConverter))] public enum SortTypeFlagAsString { No = 0, Asc = 1, Desc = -1 } public class Y { public SortTypeFlagAsString y; } } public class NullableInt32TestClass { public int? Value { get; set; } } public class DMDSLBase { public String Comment; } public class Workspace : DMDSLBase { public ControlFlowItemCollection Jobs = new ControlFlowItemCollection(); } public class ControlFlowItemBase : DMDSLBase { public String Name; } public class ControlFlowItem : ControlFlowItemBase //A Job { public TaskCollection Tasks = new TaskCollection(); public ContainerCollection Containers = new ContainerCollection(); } public class ControlFlowItemCollection : List<ControlFlowItem> { } public class Task : ControlFlowItemBase { public DataFlowTaskCollection DataFlowTasks = new DataFlowTaskCollection(); public BulkInsertTaskCollection BulkInsertTask = new BulkInsertTaskCollection(); } public class TaskCollection : List<Task> { } public class Container : ControlFlowItemBase { public ControlFlowItemCollection ContainerJobs = new ControlFlowItemCollection(); } public class ContainerCollection : List<Container> { } public class DataFlowTask_DSL : ControlFlowItemBase { } public class DataFlowTaskCollection : List<DataFlowTask_DSL> { } public class SequenceContainer_DSL : Container { } public class BulkInsertTaskCollection : List<BulkInsertTask_DSL> { } public class BulkInsertTask_DSL { } } #pragma warning restore 618
#define ASTAR_FAST_NO_EXCEPTIONS using System; using System.IO; using System.Collections.Generic; using UnityEngine; using Pathfinding.Util; using Pathfinding.WindowsStore; #if ASTAR_NO_ZIP using Pathfinding.Serialization.Zip; #elif NETFX_CORE // For Universal Windows Platform using ZipEntry = System.IO.Compression.ZipArchiveEntry; using ZipFile = System.IO.Compression.ZipArchive; #else using Pathfinding.Ionic.Zip; #endif namespace Pathfinding.Serialization { /** Holds information passed to custom graph serializers */ public class GraphSerializationContext { private readonly GraphNode[] id2NodeMapping; /** Deserialization stream. * Will only be set when deserializing */ public readonly BinaryReader reader; /** Serialization stream. * Will only be set when serializing */ public readonly BinaryWriter writer; /** Index of the graph which is currently being processed. * \version uint instead of int after 3.7.5 */ public readonly uint graphIndex; /** Metadata about graphs being deserialized */ public readonly GraphMeta meta; public GraphSerializationContext (BinaryReader reader, GraphNode[] id2NodeMapping, uint graphIndex, GraphMeta meta) { this.reader = reader; this.id2NodeMapping = id2NodeMapping; this.graphIndex = graphIndex; this.meta = meta; } public GraphSerializationContext (BinaryWriter writer) { this.writer = writer; } public void SerializeNodeReference (GraphNode node) { writer.Write(node == null ? -1 : node.NodeIndex); } public GraphNode DeserializeNodeReference () { var id = reader.ReadInt32(); if (id2NodeMapping == null) throw new Exception("Calling DeserializeNodeReference when serializing"); if (id == -1) return null; GraphNode node = id2NodeMapping[id]; if (node == null) throw new Exception("Invalid id ("+id+")"); return node; } /** Write a Vector3 */ public void SerializeVector3 (Vector3 v) { writer.Write(v.x); writer.Write(v.y); writer.Write(v.z); } /** Read a Vector3 */ public Vector3 DeserializeVector3 () { return new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); } /** Write an Int3 */ public void SerializeInt3 (Int3 v) { writer.Write(v.x); writer.Write(v.y); writer.Write(v.z); } /** Read an Int3 */ public Int3 DeserializeInt3 () { return new Int3(reader.ReadInt32(), reader.ReadInt32(), reader.ReadInt32()); } public int DeserializeInt (int defaultValue) { if (reader.BaseStream.Position <= reader.BaseStream.Length-4) { return reader.ReadInt32(); } else { return defaultValue; } } public float DeserializeFloat (float defaultValue) { if (reader.BaseStream.Position <= reader.BaseStream.Length-4) { return reader.ReadSingle(); } else { return defaultValue; } } /** Read a UnityEngine.Object */ public UnityEngine.Object DeserializeUnityObject ( ) { int inst = reader.ReadInt32(); if (inst == int.MaxValue) { return null; } string name = reader.ReadString(); string typename = reader.ReadString(); string guid = reader.ReadString(); System.Type type = System.Type.GetType(typename); if (type == null) { Debug.LogError("Could not find type '"+typename+"'. Cannot deserialize Unity reference"); return null; } if (!string.IsNullOrEmpty(guid)) { UnityReferenceHelper[] helpers = UnityEngine.Object.FindObjectsOfType(typeof(UnityReferenceHelper)) as UnityReferenceHelper[]; for (int i = 0; i < helpers.Length; i++) { if (helpers[i].GetGUID() == guid) { if (type == typeof(GameObject)) { return helpers[i].gameObject; } else { return helpers[i].GetComponent(type); } } } } //Try to load from resources UnityEngine.Object[] objs = Resources.LoadAll(name, type); for (int i = 0; i < objs.Length; i++) { if (objs[i].name == name || objs.Length == 1) { return objs[i]; } } return null; } } /** Handles low level serialization and deserialization of graph settings and data. * Mostly for internal use. You can use the methods in the AstarData class for * higher level serialization and deserialization. * * \see AstarData */ public class AstarSerializer { private AstarData data; /** Zip which the data is loaded from */ private ZipFile zip; /** Memory stream with the zip data */ private MemoryStream zipStream; /** Graph metadata */ private GraphMeta meta; /** Settings for serialization */ private SerializeSettings settings; /** Graphs that are being serialized or deserialized */ private NavGraph[] graphs; /** Index used for the graph in the file. * If some graphs were null in the file then graphIndexInZip[graphs[i]] may not equal i. * Used for deserialization. */ private Dictionary<NavGraph, int> graphIndexInZip; private int graphIndexOffset; /** Extension to use for binary files */ const string binaryExt = ".binary"; /** Extension to use for json files */ const string jsonExt = ".json"; /** Checksum for the serialized data. * Used to provide a quick equality check in editor code */ private uint checksum = 0xffffffff; System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); /** Cached StringBuilder to avoid excessive allocations */ static System.Text.StringBuilder _stringBuilder = new System.Text.StringBuilder(); /** Returns a cached StringBuilder. * This function only has one string builder cached and should * thus only be called from a single thread and should not be called while using an earlier got string builder. */ static System.Text.StringBuilder GetStringBuilder () { _stringBuilder.Length = 0; return _stringBuilder; } public AstarSerializer (AstarData data) { this.data = data; settings = SerializeSettings.Settings; } public AstarSerializer (AstarData data, SerializeSettings settings) { this.data = data; this.settings = settings; } public void SetGraphIndexOffset (int offset) { graphIndexOffset = offset; } void AddChecksum (byte[] bytes) { checksum = Checksum.GetChecksum(bytes, checksum); } void AddEntry (string name, byte[] bytes) { #if NETFX_CORE var entry = zip.CreateEntry(name); using (var stream = entry.Open()) { stream.Write(bytes, 0, bytes.Length); } #else zip.AddEntry(name, bytes); #endif } public uint GetChecksum () { return checksum; } #region Serialize public void OpenSerialize () { // Create a new zip file, here we will store all the data zipStream = new MemoryStream(); #if NETFX_CORE zip = new ZipFile(zipStream, System.IO.Compression.ZipArchiveMode.Create); #else zip = new ZipFile(); zip.AlternateEncoding = System.Text.Encoding.UTF8; zip.AlternateEncodingUsage = ZipOption.Always; #endif meta = new GraphMeta(); } public byte[] CloseSerialize () { // As the last step, serialize metadata byte[] bytes = SerializeMeta(); AddChecksum(bytes); AddEntry("meta"+jsonExt, bytes); #if !ASTAR_NO_ZIP && !NETFX_CORE // Set dummy dates on every file to prevent the binary data to change // for identical settings and graphs. // Prevents the scene from being marked as dirty in the editor // If ASTAR_NO_ZIP is defined this is not relevant since the replacement zip // implementation does not even store dates var dummy = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); foreach (var entry in zip.Entries) { entry.AccessedTime = dummy; entry.CreationTime = dummy; entry.LastModified = dummy; entry.ModifiedTime = dummy; } #endif // Save all entries to a single byte array #if !NETFX_CORE zip.Save(zipStream); #endif zip.Dispose(); bytes = zipStream.ToArray(); zip = null; zipStream = null; return bytes; } public void SerializeGraphs (NavGraph[] _graphs) { if (graphs != null) throw new InvalidOperationException("Cannot serialize graphs multiple times."); graphs = _graphs; if (zip == null) throw new NullReferenceException("You must not call CloseSerialize before a call to this function"); if (graphs == null) graphs = new NavGraph[0]; for (int i = 0; i < graphs.Length; i++) { //Ignore graph if null if (graphs[i] == null) continue; // Serialize the graph to a byte array byte[] bytes = Serialize(graphs[i]); AddChecksum(bytes); AddEntry("graph"+i+jsonExt, bytes); } } /** Serialize metadata about all graphs */ byte[] SerializeMeta () { if (graphs == null) throw new System.Exception("No call to SerializeGraphs has been done"); meta.version = AstarPath.Version; meta.graphs = graphs.Length; meta.guids = new List<string>(); meta.typeNames = new List<string>(); // For each graph, save the guid // of the graph and the type of it for (int i = 0; i < graphs.Length; i++) { if (graphs[i] != null) { meta.guids.Add(graphs[i].guid.ToString()); meta.typeNames.Add(graphs[i].GetType().FullName); } else { meta.guids.Add(null); meta.typeNames.Add(null); } } // Grab a cached string builder to avoid allocations var output = GetStringBuilder(); TinyJsonSerializer.Serialize(meta, output); return encoding.GetBytes(output.ToString()); } /** Serializes the graph settings to JSON and returns the data */ public byte[] Serialize (NavGraph graph) { // Grab a cached string builder to avoid allocations var output = GetStringBuilder(); TinyJsonSerializer.Serialize(graph, output); return encoding.GetBytes(output.ToString()); } /** Deprecated method to serialize node data. * \deprecated Not used anymore */ [System.Obsolete("Not used anymore. You can safely remove the call to this function.")] public void SerializeNodes () { } static int GetMaxNodeIndexInAllGraphs (NavGraph[] graphs) { int maxIndex = 0; for (int i = 0; i < graphs.Length; i++) { if (graphs[i] == null) continue; graphs[i].GetNodes(node => { maxIndex = Math.Max(node.NodeIndex, maxIndex); if (node.NodeIndex == -1) { Debug.LogError("Graph contains destroyed nodes. This is a bug."); } }); } return maxIndex; } static byte[] SerializeNodeIndices (NavGraph[] graphs) { var stream = new MemoryStream(); var writer = new BinaryWriter(stream); int maxNodeIndex = GetMaxNodeIndexInAllGraphs(graphs); writer.Write(maxNodeIndex); // While writing node indices, verify that the max node index is the same // (user written graphs might have gotten it wrong) int maxNodeIndex2 = 0; for (int i = 0; i < graphs.Length; i++) { if (graphs[i] == null) continue; graphs[i].GetNodes(node => { maxNodeIndex2 = Math.Max(node.NodeIndex, maxNodeIndex2); writer.Write(node.NodeIndex); }); } // Nice to verify if users are writing their own graph types if (maxNodeIndex2 != maxNodeIndex) throw new Exception("Some graphs are not consistent in their GetNodes calls, sequential calls give different results."); byte[] bytes = stream.ToArray(); writer.Close(); return bytes; } /** Serializes info returned by NavGraph.SerializeExtraInfo */ static byte[] SerializeGraphExtraInfo (NavGraph graph) { var stream = new MemoryStream(); var writer = new BinaryWriter(stream); var ctx = new GraphSerializationContext(writer); graph.SerializeExtraInfo(ctx); byte[] bytes = stream.ToArray(); writer.Close(); return bytes; } /** Used to serialize references to other nodes e.g connections. * Nodes use the GraphSerializationContext.GetNodeIdentifier and * GraphSerializationContext.GetNodeFromIdentifier methods * for serialization and deserialization respectively. */ static byte[] SerializeGraphNodeReferences (NavGraph graph) { var stream = new MemoryStream(); var writer = new BinaryWriter(stream); var ctx = new GraphSerializationContext(writer); graph.GetNodes(node => node.SerializeReferences(ctx)); writer.Close(); var bytes = stream.ToArray(); return bytes; } public void SerializeExtraInfo () { if (!settings.nodes) return; if (graphs == null) throw new InvalidOperationException("Cannot serialize extra info with no serialized graphs (call SerializeGraphs first)"); var bytes = SerializeNodeIndices(graphs); AddChecksum(bytes); AddEntry("graph_references"+binaryExt, bytes); for (int i = 0; i < graphs.Length; i++) { if (graphs[i] == null) continue; bytes = SerializeGraphExtraInfo(graphs[i]); AddChecksum(bytes); AddEntry("graph"+i+"_extra"+binaryExt, bytes); bytes = SerializeGraphNodeReferences(graphs[i]); AddChecksum(bytes); AddEntry("graph"+i+"_references"+binaryExt, bytes); } bytes = SerializeNodeLinks(); AddChecksum(bytes); AddEntry("node_link2" + binaryExt, bytes); } byte[] SerializeNodeLinks () { var stream = new MemoryStream(); var writer = new BinaryWriter(stream); var ctx = new GraphSerializationContext(writer); NodeLink2.SerializeReferences(ctx); return stream.ToArray(); } public void SerializeEditorSettings (GraphEditorBase[] editors) { if (editors == null || !settings.editorSettings) return; for (int i = 0; i < editors.Length; i++) { if (editors[i] == null) return; var output = GetStringBuilder(); TinyJsonSerializer.Serialize(editors[i], output); var bytes = encoding.GetBytes(output.ToString()); //Less or equal to 2 bytes means that nothing was saved (file is "{}") if (bytes.Length <= 2) continue; AddChecksum(bytes); AddEntry("graph"+i+"_editor"+jsonExt, bytes); } } #endregion #region Deserialize ZipEntry GetEntry (string name) { #if NETFX_CORE return zip.GetEntry(name); #else return zip[name]; #endif } bool ContainsEntry (string name) { return GetEntry(name) != null; } public bool OpenDeserialize (byte[] bytes) { // Copy the bytes to a stream zipStream = new MemoryStream(); zipStream.Write(bytes, 0, bytes.Length); zipStream.Position = 0; try { #if NETFX_CORE zip = new ZipFile(zipStream); #else zip = ZipFile.Read(zipStream); #endif } catch (Exception e) { // Catches exceptions when an invalid zip file is found Debug.LogError("Caught exception when loading from zip\n"+e); zipStream.Dispose(); return false; } if (ContainsEntry("meta" + jsonExt)) { meta = DeserializeMeta(GetEntry("meta" + jsonExt)); } else if (ContainsEntry("meta" + binaryExt)) { meta = DeserializeBinaryMeta(GetEntry("meta" + binaryExt)); } else { throw new Exception("No metadata found in serialized data."); } if (FullyDefinedVersion(meta.version) > FullyDefinedVersion(AstarPath.Version)) { Debug.LogWarning("Trying to load data from a newer version of the A* Pathfinding Project\nCurrent version: "+AstarPath.Version+" Data version: "+meta.version + "\nThis is usually fine as the stored data is usually backwards and forwards compatible." + "\nHowever node data (not settings) can get corrupted between versions (even though I try my best to keep compatibility), so it is recommended " + "to recalculate any caches (those for faster startup) and resave any files. Even if it seems to load fine, it might cause subtle bugs.\n"); } else if (FullyDefinedVersion(meta.version) < FullyDefinedVersion(AstarPath.Version)) { Debug.LogWarning("Upgrading serialized pathfinding data from version " + meta.version + " to " + AstarPath.Version + "\nThis is usually fine, it just means you have upgraded to a new version." + "\nHowever node data (not settings) can get corrupted between versions (even though I try my best to keep compatibility), so it is recommended " + "to recalculate any caches (those for faster startup) and resave any files. Even if it seems to load fine, it might cause subtle bugs.\n"); } return true; } /** Returns a version with all fields fully defined. * This is used because by default new Version(3,0,0) > new Version(3,0). * This is not the desired behaviour so we make sure that all fields are defined here */ static System.Version FullyDefinedVersion (System.Version v) { return new System.Version(Mathf.Max(v.Major, 0), Mathf.Max(v.Minor, 0), Mathf.Max(v.Build, 0), Mathf.Max(v.Revision, 0)); } public void CloseDeserialize () { zipStream.Dispose(); zip.Dispose(); zip = null; zipStream = null; } NavGraph DeserializeGraph (int zipIndex, int graphIndex) { // Get the graph type from the metadata we deserialized earlier var graphType = meta.GetGraphType(zipIndex); // Graph was null when saving, ignore if (System.Type.Equals(graphType, null)) return null; // Create a new graph of the right type NavGraph graph = data.CreateGraph(graphType); graph.graphIndex = (uint)(graphIndex); var jsonName = "graph" + zipIndex + jsonExt; var binName = "graph" + zipIndex + binaryExt; if (ContainsEntry(jsonName)) { // Read the graph settings TinyJsonDeserializer.Deserialize(GetString(GetEntry(jsonName)), graphType, graph); } else if (ContainsEntry(binName)) { var reader = GetBinaryReader(GetEntry(binName)); var ctx = new GraphSerializationContext(reader, null, graph.graphIndex, meta); graph.DeserializeSettingsCompatibility(ctx); } else { throw new FileNotFoundException("Could not find data for graph " + zipIndex + " in zip. Entry 'graph" + zipIndex + jsonExt + "' does not exist"); } if (graph.guid.ToString() != meta.guids[zipIndex]) throw new Exception("Guid in graph file not equal to guid defined in meta file. Have you edited the data manually?\n"+graph.guid+" != "+meta.guids[zipIndex]); return graph; } /** Deserializes graph settings. * \note Stored in files named "graph#.json" where # is the graph number. */ public NavGraph[] DeserializeGraphs () { // Allocate a list of graphs to be deserialized var graphList = new List<NavGraph>(); graphIndexInZip = new Dictionary<NavGraph, int>(); for (int i = 0; i < meta.graphs; i++) { var newIndex = graphList.Count + graphIndexOffset; var graph = DeserializeGraph(i, newIndex); if (graph != null) { graphList.Add(graph); graphIndexInZip[graph] = i; } } graphs = graphList.ToArray(); return graphs; } bool DeserializeExtraInfo (NavGraph graph) { var zipIndex = graphIndexInZip[graph]; var entry = GetEntry("graph"+zipIndex+"_extra"+binaryExt); if (entry == null) return false; var reader = GetBinaryReader(entry); var ctx = new GraphSerializationContext(reader, null, graph.graphIndex, meta); // Call the graph to process the data graph.DeserializeExtraInfo(ctx); return true; } bool AnyDestroyedNodesInGraphs () { bool result = false; for (int i = 0; i < graphs.Length; i++) { graphs[i].GetNodes(node => { if (node.Destroyed) { result = true; } }); } return result; } GraphNode[] DeserializeNodeReferenceMap () { // Get the file containing the list of all node indices // This is correlated with the new indices of the nodes and a mapping from old to new // is done so that references can be resolved var entry = GetEntry("graph_references"+binaryExt); if (entry == null) throw new Exception("Node references not found in the data. Was this loaded from an older version of the A* Pathfinding Project?"); var reader = GetBinaryReader(entry); int maxNodeIndex = reader.ReadInt32(); var int2Node = new GraphNode[maxNodeIndex+1]; try { for (int i = 0; i < graphs.Length; i++) { graphs[i].GetNodes(node => { var index = reader.ReadInt32(); int2Node[index] = node; }); } } catch (Exception e) { throw new Exception("Some graph(s) has thrown an exception during GetNodes, or some graph(s) have deserialized more or fewer nodes than were serialized", e); } if (reader.BaseStream.Position != reader.BaseStream.Length) { throw new Exception((reader.BaseStream.Length / 4) + " nodes were serialized, but only data for " + (reader.BaseStream.Position / 4) + " nodes was found. The data looks corrupt."); } reader.Close(); return int2Node; } void DeserializeNodeReferences (NavGraph graph, GraphNode[] int2Node) { var zipIndex = graphIndexInZip[graph]; var entry = GetEntry("graph"+zipIndex+"_references"+binaryExt); if (entry == null) throw new Exception("Node references for graph " + zipIndex + " not found in the data. Was this loaded from an older version of the A* Pathfinding Project?"); var reader = GetBinaryReader(entry); var ctx = new GraphSerializationContext(reader, int2Node, graph.graphIndex, meta); graph.GetNodes(node => node.DeserializeReferences(ctx)); } /** Deserializes extra graph info. * Extra graph info is specified by the graph types. * \see Pathfinding.NavGraph.DeserializeExtraInfo * \note Stored in files named "graph#_extra.binary" where # is the graph number. */ public void DeserializeExtraInfo () { bool anyDeserialized = false; // Loop through all graphs and deserialize the extra info // if there is any such info in the zip file for (int i = 0; i < graphs.Length; i++) { anyDeserialized |= DeserializeExtraInfo(graphs[i]); } if (!anyDeserialized) { return; } // Sanity check // Make sure the graphs don't contain destroyed nodes if (AnyDestroyedNodesInGraphs()) { Debug.LogError("Graph contains destroyed nodes. This is a bug."); } // Deserialize map from old node indices to new nodes var int2Node = DeserializeNodeReferenceMap(); // Deserialize node references for (int i = 0; i < graphs.Length; i++) { DeserializeNodeReferences(graphs[i], int2Node); } DeserializeNodeLinks(int2Node); } void DeserializeNodeLinks (GraphNode[] int2Node) { var entry = GetEntry("node_link2"+binaryExt); if (entry == null) return; var reader = GetBinaryReader(entry); var ctx = new GraphSerializationContext(reader, int2Node, 0, meta); NodeLink2.DeserializeReferences(ctx); } /** Calls PostDeserialization on all loaded graphs */ public void PostDeserialization () { for (int i = 0; i < graphs.Length; i++) { graphs[i].PostDeserialization(); } } /** Deserializes graph editor settings. * For future compatibility this method does not assume that the \a graphEditors array matches the #graphs array in order and/or count. * It searches for a matching graph (matching if graphEditor.target == graph) for every graph editor. * Multiple graph editors should not refer to the same graph.\n * \note Stored in files named "graph#_editor.json" where # is the graph number. */ public void DeserializeEditorSettings (GraphEditorBase[] graphEditors) { if (graphEditors == null) return; for (int i = 0; i < graphEditors.Length; i++) { if (graphEditors[i] == null) continue; for (int j = 0; j < graphs.Length; j++) { if (graphEditors[i].target != graphs[j]) continue; var zipIndex = graphIndexInZip[graphs[j]]; ZipEntry entry = GetEntry("graph"+zipIndex+"_editor"+jsonExt); if (entry == null) continue; TinyJsonDeserializer.Deserialize(GetString(entry), graphEditors[i].GetType(), graphEditors[i]); break; } } } /** Returns a binary reader for the data in the zip entry */ private static BinaryReader GetBinaryReader (ZipEntry entry) { #if NETFX_CORE return new BinaryReader(entry.Open()); #else var stream = new System.IO.MemoryStream(); entry.Extract(stream); stream.Position = 0; return new System.IO.BinaryReader(stream); #endif } /** Returns the data in the zip entry as a string */ private static string GetString (ZipEntry entry) { #if NETFX_CORE var reader = new StreamReader(entry.Open()); #else var buffer = new MemoryStream(); entry.Extract(buffer); buffer.Position = 0; var reader = new StreamReader(buffer); #endif string s = reader.ReadToEnd(); reader.Dispose(); return s; } private GraphMeta DeserializeMeta (ZipEntry entry) { return TinyJsonDeserializer.Deserialize(GetString(entry), typeof(GraphMeta)) as GraphMeta; } private GraphMeta DeserializeBinaryMeta (ZipEntry entry) { var meta = new GraphMeta(); var reader = GetBinaryReader(entry); if (reader.ReadString() != "A*") throw new System.Exception("Invalid magic number in saved data"); int major = reader.ReadInt32(); int minor = reader.ReadInt32(); int build = reader.ReadInt32(); int revision = reader.ReadInt32(); // Required because when saving a version with a field not set, it will save it as -1 // and then the Version constructor will throw an exception (which we do not want) if (major < 0) meta.version = new Version(0, 0); else if (minor < 0) meta.version = new Version(major, 0); else if (build < 0) meta.version = new Version(major, minor); else if (revision < 0) meta.version = new Version(major, minor, build); else meta.version = new Version(major, minor, build, revision); meta.graphs = reader.ReadInt32(); meta.guids = new List<string>(); int count = reader.ReadInt32(); for (int i = 0; i < count; i++) meta.guids.Add(reader.ReadString()); meta.typeNames = new List<string>(); count = reader.ReadInt32(); for (int i = 0; i < count; i++) meta.typeNames.Add(reader.ReadString()); return meta; } #endregion #region Utils /** Save the specified data at the specified path */ public static void SaveToFile (string path, byte[] data) { #if NETFX_CORE throw new System.NotSupportedException("Cannot save to file on this platform"); #else using (var stream = new FileStream(path, FileMode.Create)) { stream.Write(data, 0, data.Length); } #endif } /** Load the specified data from the specified path */ public static byte[] LoadFromFile (string path) { #if NETFX_CORE throw new System.NotSupportedException("Cannot load from file on this platform"); #else using (var stream = new FileStream(path, FileMode.Open)) { var bytes = new byte[(int)stream.Length]; stream.Read(bytes, 0, (int)stream.Length); return bytes; } #endif } #endregion } /** Metadata for all graphs included in serialization */ public class GraphMeta { /** Project version it was saved with */ public Version version; /** Number of graphs serialized */ public int graphs; /** Guids for all graphs */ public List<string> guids; /** Type names for all graphs */ public List<string> typeNames; /** Returns the Type of graph number \a i */ public Type GetGraphType (int i) { // The graph was null when saving. Ignore it if (String.IsNullOrEmpty(typeNames[i])) return null; #if ASTAR_FAST_NO_EXCEPTIONS || UNITY_WEBGL System.Type[] types = AstarData.DefaultGraphTypes; Type type = null; for (int j = 0; j < types.Length; j++) { if (types[j].FullName == typeNames[i]) type = types[j]; } #else // Note calling through assembly is more stable on e.g WebGL Type type = WindowsStoreCompatibility.GetTypeInfo(typeof(AstarPath)).Assembly.GetType(typeNames[i]); #endif if (!System.Type.Equals(type, null)) return type; throw new Exception("No graph of type '" + typeNames[i] + "' could be created, type does not exist"); } } /** Holds settings for how graphs should be serialized */ public class SerializeSettings { /** Enable to include node data. * If false, only settings will be saved */ public bool nodes = true; /** Use pretty printing for the json data. * Good if you want to open up the saved data and edit it manually */ [System.Obsolete("There is no support for pretty printing the json anymore")] public bool prettyPrint; /** Save editor settings. * \warning Only applicable when saving from the editor using the AstarPathEditor methods */ public bool editorSettings; /** Serialization settings for only saving graph settings */ public static SerializeSettings Settings { get { return new SerializeSettings { nodes = false }; } } } }
//------------------------------------------------------------------------------ // <license file="NativeError.cs"> // // The use and distribution terms for this software are contained in the file // named 'LICENSE', which can be found in the resources directory of this // distribution. // // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // </license> //------------------------------------------------------------------------------ using System; namespace EcmaScript.NET.Types { /// <summary> /// The class of error objects /// /// ECMA 15.11 /// </summary> sealed class BuiltinError : IdScriptableObject { public BuiltinError () { } override public string ClassName { get { return "Error"; } } private static readonly object ERROR_TAG = new object (); internal static void Init (IScriptable scope, bool zealed) { BuiltinError obj = new BuiltinError (); ScriptableObject.PutProperty (obj, "name", "Error"); ScriptableObject.PutProperty (obj, "message", ""); ScriptableObject.PutProperty (obj, "fileName", ""); ScriptableObject.PutProperty (obj, "lineNumber", 0); // TODO: Implement as non-ecma feature ScriptableObject.PutProperty (obj, "stack", "NOT IMPLEMENTED"); obj.ExportAsJSClass (MAX_PROTOTYPE_ID, scope, zealed , ScriptableObject.DONTENUM | ScriptableObject.READONLY | ScriptableObject.PERMANENT); } internal static BuiltinError make (Context cx, IScriptable scope, IdFunctionObject ctorObj, object [] args) { IScriptable proto = (IScriptable)(ctorObj.Get ("prototype", ctorObj)); BuiltinError obj = new BuiltinError (); obj.SetPrototype (proto); obj.ParentScope = scope; if (args.Length >= 1) { ScriptableObject.PutProperty (obj, "message", ScriptConvert.ToString (args [0])); if (args.Length >= 2) { ScriptableObject.PutProperty (obj, "fileName", args [1]); if (args.Length >= 3) { int line = ScriptConvert.ToInt32 (args [2]); ScriptableObject.PutProperty (obj, "lineNumber", (object)line); } } } return obj; } public override string ToString () { return js_toString (this); } protected internal override void InitPrototypeId (int id) { string s; int arity; switch (id) { case Id_constructor: arity = 1; s = "constructor"; break; case Id_toString: arity = 0; s = "toString"; break; case Id_toSource: arity = 0; s = "toSource"; break; default: throw new ArgumentException (Convert.ToString (id)); } InitPrototypeMethod (ERROR_TAG, id, s, arity); } public override object ExecIdCall (IdFunctionObject f, Context cx, IScriptable scope, IScriptable thisObj, object [] args) { if (!f.HasTag (ERROR_TAG)) { return base.ExecIdCall (f, cx, scope, thisObj, args); } int id = f.MethodId; switch (id) { case Id_constructor: return make (cx, scope, f, args); case Id_toString: return js_toString (thisObj); case Id_toSource: return js_toSource (cx, scope, thisObj); } throw new ArgumentException (Convert.ToString (id)); } private static string js_toString (IScriptable thisObj) { return getString (thisObj, "name") + ": " + getString (thisObj, "message"); } private static string js_toSource (Context cx, IScriptable scope, IScriptable thisObj) { // Emulation of SpiderMonkey behavior object name = ScriptableObject.GetProperty (thisObj, "name"); object message = ScriptableObject.GetProperty (thisObj, "message"); object fileName = ScriptableObject.GetProperty (thisObj, "fileName"); object lineNumber = ScriptableObject.GetProperty (thisObj, "lineNumber"); System.Text.StringBuilder sb = new System.Text.StringBuilder (); sb.Append ("(new "); if (name == UniqueTag.NotFound) { name = Undefined.Value; } sb.Append (ScriptConvert.ToString (name)); sb.Append ("("); if (message != UniqueTag.NotFound || fileName != UniqueTag.NotFound || lineNumber != UniqueTag.NotFound) { if (message == UniqueTag.NotFound) { message = ""; } sb.Append (ScriptRuntime.uneval (cx, scope, message)); if (fileName != UniqueTag.NotFound || lineNumber != UniqueTag.NotFound) { sb.Append (", "); if (fileName == UniqueTag.NotFound) { fileName = ""; } sb.Append (ScriptRuntime.uneval (cx, scope, fileName)); if (lineNumber != UniqueTag.NotFound) { int line = ScriptConvert.ToInt32 (lineNumber); if (line != 0) { sb.Append (", "); sb.Append (ScriptConvert.ToString (line)); } } } } sb.Append ("))"); return sb.ToString (); } private static string getString (IScriptable obj, string id) { object value = ScriptableObject.GetProperty (obj, id); if (value == UniqueTag.NotFound) return ""; return ScriptConvert.ToString (value); } #region PrototypeIds private const int Id_constructor = 1; private const int Id_toString = 2; private const int Id_toSource = 3; private const int MAX_PROTOTYPE_ID = 3; #endregion protected internal override int FindPrototypeId (string s) { int id; #region Generated PrototypeId Switch L0: { id = 0; string X = null; int c; int s_length = s.Length; if (s_length==8) { c=s[3]; if (c=='o') { X="toSource";id=Id_toSource; } else if (c=='t') { X="toString";id=Id_toString; } } else if (s_length==11) { X="constructor";id=Id_constructor; } if (X!=null && X!=s && !X.Equals(s)) id = 0; } EL0: #endregion return id; } } }
// 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.Xml; using System.Collections.Generic; namespace System.Runtime.Serialization { // NOTE: XmlReader methods that are not needed have been left un-implemented internal class ExtensionDataReader : XmlReader { private enum ExtensionDataNodeType { None, Element, EndElement, Text, Xml, ReferencedElement, NullElement, } private ElementData[] _elements; private ElementData _element; private ElementData _nextElement; private ReadState _readState = ReadState.Initial; private ExtensionDataNodeType _internalNodeType; private XmlNodeType _nodeType; private int _depth; private string _localName; private string _ns; private string _prefix; private string _value; private int _attributeCount; private int _attributeIndex; #pragma warning disable 0649 private XmlNodeReader _xmlNodeReader; #pragma warning restore 0649 private Queue<IDataNode> _deserializedDataNodes; private XmlObjectSerializerReadContext _context; private static Dictionary<string, string> s_nsToPrefixTable; private static Dictionary<string, string> s_prefixToNsTable; static ExtensionDataReader() { s_nsToPrefixTable = new Dictionary<string, string>(); s_prefixToNsTable = new Dictionary<string, string>(); AddPrefix(Globals.XsiPrefix, Globals.SchemaInstanceNamespace); AddPrefix(Globals.SerPrefix, Globals.SerializationNamespace); AddPrefix(String.Empty, String.Empty); } internal ExtensionDataReader(XmlObjectSerializerReadContext context) { _attributeIndex = -1; _context = context; } internal void SetDeserializedValue(object obj) { IDataNode deserializedDataNode = (_deserializedDataNodes == null || _deserializedDataNodes.Count == 0) ? null : _deserializedDataNodes.Dequeue(); if (deserializedDataNode != null && !(obj is IDataNode)) { deserializedDataNode.Value = obj; deserializedDataNode.IsFinalValue = true; } } internal IDataNode GetCurrentNode() { IDataNode retVal = _element.dataNode; Skip(); return retVal; } internal void SetDataNode(IDataNode dataNode, string name, string ns) { SetNextElement(dataNode, name, ns, null); _element = _nextElement; _nextElement = null; SetElement(); } internal void Reset() { _localName = null; _ns = null; _prefix = null; _value = null; _attributeCount = 0; _attributeIndex = -1; _depth = 0; _element = null; _nextElement = null; _elements = null; _deserializedDataNodes = null; } private bool IsXmlDataNode { get { return (_internalNodeType == ExtensionDataNodeType.Xml); } } public override XmlNodeType NodeType { get { return IsXmlDataNode ? _xmlNodeReader.NodeType : _nodeType; } } public override string LocalName { get { return IsXmlDataNode ? _xmlNodeReader.LocalName : _localName; } } public override string NamespaceURI { get { return IsXmlDataNode ? _xmlNodeReader.NamespaceURI : _ns; } } public override string Prefix { get { return IsXmlDataNode ? _xmlNodeReader.Prefix : _prefix; } } public override string Value { get { return IsXmlDataNode ? _xmlNodeReader.Value : _value; } } public override int Depth { get { return IsXmlDataNode ? _xmlNodeReader.Depth : _depth; } } public override int AttributeCount { get { return IsXmlDataNode ? _xmlNodeReader.AttributeCount : _attributeCount; } } public override bool EOF { get { return IsXmlDataNode ? _xmlNodeReader.EOF : (_readState == ReadState.EndOfFile); } } public override ReadState ReadState { get { return IsXmlDataNode ? _xmlNodeReader.ReadState : _readState; } } public override bool IsEmptyElement { get { return IsXmlDataNode ? _xmlNodeReader.IsEmptyElement : false; } } public override bool IsDefault { get { return IsXmlDataNode ? _xmlNodeReader.IsDefault : base.IsDefault; } } //public override char QuoteChar { get { return IsXmlDataNode ? xmlNodeReader.QuoteChar : base.QuoteChar; } } public override XmlSpace XmlSpace { get { return IsXmlDataNode ? _xmlNodeReader.XmlSpace : base.XmlSpace; } } public override string XmlLang { get { return IsXmlDataNode ? _xmlNodeReader.XmlLang : base.XmlLang; } } public override string this[int i] { get { return IsXmlDataNode ? _xmlNodeReader[i] : GetAttribute(i); } } public override string this[string name] { get { return IsXmlDataNode ? _xmlNodeReader[name] : GetAttribute(name); } } public override string this[string name, string namespaceURI] { get { return IsXmlDataNode ? _xmlNodeReader[name, namespaceURI] : GetAttribute(name, namespaceURI); } } public override bool MoveToFirstAttribute() { if (IsXmlDataNode) return _xmlNodeReader.MoveToFirstAttribute(); if (_attributeCount == 0) return false; MoveToAttribute(0); return true; } public override bool MoveToNextAttribute() { if (IsXmlDataNode) return _xmlNodeReader.MoveToNextAttribute(); if (_attributeIndex + 1 >= _attributeCount) return false; MoveToAttribute(_attributeIndex + 1); return true; } public override void MoveToAttribute(int index) { if (IsXmlDataNode) _xmlNodeReader.MoveToAttribute(index); else { if (index < 0 || index >= _attributeCount) throw new XmlException(SR.InvalidXmlDeserializingExtensionData); _nodeType = XmlNodeType.Attribute; AttributeData attribute = _element.attributes[index]; _localName = attribute.localName; _ns = attribute.ns; _prefix = attribute.prefix; _value = attribute.value; _attributeIndex = index; } } public override string GetAttribute(string name, string namespaceURI) { if (IsXmlDataNode) return _xmlNodeReader.GetAttribute(name, namespaceURI); for (int i = 0; i < _element.attributeCount; i++) { AttributeData attribute = _element.attributes[i]; if (attribute.localName == name && attribute.ns == namespaceURI) return attribute.value; } return null; } public override bool MoveToAttribute(string name, string namespaceURI) { if (IsXmlDataNode) return _xmlNodeReader.MoveToAttribute(name, _ns); for (int i = 0; i < _element.attributeCount; i++) { AttributeData attribute = _element.attributes[i]; if (attribute.localName == name && attribute.ns == namespaceURI) { MoveToAttribute(i); return true; } } return false; } public override bool MoveToElement() { if (IsXmlDataNode) return _xmlNodeReader.MoveToElement(); if (_nodeType != XmlNodeType.Attribute) return false; SetElement(); return true; } private void SetElement() { _nodeType = XmlNodeType.Element; _localName = _element.localName; _ns = _element.ns; _prefix = _element.prefix; _value = String.Empty; _attributeCount = _element.attributeCount; _attributeIndex = -1; } public override string LookupNamespace(string prefix) { if (IsXmlDataNode) return _xmlNodeReader.LookupNamespace(prefix); string ns; if (!s_prefixToNsTable.TryGetValue(prefix, out ns)) return null; return ns; } public override void Skip() { if (IsXmlDataNode) _xmlNodeReader.Skip(); else { if (ReadState != ReadState.Interactive) return; MoveToElement(); if (IsElementNode(_internalNodeType)) { int depth = 1; while (depth != 0) { if (!Read()) throw new XmlException(SR.InvalidXmlDeserializingExtensionData); if (IsElementNode(_internalNodeType)) depth++; else if (_internalNodeType == ExtensionDataNodeType.EndElement) { ReadEndElement(); depth--; } } } else Read(); } } private bool IsElementNode(ExtensionDataNodeType nodeType) { return (nodeType == ExtensionDataNodeType.Element || nodeType == ExtensionDataNodeType.ReferencedElement || nodeType == ExtensionDataNodeType.NullElement); } protected override void Dispose(bool disposing) { if (IsXmlDataNode) _xmlNodeReader.Dispose(); else { Reset(); _readState = ReadState.Closed; } base.Dispose(disposing); } public override bool Read() { if (_nodeType == XmlNodeType.Attribute && MoveToNextAttribute()) return true; MoveNext(_element.dataNode); switch (_internalNodeType) { case ExtensionDataNodeType.Element: case ExtensionDataNodeType.ReferencedElement: case ExtensionDataNodeType.NullElement: PushElement(); SetElement(); break; case ExtensionDataNodeType.Text: _nodeType = XmlNodeType.Text; _prefix = String.Empty; _ns = String.Empty; _localName = String.Empty; _attributeCount = 0; _attributeIndex = -1; break; case ExtensionDataNodeType.EndElement: _nodeType = XmlNodeType.EndElement; _prefix = String.Empty; _ns = String.Empty; _localName = String.Empty; _value = String.Empty; _attributeCount = 0; _attributeIndex = -1; PopElement(); break; case ExtensionDataNodeType.None: if (_depth != 0) throw new XmlException(SR.InvalidXmlDeserializingExtensionData); _nodeType = XmlNodeType.None; _prefix = String.Empty; _ns = String.Empty; _localName = String.Empty; _value = String.Empty; _attributeCount = 0; _readState = ReadState.EndOfFile; return false; case ExtensionDataNodeType.Xml: // do nothing break; default: Fx.Assert("ExtensionDataReader in invalid state"); throw new SerializationException(SR.InvalidStateInExtensionDataReader); } _readState = ReadState.Interactive; return true; } public override string Name { get { if (IsXmlDataNode) { return _xmlNodeReader.Name; } Fx.Assert("ExtensionDataReader Name property should only be called for IXmlSerializable"); return string.Empty; } } public override bool HasValue { get { if (IsXmlDataNode) { return _xmlNodeReader.HasValue; } Fx.Assert("ExtensionDataReader HasValue property should only be called for IXmlSerializable"); return false; } } public override string BaseURI { get { if (IsXmlDataNode) { return _xmlNodeReader.BaseURI; } Fx.Assert("ExtensionDataReader BaseURI property should only be called for IXmlSerializable"); return string.Empty; } } public override XmlNameTable NameTable { get { if (IsXmlDataNode) { return _xmlNodeReader.NameTable; } Fx.Assert("ExtensionDataReader NameTable property should only be called for IXmlSerializable"); return null; } } public override string GetAttribute(string name) { if (IsXmlDataNode) { return _xmlNodeReader.GetAttribute(name); } Fx.Assert("ExtensionDataReader GetAttribute method should only be called for IXmlSerializable"); return null; } public override string GetAttribute(int i) { if (IsXmlDataNode) { return _xmlNodeReader.GetAttribute(i); } Fx.Assert("ExtensionDataReader GetAttribute method should only be called for IXmlSerializable"); return null; } public override bool MoveToAttribute(string name) { if (IsXmlDataNode) { return _xmlNodeReader.MoveToAttribute(name); } Fx.Assert("ExtensionDataReader MoveToAttribute method should only be called for IXmlSerializable"); return false; } public override void ResolveEntity() { if (IsXmlDataNode) { _xmlNodeReader.ResolveEntity(); } else { Fx.Assert("ExtensionDataReader ResolveEntity method should only be called for IXmlSerializable"); } } public override bool ReadAttributeValue() { if (IsXmlDataNode) { return _xmlNodeReader.ReadAttributeValue(); } Fx.Assert("ExtensionDataReader ReadAttributeValue method should only be called for IXmlSerializable"); return false; } private void MoveNext(IDataNode dataNode) { throw NotImplemented.ByDesign; } private void SetNextElement(IDataNode node, string name, string ns, string prefix) { throw NotImplemented.ByDesign; } private void PushElement() { GrowElementsIfNeeded(); _elements[_depth++] = _element; if (_nextElement == null) _element = GetNextElement(); else { _element = _nextElement; _nextElement = null; } } private void PopElement() { _prefix = _element.prefix; _localName = _element.localName; _ns = _element.ns; if (_depth == 0) return; _depth--; if (_elements != null) { _element = _elements[_depth]; } } private void GrowElementsIfNeeded() { if (_elements == null) _elements = new ElementData[8]; else if (_elements.Length == _depth) { ElementData[] newElements = new ElementData[_elements.Length * 2]; Array.Copy(_elements, 0, newElements, 0, _elements.Length); _elements = newElements; } } private ElementData GetNextElement() { int nextDepth = _depth + 1; return (_elements == null || _elements.Length <= nextDepth || _elements[nextDepth] == null) ? new ElementData() : _elements[nextDepth]; } internal static string GetPrefix(string ns) { string prefix; ns = ns ?? String.Empty; if (!s_nsToPrefixTable.TryGetValue(ns, out prefix)) { lock (s_nsToPrefixTable) { if (!s_nsToPrefixTable.TryGetValue(ns, out prefix)) { prefix = (ns == null || ns.Length == 0) ? String.Empty : "p" + s_nsToPrefixTable.Count; AddPrefix(prefix, ns); } } } return prefix; } private static void AddPrefix(string prefix, string ns) { s_nsToPrefixTable.Add(ns, prefix); s_prefixToNsTable.Add(prefix, ns); } } #if USE_REFEMIT || uapaot public class AttributeData #else internal class AttributeData #endif { public string prefix; public string ns; public string localName; public string value; } #if USE_REFEMIT || uapaot public class ElementData #else internal class ElementData #endif { public string localName; public string ns; public string prefix; public int attributeCount; public AttributeData[] attributes; public IDataNode dataNode; public int childElementIndex; public void AddAttribute(string prefix, string ns, string name, string value) { GrowAttributesIfNeeded(); AttributeData attribute = attributes[attributeCount]; if (attribute == null) attributes[attributeCount] = attribute = new AttributeData(); attribute.prefix = prefix; attribute.ns = ns; attribute.localName = name; attribute.value = value; attributeCount++; } private void GrowAttributesIfNeeded() { if (attributes == null) attributes = new AttributeData[4]; else if (attributes.Length == attributeCount) { AttributeData[] newAttributes = new AttributeData[attributes.Length * 2]; Array.Copy(attributes, 0, newAttributes, 0, attributes.Length); attributes = newAttributes; } } } }
// 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. // Ported from desktop (BCL\System\DefaultBinder.cs) using System; using System.Reflection; using System.Diagnostics.Contracts; namespace Internal.Reflection.Core.Execution.Binder { internal static class DefaultBinder { // This method is passed a set of methods and must choose the best // fit. The methods all have the same number of arguments and the object // array args. On exit, this method will choice the best fit method // and coerce the args to match that method. By match, we mean all primitive // arguments are exact matches and all object arguments are exact or subclasses // of the target. If the target OR is an interface, the object must implement // that interface. There are a couple of exceptions // thrown when a method cannot be returned. If no method matches the args and // ArgumentException is thrown. If multiple methods match the args then // an AmbiguousMatchException is thrown. // // The most specific match will be selected. // public static MethodBase BindToMethod(MethodBase[] match, ref object[] args) { if (match == null || match.Length == 0) { throw new ArgumentException(SR.Arg_EmptyArray, nameof(match)); } MethodBase[] candidates = (MethodBase[])match.Clone(); int i; int j; #region Map named parameters to candidate parameter positions // We are creating an paramOrder array to act as a mapping // between the order of the args and the actual order of the // parameters in the method. This order may differ because // named parameters (names) may change the order. If names // is not provided, then we assume the default mapping (0,1,...) int[][] paramOrder = new int[candidates.Length][]; for (i = 0; i < candidates.Length; i++) { ParameterInfo[] par = candidates[i].GetParameters(); // args.Length + 1 takes into account the possibility of a last paramArray that can be omitted paramOrder[i] = new int[(par.Length > args.Length) ? par.Length : args.Length]; // Default mapping for (j = 0; j < args.Length; j++) { paramOrder[i][j] = j; } } #endregion Type[] paramArrayTypes = new Type[candidates.Length]; Type[] argTypes = new Type[args.Length]; #region Cache the type of the provided arguments // object that contain a null are treated as if they were typeless (but match either object // references or value classes). We mark this condition by placing a null in the argTypes array. for (i = 0; i < args.Length; i++) { if (args[i] != null) { argTypes[i] = args[i].GetType(); } } #endregion // Find the method that matches... int CurIdx = 0; Type paramArrayType = null; #region Filter methods by parameter count and type for (i = 0; i < candidates.Length; i++) { paramArrayType = null; // If we have named parameters then we may have a hole in the candidates array. if (candidates[i] == null) { continue; } // Validate the parameters. ParameterInfo[] par = candidates[i].GetParameters(); #region Match method by parameter count if (par.Length == 0) { #region No formal parameters if (args.Length != 0) { if ((candidates[i].CallingConvention & CallingConventions.VarArgs) == 0) { continue; } } // This is a valid routine so we move it up the candidates list. paramOrder[CurIdx] = paramOrder[i]; candidates[CurIdx++] = candidates[i]; continue; #endregion } else if (par.Length > args.Length) { #region Shortage of provided parameters // If the number of parameters is greater than the number of args then // we are in the situation were we may be using default values. for (j = args.Length; j < par.Length - 1; j++) { if (!par[j].HasDefaultValue) { break; } } if (j != par.Length - 1) { continue; } if (!par[j].HasDefaultValue) { if (!par[j].ParameterType.IsArray) { continue; } if (!HasParamArrayAttribute(par[j])) { continue; } paramArrayType = par[j].ParameterType.GetElementType(); } #endregion } else if (par.Length < args.Length) { #region Excess provided parameters // test for the ParamArray case int lastArgPos = par.Length - 1; if (!par[lastArgPos].ParameterType.IsArray) { continue; } if (!HasParamArrayAttribute(par[lastArgPos])) { continue; } if (paramOrder[i][lastArgPos] != lastArgPos) { continue; } paramArrayType = par[lastArgPos].ParameterType.GetElementType(); #endregion } else { #region Test for paramArray, save paramArray type int lastArgPos = par.Length - 1; if (par[lastArgPos].ParameterType.IsArray && HasParamArrayAttribute(par[lastArgPos]) && paramOrder[i][lastArgPos] == lastArgPos) { if (!par[lastArgPos].ParameterType.GetTypeInfo().IsAssignableFrom(argTypes[lastArgPos].GetTypeInfo())) { paramArrayType = par[lastArgPos].ParameterType.GetElementType(); } } #endregion } #endregion Type pCls = null; int argsToCheck = (paramArrayType != null) ? par.Length - 1 : args.Length; #region Match method by parameter type for (j = 0; j < argsToCheck; j++) { #region Classic argument coercion checks // get the formal type pCls = par[j].ParameterType; if (pCls.IsByRef) { pCls = pCls.GetElementType(); } // the type is the same if (pCls == argTypes[paramOrder[i][j]]) { continue; } // the argument was null, so it matches with everything if (args[paramOrder[i][j]] == null) { continue; } // the type is Object, so it will match everything if (pCls == typeof(Object)) { continue; } // now do a "classic" type check if (pCls.GetTypeInfo().IsPrimitive) { if (argTypes[paramOrder[i][j]] == null || !CanConvertPrimitiveObjectToType(args[paramOrder[i][j]], pCls)) { break; } } else { if (argTypes[paramOrder[i][j]] == null) { continue; } if (!pCls.GetTypeInfo().IsAssignableFrom(argTypes[paramOrder[i][j]].GetTypeInfo())) { break; } } #endregion } if (paramArrayType != null && j == par.Length - 1) { #region Check that excess arguments can be placed in the param array // Legacy: It's so pathetic that we go to all this trouble let "widening-compatible" params arguments through this screen // only to end up blowing up with an InvalidCastException anyway because we use Array.Copy() to do the actual copy down below. // Ah, the joys of backward compatibility... for (; j < args.Length; j++) { if (paramArrayType.GetTypeInfo().IsPrimitive) { if (argTypes[j] == null || !CanConvertPrimitiveObjectToType(args[j], paramArrayType)) { break; } } else { if (argTypes[j] == null) { continue; } if (!paramArrayType.GetTypeInfo().IsAssignableFrom(argTypes[j].GetTypeInfo())) { break; } } } #endregion } #endregion if (j == args.Length) { #region This is a valid routine so we move it up the candidates list paramOrder[CurIdx] = paramOrder[i]; paramArrayTypes[CurIdx] = paramArrayType; candidates[CurIdx++] = candidates[i]; #endregion } } #endregion // If we didn't find a method if (CurIdx == 0) { throw new MissingMethodException(SR.MissingMember); } if (CurIdx == 1) { #region Found only one method // If the parameters and the args are not the same length or there is a paramArray // then we need to create a argument array. ParameterInfo[] parms = candidates[0].GetParameters(); if (parms.Length == args.Length) { if (paramArrayTypes[0] != null) { Object[] objs = new Object[parms.Length]; int lastPos = parms.Length - 1; Array.Copy(args, 0, objs, 0, lastPos); objs[lastPos] = Array.CreateInstance(paramArrayTypes[0], 1); ((Array)objs[lastPos]).SetValue(args[lastPos], 0); args = objs; } } else if (parms.Length > args.Length) { Object[] objs = new Object[parms.Length]; for (i = 0; i < args.Length; i++) { objs[i] = args[i]; } for (; i < parms.Length - 1; i++) { objs[i] = parms[i].DefaultValue; } if (paramArrayTypes[0] != null) { objs[i] = Array.CreateInstance(paramArrayTypes[0], 0); // create an empty array for the } else { objs[i] = parms[i].DefaultValue; } args = objs; } else { if ((candidates[0].CallingConvention & CallingConventions.VarArgs) == 0) { Object[] objs = new Object[parms.Length]; int paramArrayPos = parms.Length - 1; Array.Copy(args, 0, objs, 0, paramArrayPos); objs[paramArrayPos] = Array.CreateInstance(paramArrayTypes[0], args.Length - paramArrayPos); Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos); args = objs; } } #endregion return candidates[0]; } int currentMin = 0; bool ambig = false; for (i = 1; i < CurIdx; i++) { #region Walk all of the methods looking the most specific method to invoke int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder[currentMin], paramArrayTypes[currentMin], candidates[i], paramOrder[i], paramArrayTypes[i], argTypes, args); if (newMin == 0) { ambig = true; } else if (newMin == 2) { currentMin = i; ambig = false; } #endregion } if (ambig) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } // If the parameters and the args are not the same length or there is a paramArray // then we need to create a argument array. ParameterInfo[] parameters = candidates[currentMin].GetParameters(); if (parameters.Length == args.Length) { if (paramArrayTypes[currentMin] != null) { Object[] objs = new Object[parameters.Length]; int lastPos = parameters.Length - 1; Array.Copy(args, 0, objs, 0, lastPos); objs[lastPos] = Array.CreateInstance(paramArrayTypes[currentMin], 1); ((Array)objs[lastPos]).SetValue(args[lastPos], 0); args = objs; } } else if (parameters.Length > args.Length) { Object[] objs = new Object[parameters.Length]; for (i = 0; i < args.Length; i++) { objs[i] = args[i]; } for (; i < parameters.Length - 1; i++) { objs[i] = parameters[i].DefaultValue; } if (paramArrayTypes[currentMin] != null) { objs[i] = Array.CreateInstance(paramArrayTypes[currentMin], 0); } else { objs[i] = parameters[i].DefaultValue; } args = objs; } else { if ((candidates[currentMin].CallingConvention & CallingConventions.VarArgs) == 0) { Object[] objs = new Object[parameters.Length]; int paramArrayPos = parameters.Length - 1; Array.Copy(args, 0, objs, 0, paramArrayPos); objs[paramArrayPos] = Array.CreateInstance(paramArrayTypes[currentMin], args.Length - paramArrayPos); Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos); args = objs; } } return candidates[currentMin]; } // Given a set of methods that match the base criteria, select a method based // upon an array of types. This method should return null if no method matches // the criteria. public static MethodBase SelectMethod(MethodBase[] match, Type[] types) { int i; int j; MethodBase[] candidates = (MethodBase[])match.Clone(); // Find all the methods that can be described by the types parameter. // Remove all of them that cannot. int CurIdx = 0; for (i = 0; i < candidates.Length; i++) { ParameterInfo[] par = candidates[i].GetParameters(); if (par.Length != types.Length) continue; for (j = 0; j < types.Length; j++) { Type pCls = par[j].ParameterType; if (pCls == types[j]) { continue; } if (pCls == typeof(Object)) { continue; } if (pCls.GetTypeInfo().IsPrimitive) { if (!CanConvertPrimitive(types[j], pCls)) { break; } } else { if (!pCls.GetTypeInfo().IsAssignableFrom(types[j].GetTypeInfo())) { break; } } } if (j == types.Length) { candidates[CurIdx++] = candidates[i]; } } if (CurIdx == 0) { return null; } if (CurIdx == 1) { return candidates[0]; } // Walk all of the methods looking the most specific method to invoke int currentMin = 0; bool ambig = false; int[] paramOrder = new int[types.Length]; for (i = 0; i < types.Length; i++) { paramOrder[i] = i; } for (i = 1; i < CurIdx; i++) { int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder, null, candidates[i], paramOrder, null, types, null); if (newMin == 0) { ambig = true; } else { if (newMin == 2) { currentMin = i; ambig = false; currentMin = i; } } } if (ambig) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } return candidates[currentMin]; } private static bool HasParamArrayAttribute(ParameterInfo parameterInfo) { foreach (CustomAttributeData cad in parameterInfo.CustomAttributes) { if (cad.AttributeType.Equals(typeof(ParamArrayAttribute))) { return true; } } return false; } private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type paramArrayType1, ParameterInfo[] p2, int[] paramOrder2, Type paramArrayType2, Type[] types, Object[] args) { // A method using params is always less specific than one not using params if (paramArrayType1 != null && paramArrayType2 == null) { return 2; } if (paramArrayType2 != null && paramArrayType1 == null) { return 1; } // now either p1 and p2 both use params or neither does. bool p1Less = false; bool p2Less = false; for (int i = 0; i < types.Length; i++) { if (args != null && args[i] == Type.Missing) { continue; } Type c1, c2; // If a param array is present, then either // the user re-ordered the parameters in which case // the argument to the param array is either an array // in which case the params is conceptually ignored and so paramArrayType1 == null // or the argument to the param array is a single element // in which case paramOrder[i] == p1.Length - 1 for that element // or the user did not re-order the parameters in which case // the paramOrder array could contain indexes larger than p.Length - 1 (see VSW 577286) // so any index >= p.Length - 1 is being put in the param array if (paramArrayType1 != null && paramOrder1[i] >= p1.Length - 1) { c1 = paramArrayType1; } else { c1 = p1[paramOrder1[i]].ParameterType; } if (paramArrayType2 != null && paramOrder2[i] >= p2.Length - 1) { c2 = paramArrayType2; } else { c2 = p2[paramOrder2[i]].ParameterType; } if (c1 == c2) { continue; } switch (FindMostSpecificType(c1, c2, types[i])) { case 0: return 0; case 1: p1Less = true; break; case 2: p2Less = true; break; } } // Two way p1Less and p2Less can be equal. All the arguments are the // same they both equal false, otherwise there were things that both // were the most specific type on.... if (p1Less == p2Less) { // if we cannot tell which is a better match based on parameter types (p1Less == p2Less), // let's see which one has the most matches without using the params array (the longer one wins). if (!p1Less && args != null) { if (p1.Length > p2.Length) { return 1; } else if (p2.Length > p1.Length) { return 2; } } return 0; } else { return (p1Less == true) ? 1 : 2; } } private static int FindMostSpecificType(Type c1, Type c2, Type t) { // If the two types are exact move on... if (c1 == c2) { return 0; } if (c1 == t) { return 1; } if (c2 == t) { return 2; } bool c1FromC2; bool c2FromC1; if (c1.IsByRef || c2.IsByRef) { if (c1.IsByRef && c2.IsByRef) { c1 = c1.GetElementType(); c2 = c2.GetElementType(); } else if (c1.IsByRef) { if (c1.GetElementType() == c2) { return 2; } c1 = c1.GetElementType(); } else { if (c2.GetElementType() == c1) { return 1; } c2 = c2.GetElementType(); } } if (c1.GetTypeInfo().IsPrimitive && c2.GetTypeInfo().IsPrimitive) { c1FromC2 = CanConvertPrimitive(c2, c1); c2FromC1 = CanConvertPrimitive(c1, c2); } else { c1FromC2 = c1.GetTypeInfo().IsAssignableFrom(c2.GetTypeInfo()); c2FromC1 = c2.GetTypeInfo().IsAssignableFrom(c1.GetTypeInfo()); } if (c1FromC2 == c2FromC1) return 0; if (c1FromC2) { return 2; } else { return 1; } } public static PropertyInfo SelectProperty(PropertyInfo[] match, Type returnType, Type[] indexes) { // Allow a null indexes array. But if it is not null, every element must be non-null as well. if (indexes != null && !Contract.ForAll(indexes, delegate (Type t) { return t != null; })) { Exception e; // Written this way to pass the Code Contracts style requirements. e = new ArgumentNullException(nameof(indexes)); throw e; } if (match == null || match.Length == 0) { throw new ArgumentException(SR.Arg_EmptyArray, nameof(match)); } PropertyInfo[] candidates = (PropertyInfo[])match.Clone(); int i, j = 0; // Find all the properties that can be described by type indexes parameter int CurIdx = 0; int indexesLength = (indexes != null) ? indexes.Length : 0; for (i = 0; i < candidates.Length; i++) { if (indexes != null) { ParameterInfo[] par = candidates[i].GetIndexParameters(); if (par.Length != indexesLength) { continue; } for (j = 0; j < indexesLength; j++) { Type pCls = par[j].ParameterType; // If the classes exactly match continue if (pCls == indexes[j]) { continue; } if (pCls == typeof(Object)) { continue; } if (pCls.GetTypeInfo().IsPrimitive) { if (!CanConvertPrimitive(indexes[j], pCls)) { break; } } else { if (!pCls.GetTypeInfo().IsAssignableFrom(indexes[j].GetTypeInfo())) { break; } } } } if (j == indexesLength) { if (returnType != null) { if (candidates[i].PropertyType.GetTypeInfo().IsPrimitive) { if (!CanConvertPrimitive(returnType, candidates[i].PropertyType)) { continue; } } else { if (!candidates[i].PropertyType.GetTypeInfo().IsAssignableFrom(returnType.GetTypeInfo())) { continue; } } } candidates[CurIdx++] = candidates[i]; } } if (CurIdx == 0) { return null; } if (CurIdx == 1) { return candidates[0]; } // Walk all of the properties looking the most specific method to invoke int currentMin = 0; bool ambig = false; int[] paramOrder = new int[indexesLength]; for (i = 0; i < indexesLength; i++) { paramOrder[i] = i; } for (i = 1; i < CurIdx; i++) { int newMin = FindMostSpecificType(candidates[currentMin].PropertyType, candidates[i].PropertyType, returnType); if (newMin == 0 && indexes != null) newMin = FindMostSpecific(candidates[currentMin].GetIndexParameters(), paramOrder, null, candidates[i].GetIndexParameters(), paramOrder, null, indexes, null); if (newMin == 0) { newMin = FindMostSpecificProperty(candidates[currentMin], candidates[i]); if (newMin == 0) { ambig = true; } } if (newMin == 2) { ambig = false; currentMin = i; } } if (ambig) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } return candidates[currentMin]; } private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type paramArrayType1, MethodBase m2, int[] paramOrder2, Type paramArrayType2, Type[] types, Object[] args) { // Find the most specific method based on the parameters. int res = FindMostSpecific(m1.GetParameters(), paramOrder1, paramArrayType1, m2.GetParameters(), paramOrder2, paramArrayType2, types, args); // If the match was not ambiguous then return the result. if (res != 0) { return res; } // Check to see if the methods have the exact same name and signature. if (CompareMethodSigAndName(m1, m2)) { // Determine the depth of the declaring types for both methods. int hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType); int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType); // The most derived method is the most specific one. if (hierarchyDepth1 == hierarchyDepth2) { return 0; } else if (hierarchyDepth1 < hierarchyDepth2) { return 2; } else { return 1; } } // The match is ambiguous. return 0; } private static int FindMostSpecificProperty(PropertyInfo cur1, PropertyInfo cur2) { // Check to see if the fields have the same name. if (cur1.Name == cur2.Name) { int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType); int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType); if (hierarchyDepth1 == hierarchyDepth2) { return 0; } else if (hierarchyDepth1 < hierarchyDepth2) { return 2; } else { return 1; } } // The match is ambiguous. return 0; } private static bool CompareMethodSigAndName(MethodBase m1, MethodBase m2) { ParameterInfo[] params1 = m1.GetParameters(); ParameterInfo[] params2 = m2.GetParameters(); if (params1.Length != params2.Length) { return false; } int numParams = params1.Length; for (int i = 0; i < numParams; i++) { if (params1[i].ParameterType != params2[i].ParameterType) { return false; } } return true; } private static int GetHierarchyDepth(Type t) { int depth = 0; Type currentType = t; do { depth++; currentType = currentType.GetTypeInfo().BaseType; } while (currentType != null); return depth; } // CanConvertPrimitive // This will determine if the source can be converted to the target type private static bool CanConvertPrimitive(Type source, Type target) { return CanPrimitiveWiden(source, target); } // CanConvertPrimitiveObjectToType private static bool CanConvertPrimitiveObjectToType(Object source, Type type) { return CanConvertPrimitive(source.GetType(), type); } #region Portable Runtime Augments Methods private static bool CanPrimitiveWiden(Type source, Type target) { Primitives widerCodes = _primitiveConversions[(int)GetTypeCode(source)]; Primitives targetCode = (Primitives)(1 << (int)GetTypeCode(target)); return 0 != (widerCodes & targetCode); } [Flags] private enum Primitives { Boolean = 1 << (int)TypeCode.Boolean, Char = 1 << (int)TypeCode.Char, SByte = 1 << (int)TypeCode.SByte, Byte = 1 << (int)TypeCode.Byte, Int16 = 1 << (int)TypeCode.Int16, UInt16 = 1 << (int)TypeCode.UInt16, Int32 = 1 << (int)TypeCode.Int32, UInt32 = 1 << (int)TypeCode.UInt32, Int64 = 1 << (int)TypeCode.Int64, UInt64 = 1 << (int)TypeCode.UInt64, Single = 1 << (int)TypeCode.Single, Double = 1 << (int)TypeCode.Double, Decimal = 1 << (int)TypeCode.Decimal, DateTime = 1 << (int)TypeCode.DateTime, String = 1 << (int)TypeCode.String, } private static Primitives[] _primitiveConversions = new Primitives[] { /* Empty */ 0, // not primitive /* Object */ 0, // not primitive /* DBNull */ 0, // not exposed. /* Boolean */ Primitives.Boolean, /* Char */ Primitives.Char | Primitives.UInt16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, /* SByte */ Primitives.SByte | Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, /* Byte */ Primitives.Byte | Primitives.Char | Primitives.UInt16 | Primitives.Int16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, /* Int16 */ Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, /* UInt16 */ Primitives.UInt16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, /* Int32 */ Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double | /* UInt32 */ Primitives.UInt32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, /* Int64 */ Primitives.Int64 | Primitives.Single | Primitives.Double, /* UInt64 */ Primitives.UInt64 | Primitives.Single | Primitives.Double, /* Single */ Primitives.Single | Primitives.Double, /* Double */ Primitives.Double, /* Decimal */ Primitives.Decimal, /* DateTime */ Primitives.DateTime, /* [Unused] */ 0, /* String */ Primitives.String, }; private static TypeCode GetTypeCode(Type type) { if (type == typeof(Boolean)) { return TypeCode.Boolean; } if (type == typeof(Char)) { return TypeCode.Char; } if (type == typeof(SByte)) { return TypeCode.SByte; } if (type == typeof(Byte)) { return TypeCode.Byte; } if (type == typeof(Int16)) { return TypeCode.Int16; } if (type == typeof(UInt16)) { return TypeCode.UInt16; } if (type == typeof(Int32)) { return TypeCode.Int32; } if (type == typeof(UInt32)) { return TypeCode.UInt32; } if (type == typeof(Int64)) { return TypeCode.Int64; } if (type == typeof(UInt64)) { return TypeCode.UInt64; } if (type == typeof(Single)) { return TypeCode.Single; } if (type == typeof(Double)) { return TypeCode.Double; } if (type == typeof(Decimal)) { return TypeCode.Decimal; } if (type == typeof(DateTime)) { return TypeCode.DateTime; } if (type.GetTypeInfo().IsEnum) { return GetTypeCode(Enum.GetUnderlyingType(type)); } return TypeCode.Object; } #endregion Portable Runtime Augments Methods } }
// // https://github.com/mythz/ServiceStack.Redis // ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2013 ServiceStack. // // Licensed under the same terms of Redis and ServiceStack: new BSD license. // using System; using System.Collections; using System.Collections.Generic; namespace NServiceKit.Redis { /// <summary> /// Wrap the common redis list operations under a IList[string] interface. /// </summary> internal class RedisClientList : IRedisList { private readonly RedisClient client; private readonly string listId; private const int PageLimit = 1000; public RedisClientList(RedisClient client, string listId) { this.listId = listId; this.client = client; } public string Id { get { return listId; } } public IEnumerator<string> GetEnumerator() { return this.Count <= PageLimit ? client.GetAllItemsFromList(listId).GetEnumerator() : GetPagingEnumerator(); } public IEnumerator<string> GetPagingEnumerator() { var skip = 0; List<string> pageResults; do { pageResults = client.GetRangeFromList(listId, skip, skip + PageLimit - 1); foreach (var result in pageResults) { yield return result; } skip += PageLimit; } while (pageResults.Count == PageLimit); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(string item) { client.AddItemToList(listId, item); } public void Clear() { client.RemoveAllFromList(listId); } public bool Contains(string item) { //TODO: replace with native implementation when exists foreach (var existingItem in this) { if (existingItem == item) return true; } return false; } public void CopyTo(string[] array, int arrayIndex) { var allItemsInList = client.GetAllItemsFromList(listId); allItemsInList.CopyTo(array, arrayIndex); } public bool Remove(string item) { return client.RemoveItemFromList(listId, item) > 0; } public int Count { get { return (int)client.GetListCount(listId); } } public bool IsReadOnly { get { return false; } } public int IndexOf(string item) { //TODO: replace with native implementation when exists var i = 0; foreach (var existingItem in this) { if (existingItem == item) return i; i++; } return -1; } public void Insert(int index, string item) { //TODO: replace with implementation involving creating on new temp list then replacing //otherwise wait for native implementation throw new NotImplementedException(); } public void RemoveAt(int index) { //TODO: replace with native implementation when one exists var markForDelete = Guid.NewGuid().ToString(); client.SetItemInList(listId, index, markForDelete); client.RemoveItemFromList(listId, markForDelete); } public string this[int index] { get { return client.GetItemFromList(listId, index); } set { client.SetItemInList(listId, index, value); } } public List<string> GetAll() { return client.GetAllItemsFromList(listId); } public List<string> GetRange(int startingFrom, int endingAt) { return client.GetRangeFromList(listId, startingFrom, endingAt); } public List<string> GetRangeFromSortedList(int startingFrom, int endingAt) { return client.GetRangeFromSortedList(listId, startingFrom, endingAt); } public void RemoveAll() { client.RemoveAllFromList(listId); } public void Trim(int keepStartingFrom, int keepEndingAt) { client.TrimList(listId, keepStartingFrom, keepEndingAt); } public long RemoveValue(string value) { return client.RemoveItemFromList(listId, value); } public long RemoveValue(string value, int noOfMatches) { return client.RemoveItemFromList(listId, value, noOfMatches); } public void Append(string value) { Add(value); } public string RemoveStart() { return client.RemoveStartFromList(listId); } public string BlockingRemoveStart(TimeSpan? timeOut) { return client.BlockingRemoveStartFromList(listId, timeOut); } public string RemoveEnd() { return client.RemoveEndFromList(listId); } public void Enqueue(string value) { client.EnqueueItemOnList(listId, value); } public void Prepend(string value) { client.PrependItemToList(listId, value); } public void Push(string value) { client.PushItemToList(listId, value); } public string Pop() { return client.PopItemFromList(listId); } public string BlockingPop(TimeSpan? timeOut) { return client.BlockingPopItemFromList(listId, timeOut); } public string Dequeue() { return client.DequeueItemFromList(listId); } public string BlockingDequeue(TimeSpan? timeOut) { return client.BlockingDequeueItemFromList(listId, timeOut); } public string PopAndPush(IRedisList toList) { return client.PopAndPushItemBetweenLists(listId, toList.Id); } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using CookComputing.XmlRpc; namespace XenAPI { /// <summary> /// Represents a patch stored on a server /// First published in XenServer 4.0. /// </summary> public partial class Host_patch : XenObject<Host_patch> { public Host_patch() { } public Host_patch(string uuid, string name_label, string name_description, string version, XenRef<Host> host, bool applied, DateTime timestamp_applied, long size, XenRef<Pool_patch> pool_patch, Dictionary<string, string> other_config) { this.uuid = uuid; this.name_label = name_label; this.name_description = name_description; this.version = version; this.host = host; this.applied = applied; this.timestamp_applied = timestamp_applied; this.size = size; this.pool_patch = pool_patch; this.other_config = other_config; } /// <summary> /// Creates a new Host_patch from a Proxy_Host_patch. /// </summary> /// <param name="proxy"></param> public Host_patch(Proxy_Host_patch proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(Host_patch update) { uuid = update.uuid; name_label = update.name_label; name_description = update.name_description; version = update.version; host = update.host; applied = update.applied; timestamp_applied = update.timestamp_applied; size = update.size; pool_patch = update.pool_patch; other_config = update.other_config; } internal void UpdateFromProxy(Proxy_Host_patch proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; name_label = proxy.name_label == null ? null : (string)proxy.name_label; name_description = proxy.name_description == null ? null : (string)proxy.name_description; version = proxy.version == null ? null : (string)proxy.version; host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host); applied = (bool)proxy.applied; timestamp_applied = proxy.timestamp_applied; size = proxy.size == null ? 0 : long.Parse((string)proxy.size); pool_patch = proxy.pool_patch == null ? null : XenRef<Pool_patch>.Create(proxy.pool_patch); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_Host_patch ToProxy() { Proxy_Host_patch result_ = new Proxy_Host_patch(); result_.uuid = (uuid != null) ? uuid : ""; result_.name_label = (name_label != null) ? name_label : ""; result_.name_description = (name_description != null) ? name_description : ""; result_.version = (version != null) ? version : ""; result_.host = (host != null) ? host : ""; result_.applied = applied; result_.timestamp_applied = timestamp_applied; result_.size = size.ToString(); result_.pool_patch = (pool_patch != null) ? pool_patch : ""; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Creates a new Host_patch from a Hashtable. /// </summary> /// <param name="table"></param> public Host_patch(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); name_label = Marshalling.ParseString(table, "name_label"); name_description = Marshalling.ParseString(table, "name_description"); version = Marshalling.ParseString(table, "version"); host = Marshalling.ParseRef<Host>(table, "host"); applied = Marshalling.ParseBool(table, "applied"); timestamp_applied = Marshalling.ParseDateTime(table, "timestamp_applied"); size = Marshalling.ParseLong(table, "size"); pool_patch = Marshalling.ParseRef<Pool_patch>(table, "pool_patch"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Host_patch other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._name_label, other._name_label) && Helper.AreEqual2(this._name_description, other._name_description) && Helper.AreEqual2(this._version, other._version) && Helper.AreEqual2(this._host, other._host) && Helper.AreEqual2(this._applied, other._applied) && Helper.AreEqual2(this._timestamp_applied, other._timestamp_applied) && Helper.AreEqual2(this._size, other._size) && Helper.AreEqual2(this._pool_patch, other._pool_patch) && Helper.AreEqual2(this._other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Host_patch server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { Host_patch.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given host_patch. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> [Deprecated("XenServer 7.1")] public static Host_patch get_record(Session session, string _host_patch) { return new Host_patch((Proxy_Host_patch)session.proxy.host_patch_get_record(session.uuid, (_host_patch != null) ? _host_patch : "").parse()); } /// <summary> /// Get a reference to the host_patch instance with the specified UUID. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> [Deprecated("XenServer 7.1")] public static XenRef<Host_patch> get_by_uuid(Session session, string _uuid) { return XenRef<Host_patch>.Create(session.proxy.host_patch_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse()); } /// <summary> /// Get all the host_patch instances with the given label. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_label">label of object to return</param> [Deprecated("XenServer 7.1")] public static List<XenRef<Host_patch>> get_by_name_label(Session session, string _label) { return XenRef<Host_patch>.Create(session.proxy.host_patch_get_by_name_label(session.uuid, (_label != null) ? _label : "").parse()); } /// <summary> /// Get the uuid field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static string get_uuid(Session session, string _host_patch) { return (string)session.proxy.host_patch_get_uuid(session.uuid, (_host_patch != null) ? _host_patch : "").parse(); } /// <summary> /// Get the name/label field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static string get_name_label(Session session, string _host_patch) { return (string)session.proxy.host_patch_get_name_label(session.uuid, (_host_patch != null) ? _host_patch : "").parse(); } /// <summary> /// Get the name/description field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static string get_name_description(Session session, string _host_patch) { return (string)session.proxy.host_patch_get_name_description(session.uuid, (_host_patch != null) ? _host_patch : "").parse(); } /// <summary> /// Get the version field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static string get_version(Session session, string _host_patch) { return (string)session.proxy.host_patch_get_version(session.uuid, (_host_patch != null) ? _host_patch : "").parse(); } /// <summary> /// Get the host field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static XenRef<Host> get_host(Session session, string _host_patch) { return XenRef<Host>.Create(session.proxy.host_patch_get_host(session.uuid, (_host_patch != null) ? _host_patch : "").parse()); } /// <summary> /// Get the applied field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static bool get_applied(Session session, string _host_patch) { return (bool)session.proxy.host_patch_get_applied(session.uuid, (_host_patch != null) ? _host_patch : "").parse(); } /// <summary> /// Get the timestamp_applied field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static DateTime get_timestamp_applied(Session session, string _host_patch) { return session.proxy.host_patch_get_timestamp_applied(session.uuid, (_host_patch != null) ? _host_patch : "").parse(); } /// <summary> /// Get the size field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static long get_size(Session session, string _host_patch) { return long.Parse((string)session.proxy.host_patch_get_size(session.uuid, (_host_patch != null) ? _host_patch : "").parse()); } /// <summary> /// Get the pool_patch field of the given host_patch. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static XenRef<Pool_patch> get_pool_patch(Session session, string _host_patch) { return XenRef<Pool_patch>.Create(session.proxy.host_patch_get_pool_patch(session.uuid, (_host_patch != null) ? _host_patch : "").parse()); } /// <summary> /// Get the other_config field of the given host_patch. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static Dictionary<string, string> get_other_config(Session session, string _host_patch) { return Maps.convert_from_proxy_string_string(session.proxy.host_patch_get_other_config(session.uuid, (_host_patch != null) ? _host_patch : "").parse()); } /// <summary> /// Set the other_config field of the given host_patch. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _host_patch, Dictionary<string, string> _other_config) { session.proxy.host_patch_set_other_config(session.uuid, (_host_patch != null) ? _host_patch : "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given host_patch. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _host_patch, string _key, string _value) { session.proxy.host_patch_add_to_other_config(session.uuid, (_host_patch != null) ? _host_patch : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given host_patch. If the key is not in that Map, then do nothing. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _host_patch, string _key) { session.proxy.host_patch_remove_from_other_config(session.uuid, (_host_patch != null) ? _host_patch : "", (_key != null) ? _key : "").parse(); } /// <summary> /// Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch /// First published in XenServer 4.0. /// Deprecated since XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> [Deprecated("XenServer 4.1")] public static void destroy(Session session, string _host_patch) { session.proxy.host_patch_destroy(session.uuid, (_host_patch != null) ? _host_patch : "").parse(); } /// <summary> /// Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch /// First published in XenServer 4.0. /// Deprecated since XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> [Deprecated("XenServer 4.1")] public static XenRef<Task> async_destroy(Session session, string _host_patch) { return XenRef<Task>.Create(session.proxy.async_host_patch_destroy(session.uuid, (_host_patch != null) ? _host_patch : "").parse()); } /// <summary> /// Apply the selected patch and return its output /// First published in XenServer 4.0. /// Deprecated since XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> [Deprecated("XenServer 4.1")] public static string apply(Session session, string _host_patch) { return (string)session.proxy.host_patch_apply(session.uuid, (_host_patch != null) ? _host_patch : "").parse(); } /// <summary> /// Apply the selected patch and return its output /// First published in XenServer 4.0. /// Deprecated since XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> [Deprecated("XenServer 4.1")] public static XenRef<Task> async_apply(Session session, string _host_patch) { return XenRef<Task>.Create(session.proxy.async_host_patch_apply(session.uuid, (_host_patch != null) ? _host_patch : "").parse()); } /// <summary> /// Return a list of all the host_patchs known to the system. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.1. /// </summary> /// <param name="session">The session</param> [Deprecated("XenServer 7.1")] public static List<XenRef<Host_patch>> get_all(Session session) { return XenRef<Host_patch>.Create(session.proxy.host_patch_get_all(session.uuid).parse()); } /// <summary> /// Get all the host_patch Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Host_patch>, Host_patch> get_all_records(Session session) { return XenRef<Host_patch>.Create<Proxy_Host_patch>(session.proxy.host_patch_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// a human-readable name /// </summary> public virtual string name_label { get { return _name_label; } set { if (!Helper.AreEqual(value, _name_label)) { _name_label = value; Changed = true; NotifyPropertyChanged("name_label"); } } } private string _name_label; /// <summary> /// a notes field containing human-readable description /// </summary> public virtual string name_description { get { return _name_description; } set { if (!Helper.AreEqual(value, _name_description)) { _name_description = value; Changed = true; NotifyPropertyChanged("name_description"); } } } private string _name_description; /// <summary> /// Patch version number /// </summary> public virtual string version { get { return _version; } set { if (!Helper.AreEqual(value, _version)) { _version = value; Changed = true; NotifyPropertyChanged("version"); } } } private string _version; /// <summary> /// Host the patch relates to /// </summary> public virtual XenRef<Host> host { get { return _host; } set { if (!Helper.AreEqual(value, _host)) { _host = value; Changed = true; NotifyPropertyChanged("host"); } } } private XenRef<Host> _host; /// <summary> /// True if the patch has been applied /// </summary> public virtual bool applied { get { return _applied; } set { if (!Helper.AreEqual(value, _applied)) { _applied = value; Changed = true; NotifyPropertyChanged("applied"); } } } private bool _applied; /// <summary> /// Time the patch was applied /// </summary> public virtual DateTime timestamp_applied { get { return _timestamp_applied; } set { if (!Helper.AreEqual(value, _timestamp_applied)) { _timestamp_applied = value; Changed = true; NotifyPropertyChanged("timestamp_applied"); } } } private DateTime _timestamp_applied; /// <summary> /// Size of the patch /// </summary> public virtual long size { get { return _size; } set { if (!Helper.AreEqual(value, _size)) { _size = value; Changed = true; NotifyPropertyChanged("size"); } } } private long _size; /// <summary> /// The patch applied /// First published in XenServer 4.1. /// </summary> public virtual XenRef<Pool_patch> pool_patch { get { return _pool_patch; } set { if (!Helper.AreEqual(value, _pool_patch)) { _pool_patch = value; Changed = true; NotifyPropertyChanged("pool_patch"); } } } private XenRef<Pool_patch> _pool_patch; /// <summary> /// additional configuration /// First published in XenServer 4.1. /// </summary> public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config; } }
namespace tomenglertde.Wax.Model.Wix { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using tomenglertde.Wax.Model.Mapping; using tomenglertde.Wax.Model.Tools; using tomenglertde.Wax.Model.VisualStudio; public class WixSourceFile { private readonly EnvDTE.ProjectItem _projectItem; private readonly XDocument _xmlFile; private XDocument _rawXmlFile; private readonly XElement _root; private readonly List<WixFileNode> _fileNodes; private readonly List<WixDirectoryNode> _directoryNodes; private readonly List<WixComponentGroupNode> _componentGroupNodes; private readonly List<WixComponentNode> _componentNodes; private readonly List<WixFeatureNode> _featureNodes; private readonly List<WixDefine> _defines; public WixSourceFile(WixProject project, EnvDTE.ProjectItem projectItem) { Project = project; _projectItem = projectItem; try { _xmlFile = _projectItem.GetXmlContent(LoadOptions.PreserveWhitespace); _rawXmlFile = _projectItem.GetXmlContent(LoadOptions.None); } catch { var placeholder = @"<?xml version=""1.0"" encoding=""utf-8""?><Include />"; _xmlFile = XDocument.Parse(placeholder); _rawXmlFile = XDocument.Parse(placeholder); } var root = _xmlFile.Root; _root = root ?? throw new InvalidDataException("Invalid source file: " + projectItem.TryGetFileName()); WixNames = new WixNames(root.GetDefaultNamespace().NamespaceName); _defines = root.Nodes().OfType<XProcessingInstruction>() .Where(p => p.Target.Equals(WixNames.Define, StringComparison.Ordinal)) .Select(p => new WixDefine(this, p)) .ToList(); _componentGroupNodes = root.Descendants(WixNames.ComponentGroupNode) .Select(node => new WixComponentGroupNode(this, node)) .ToList(); _componentNodes = root.Descendants(WixNames.ComponentNode) .Select(node => new WixComponentNode(this, node)) .ToList(); _fileNodes = new List<WixFileNode>(); _fileNodes.AddRange(root .Descendants(WixNames.FileNode) .Select(node => new WixFileNode(this, node, _fileNodes))); _directoryNodes = root .Descendants(WixNames.DirectoryNode) .Select(node => new WixDirectoryNode(this, node)) .Where(node => node.Id != "TARGETDIR") .ToList(); _featureNodes = root .Descendants(WixNames.FeatureNode) .Select(node => new WixFeatureNode(this, node)) .ToList(); var featureNodesLookup = _featureNodes.ToDictionary(item => item.Id); foreach (var featureNode in _featureNodes) { featureNode.BuildTree(featureNodesLookup); } } public WixNames WixNames { get; } public IEnumerable<WixFileNode> FileNodes => new ReadOnlyCollection<WixFileNode>(_fileNodes); public IEnumerable<WixDirectoryNode> DirectoryNodes => new ReadOnlyCollection<WixDirectoryNode>(_directoryNodes); public IEnumerable<WixComponentGroupNode> ComponentGroupNodes => new ReadOnlyCollection<WixComponentGroupNode>(_componentGroupNodes); public IEnumerable<WixFeatureNode> FeatureNodes => new ReadOnlyCollection<WixFeatureNode>(_featureNodes); public IEnumerable<WixComponentNode> ComponentNodes => new ReadOnlyCollection<WixComponentNode>(_componentNodes); public WixProject Project { get; } public bool HasChanges { get { try { var xmlFile = _projectItem.GetXmlContent(LoadOptions.None); return xmlFile.ToString(SaveOptions.DisableFormatting) != _rawXmlFile.ToString(SaveOptions.DisableFormatting); } catch (XmlException) { return true; } } } internal WixDirectoryNode AddDirectory(string id, string name, string parentId) { var root = _root; var fragmentElement = new XElement(WixNames.FragmentNode); root.AddWithFormatting(fragmentElement); var directoryRefElement = new XElement(WixNames.DirectoryRefNode, new XAttribute("Id", parentId)); fragmentElement.AddWithFormatting(directoryRefElement); var directoryElement = new XElement(WixNames.DirectoryNode, new XAttribute("Id", id), new XAttribute("Name", name)); directoryRefElement.AddWithFormatting(directoryElement); Save(); return AddDirectoryNode(directoryElement); } public WixDirectoryNode AddDirectoryNode(XElement directoryElement) { var directoryNode = new WixDirectoryNode(this, directoryElement); _directoryNodes.Add(directoryNode); return directoryNode; } internal WixComponentGroupNode AddComponentGroup(string directoryId) { var root = _root; var fragmentElement = new XElement(WixNames.FragmentNode); root.AddWithFormatting(fragmentElement); var componentGroupElement = new XElement(WixNames.ComponentGroupNode, new XAttribute("Id", directoryId + "_files"), new XAttribute("Directory", directoryId)); fragmentElement.AddWithFormatting(componentGroupElement); Save(); var componentGroup = new WixComponentGroupNode(this, componentGroupElement); _componentGroupNodes.Add(componentGroup); return componentGroup; } internal WixFileNode AddFileComponent(WixComponentGroupNode componentGroup, string id, string name, FileMapping fileMapping) { Debug.Assert(componentGroup.SourceFile.Equals(this)); var project = fileMapping.TopLevelProject; var variableName = string.Format(CultureInfo.InvariantCulture, "{0}_TargetDir", project.Name); ForceDirectoryVariable(variableName, project); var componentElement = new XElement(WixNames.ComponentNode, new XAttribute("Id", id), new XAttribute("Guid", Guid.NewGuid().ToString())); componentGroup.Node.AddWithFormatting(componentElement); var source = string.Format(CultureInfo.InvariantCulture, "$(var.{0}){1}", variableName, fileMapping.SourceName); var fileElement = new XElement(WixNames.FileNode, new XAttribute("Id", id), new XAttribute("Name", name), new XAttribute("Source", source)); componentElement.AddWithFormatting(fileElement); Save(); var fileNode = new WixFileNode(componentGroup.SourceFile, fileElement, _fileNodes); _fileNodes.Add(fileNode); return fileNode; } internal void Save() { _projectItem.SetContent(_xmlFile.Declaration + _xmlFile.ToString(SaveOptions.DisableFormatting)); _rawXmlFile = _projectItem.GetXmlContent(LoadOptions.None); } private void ForceDirectoryVariable(string variableName, Project project) { if (_defines.Any(d => d.Name.Equals(variableName, StringComparison.Ordinal))) return; var data = string.Format(CultureInfo.InvariantCulture, "{0}=$(var.{1}.TargetDir)", variableName, project.Name); var processingInstruction = new XProcessingInstruction(WixNames.Define, data); var lastNode = _defines.LastOrDefault(); if (lastNode != null) { lastNode.Node.AddAfterSelf(processingInstruction); } else { var firstNode = _root.FirstNode; if (firstNode != null) { firstNode.AddBeforeSelf(processingInstruction); } else { _root.Add(processingInstruction); } } _defines.Add(new WixDefine(this, processingInstruction)); } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Backoffice_Informasi_RADList : System.Web.UI.Page { public int NoKe = 0; protected string dsReportSessionName = "dsListRegistrasiRAD"; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (Session["InformasiPasienRAD"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx"); } btnSearch.Text = Resources.GetString("", "Search"); ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif"; ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif"; ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif"; ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif"; txtTanggalRegistrasi.Text = DateTime.Now.ToString("dd/MM/yyyy"); UpdateDataView(true); } } #region .Update View Data ////////////////////////////////////////////////////////////////////// // PhysicalDataRead // ------------------------------------------------------------------ /// <summary> /// This function is responsible for loading data from database. /// </summary> /// <returns>DataSet</returns> public DataSet PhysicalDataRead() { // Local variables DataSet oDS = new DataSet(); // Get Data DataTable myData = new DataTable(); SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); if (txtTanggalRegistrasi.Text != "") { myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); } myObj.PoliklinikId = 41 ;//RAD myData = myObj.SelectAllFilter(); oDS.Tables.Add(myData); return oDS; } /// <summary> /// This function is responsible for binding data to Datagrid. /// </summary> /// <param name="dv"></param> private void BindData(DataView dv) { // Sets the sorting order dv.Sort = DataGridList.Attributes["SortField"]; if (DataGridList.Attributes["SortAscending"] == "no") dv.Sort += " DESC"; if (dv.Count > 0) { DataGridList.ShowFooter = false; int intRowCount = dv.Count; int intPageSaze = DataGridList.PageSize; int intPageCount = intRowCount / intPageSaze; if (intRowCount - (intPageCount * intPageSaze) > 0) intPageCount = intPageCount + 1; if (DataGridList.CurrentPageIndex >= intPageCount) DataGridList.CurrentPageIndex = intPageCount - 1; } else { DataGridList.ShowFooter = true; DataGridList.CurrentPageIndex = 0; } // Re-binds the grid NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex; DataGridList.DataSource = dv; DataGridList.DataBind(); int CurrentPage = DataGridList.CurrentPageIndex + 1; lblCurrentPage.Text = CurrentPage.ToString(); lblTotalPage.Text = DataGridList.PageCount.ToString(); lblTotalRecord.Text = dv.Count.ToString(); } /// <summary> /// This function is responsible for loading data from database and store to Session. /// </summary> /// <param name="strDataSessionName"></param> public void DataFromSourceToMemory(String strDataSessionName) { // Gets rows from the data source DataSet oDS = PhysicalDataRead(); // Stores it in the session cache Session[strDataSessionName] = oDS; } /// <summary> /// This function is responsible for update data view from datagrid. /// </summary> /// <param name="requery">true = get data from database, false= get data from session</param> public void UpdateDataView(bool requery) { // Retrieves the data if ((Session[dsReportSessionName] == null) || (requery)) { if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString()); DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; BindData(ds.Tables[0].DefaultView); } public void UpdateDataView() { // Retrieves the data if ((Session[dsReportSessionName] == null)) { DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; BindData(ds.Tables[0].DefaultView); } #endregion #region .Event DataGridList ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // HANDLERs // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a new page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PageChanged(Object sender, DataGridPageChangedEventArgs e) { DataGridList.CurrentPageIndex = e.NewPageIndex; DataGridList.SelectedIndex = -1; UpdateDataView(); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a new page. /// </summary> /// <param name="sender"></param> /// <param name="nPageIndex"></param> public void GoToPage(Object sender, int nPageIndex) { DataGridPageChangedEventArgs evPage; evPage = new DataGridPageChangedEventArgs(sender, nPageIndex); PageChanged(sender, evPage); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a first page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToFirst(Object sender, ImageClickEventArgs e) { GoToPage(sender, 0); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a previous page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToPrev(Object sender, ImageClickEventArgs e) { if (DataGridList.CurrentPageIndex > 0) { GoToPage(sender, DataGridList.CurrentPageIndex - 1); } else { GoToPage(sender, 0); } } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a next page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e) { if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1)) { GoToPage(sender, DataGridList.CurrentPageIndex + 1); } } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a last page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToLast(Object sender, ImageClickEventArgs e) { GoToPage(sender, DataGridList.PageCount - 1); } /// <summary> /// This function is invoked when you click on a column's header to /// sort by that. It just saves the current sort field name and /// refreshes the grid. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void SortByColumn(Object sender, DataGridSortCommandEventArgs e) { String strSortBy = DataGridList.Attributes["SortField"]; String strSortAscending = DataGridList.Attributes["SortAscending"]; // Sets the new sorting field DataGridList.Attributes["SortField"] = e.SortExpression; // Sets the order (defaults to ascending). If you click on the // sorted column, the order reverts. DataGridList.Attributes["SortAscending"] = "yes"; if (e.SortExpression == strSortBy) DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes"); // Refreshes the view OnClearSelection(null, null); UpdateDataView(); } /// <summary> /// The function gets invoked when a new item is being created in /// the datagrid. This applies to pager, header, footer, regular /// and alternating items. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PageItemCreated(Object sender, DataGridItemEventArgs e) { // Get the newly created item ListItemType itemType = e.Item.ItemType; ////////////////////////////////////////////////////////// // Is it the HEADER? if (itemType == ListItemType.Header) { for (int i = 0; i < DataGridList.Columns.Count; i++) { // draw to reflect sorting if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression) { ////////////////////////////////////////////// // Should be much easier this way: // ------------------------------------------ // TableCell cell = e.Item.Cells[i]; // Label lblSorted = new Label(); // lblSorted.Font = "webdings"; // lblSorted.Text = strOrder; // cell.Controls.Add(lblSorted); // // but it seems it doesn't work <g> ////////////////////////////////////////////// // Add a non-clickable triangle to mean desc or asc. // The </a> ensures that what follows is non-clickable TableCell cell = e.Item.Cells[i]; LinkButton lb = (LinkButton)cell.Controls[0]; //lb.Text += "</a>&nbsp;<span style=font-family:webdings;>" + GetOrderSymbol() + "</span>"; lb.Text += "</a>&nbsp;<img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >"; } } } ////////////////////////////////////////////////////////// // Is it the PAGER? if (itemType == ListItemType.Pager) { // There's just one control in the list... TableCell pager = (TableCell)e.Item.Controls[0]; // Enumerates all the items in the pager... for (int i = 0; i < pager.Controls.Count; i += 2) { // It can be either a Label or a Link button try { Label l = (Label)pager.Controls[i]; l.Text = "Hal " + l.Text; l.CssClass = "CurrentPage"; } catch { LinkButton h = (LinkButton)pager.Controls[i]; h.Text = "[ " + h.Text + " ]"; h.CssClass = "HotLink"; } } } } /// <summary> /// Verifies whether the current sort is ascending or descending and /// returns an appropriate display text (i.e., a webding) /// </summary> /// <returns></returns> private String GetOrderSymbol() { bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no"); //return (bDescending ? " 6" : " 5"); return (bDescending ? "downbr.gif" : "upbr.gif"); } /// <summary> /// When clicked clears the current selection if any /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnClearSelection(Object sender, EventArgs e) { DataGridList.SelectedIndex = -1; } #endregion #region .Event Button /// <summary> /// When clicked, redirect to form add for inserts a new record to the database /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnNewRecord(Object sender, EventArgs e) { string CurrentPage = DataGridList.CurrentPageIndex.ToString(); Response.Redirect("RADAddBaru.aspx?CurrentPage=" + CurrentPage); } public void OnAddRJ(Object sender, EventArgs e) { string CurrentPage = DataGridList.CurrentPageIndex.ToString(); Response.Redirect("RADAddRJ.aspx?CurrentPage=" + CurrentPage); } public void OnAddRI(Object sender, EventArgs e) { string CurrentPage = DataGridList.CurrentPageIndex.ToString(); Response.Redirect("RADAddRI.aspx?CurrentPage=" + CurrentPage); } /// <summary> /// When clicked, filter data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnSearch(Object sender, System.EventArgs e) { if ((Session[dsReportSessionName] == null)) { DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; DataView dv = ds.Tables[0].DefaultView; if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Nama") dv.RowFilter = " Nama LIKE '%" + txtSearch.Text + "%'"; else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NoRegistrasi") dv.RowFilter = " NoRegistrasi LIKE '%" + txtSearch.Text + "%'"; else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NoRM") dv.RowFilter = " NoRM LIKE '%" + txtSearch.Text + "%'"; else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NRP") dv.RowFilter = " NRP LIKE '%" + txtSearch.Text + "%'"; else dv.RowFilter = ""; BindData(dv); } #endregion #region .Update Link Item Butom /// <summary> /// The function is responsible for get link button form. /// </summary> /// <param name="szId"></param> /// <param name="CurrentPage"></param> /// <returns></returns> public string GetLinkButton(string RawatJalanId, string StatusRawatJalan, string Nama, string CurrentPage) { string szResult = ""; if (Session["InformasiPasienRAD"] != null) { szResult += "<a class=\"toolbar\" href=\"RADView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + RawatJalanId + "\" "; szResult += ">Detil</a>"; } return szResult; } #endregion protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e) { UpdateDataView(true); } protected void DataGridList_DeleteCommand(object source, DataGridCommandEventArgs e) { string RawatJalanId = DataGridList.DataKeys[e.Item.ItemIndex].ToString(); SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.RawatJalanId = int.Parse(RawatJalanId); myObj.Delete(); DataGridList.SelectedIndex = -1; UpdateDataView(true); } }
// Copyright 2019 DeepMind Technologies Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; namespace Mujoco { [TestFixture] public class MjDefaultSelectorsEditorTests { private XmlElement SetUp(string mjcfString, string selector) { var mjcf = new XmlDocument(); mjcf.LoadXml(mjcfString); return mjcf.SelectSingleNode(selector) as XmlElement; } [TestCase("class")] [TestCase("childclass")] public void SelectingTopLevelClassDefault(string qualifier) { var mjcfString = @"<mujoco> <worldbody> <modified QUALIFIER=""class""/> </worldbody> </mujoco>".Replace("QUALIFIER", qualifier); var modifiedNode = SetUp(mjcfString, "/mujoco/worldbody/modified"); var classes = MjXmlModifiers.GetApplicableDefaultClasses(modifiedNode).ToArray(); Assert.That(classes.Length, Is.EqualTo(1)); Assert.That( classes[0], Is.EqualTo("class")); } [TestCase("class")] [TestCase("childclass")] public void SelectingNestedClassDefaultWithInheritance(string qualifier) { var mjcfString = @"<mujoco> <worldbody> <some_node childclass=""parent""> <modified QUALIFIER=""child""/> </some_node> </worldbody> </mujoco>".Replace("QUALIFIER", qualifier); var modifiedNode = SetUp(mjcfString, "/mujoco/worldbody/some_node/modified"); var classes = MjXmlModifiers.GetApplicableDefaultClasses(modifiedNode).ToArray(); Assert.That(classes.Length, Is.EqualTo(2)); Assert.That(classes[0], Is.EqualTo("child")); Assert.That( classes[1], Is.EqualTo("parent")); } [TestCase("class")] [TestCase("childclass")] public void SelectingNestedClassDefaultWithoutInheritance(string qualifier) { var mjcfString = @"<mujoco> <worldbody> <some_node class=""parent""> <modified QUALIFIER=""child""/> </some_node> </worldbody> </mujoco>".Replace("QUALIFIER", qualifier); var modifiedNode = SetUp(mjcfString, "/mujoco/worldbody/some_node/modified"); var classes = MjXmlModifiers.GetApplicableDefaultClasses(modifiedNode).ToArray(); Assert.That(classes.Length, Is.EqualTo(1)); Assert.That(classes[0], Is.EqualTo("child")); } } [TestFixture] public class MjAttributeCopierEditorTests { [Test] public void CopyingXmlElementAttributes() { var mjcfString = @"<root> <tag_1 attr_1=""a"" attr_2=""b""/> <tag_2/> </root>"; var mjcf = new XmlDocument(); mjcf.LoadXml(mjcfString); var tags = new XmlElement[] { mjcf.SelectSingleNode("/root/tag_1") as XmlElement, mjcf.SelectSingleNode("/root/tag_2") as XmlElement }; MjXmlModifiers.CopyAttributes(tags[0], tags[1]); // Reselect the element to make sure we're testing the actual part of the DOM, and not its copy. var testedElement = mjcf.SelectSingleNode("/root/tag_2") as XmlElement; Assert.That(testedElement.GetStringAttribute("attr_1", "unknown"), Is.EqualTo("a")); Assert.That(testedElement.GetStringAttribute("attr_2", "unknown"), Is.EqualTo("b")); } [Test] public void CopyingXmlElementAttributesWithoutOverwritingTheExistingOnes() { var mjcfString = @"<root> <tag_1 attr_1=""a"" attr_2=""b""/> <tag_2 attr_1=""c""/> </root>"; var mjcf = new XmlDocument(); mjcf.LoadXml(mjcfString); var tags = new XmlElement[] { mjcf.SelectSingleNode("/root/tag_1") as XmlElement, mjcf.SelectSingleNode("/root/tag_2") as XmlElement }; MjXmlModifiers.CopyAttributes(tags[0], tags[1]); // Reselect the element to make sure we're testing the actual part of the DOM, and not its copy. var testedElement = mjcf.SelectSingleNode("/root/tag_2") as XmlElement; Assert.That(testedElement.GetStringAttribute("attr_1", "unknown"), Is.EqualTo("c")); Assert.That(testedElement.GetStringAttribute("attr_2", "unknown"), Is.EqualTo("b")); } [Test] public void CopyingXmlElementAttributesWithOverwritingTheExistingOnes() { var mjcfString = @"<root> <tag_1 attr_1=""a"" attr_2=""b""/> <tag_2 attr_1=""c""/> </root>"; var mjcf = new XmlDocument(); mjcf.LoadXml(mjcfString); var tags = new XmlElement[] { mjcf.SelectSingleNode("/root/tag_1") as XmlElement, mjcf.SelectSingleNode("/root/tag_2") as XmlElement }; MjXmlModifiers.CopyAttributesOverwriteExisting(tags[0], tags[1]); // Reselect the element to make sure we're testing the actual part of the DOM, and not its copy. var testedElement = mjcf.SelectSingleNode("/root/tag_2") as XmlElement; Assert.That(testedElement.GetStringAttribute("attr_1", "unknown"), Is.EqualTo("a")); Assert.That(testedElement.GetStringAttribute("attr_2", "unknown"), Is.EqualTo("b")); } } [TestFixture] public class MjXmlModifiersIntegrationEditorTests { [Test] public void ApplyingDefaultsAggregatesAttributesFromMultipleDefaults() { var mjcfString = @"<mujoco> <default> <modified attrib=""a""/> <default class=""class""> <modified attrib=""b""/> </default> </default> <worldbody> <modified class=""class""/> </worldbody> </mujoco>"; var mjcf = new XmlDocument(); mjcf.LoadXml(mjcfString); var modifiedElement = mjcf.SelectSingleNode("/mujoco/worldbody/modified") as XmlElement; var modifiers = new MjXmlModifiers(mjcf); modifiers.ApplyModifiersToElement(modifiedElement); modifiedElement = mjcf.SelectSingleNode("/mujoco/worldbody/modified") as XmlElement; Assert.That(modifiedElement.GetStringAttribute("attrib", string.Empty), Is.EqualTo("b")); } [Test] public void ApplyingDefaultsDoesntOverwriteTheExistingNodeAttribute() { var mjcfString = @"<mujoco> <default> <modified attrib=""b""/> </default> <worldbody> <modified attrib=""a""/> </worldbody> </mujoco>"; var mjcf = new XmlDocument(); mjcf.LoadXml(mjcfString); var modifiedElement = mjcf.SelectSingleNode("/mujoco/worldbody/modified") as XmlElement; var modifiers = new MjXmlModifiers(mjcf); modifiers.ApplyModifiersToElement(modifiedElement); modifiedElement = mjcf.SelectSingleNode("/mujoco/worldbody/modified") as XmlElement; Assert.That(modifiedElement.GetStringAttribute("attrib", string.Empty), Is.EqualTo("a")); } [Test] public void MissingDefaultDoesntBreakInheritanceHierarchy() { var mjcfString = @"<mujoco> <default> <default class=""a""> <default class=""b""> <geom type=""sphere""/> </default> </default> </default> <worldbody> <body childclass=""a""> <body childclass=""b""> <geom name=""thingy""/> </body> </body> </worldbody> </mujoco>"; var mjcf = new XmlDocument(); mjcf.LoadXml(mjcfString); var modifiedElement = mjcf.SelectSingleNode("descendant::body/geom") as XmlElement; var modifiers = new MjXmlModifiers(mjcf); modifiers.ApplyModifiersToElement(modifiedElement); Assert.That(modifiedElement.GetStringAttribute("name", string.Empty), Is.EqualTo("thingy")); Assert.That(modifiedElement.GetStringAttribute("type", string.Empty), Is.EqualTo("sphere")); } [Test] public void PropagatePropertiesAcrossDefaultHierarchy() { var mjcfString = @"<mujoco> <default> <default class=""a""> <geom attrib1=""from_a""/> <default class=""b""> <geom attrib2=""from_b""/> </default> </default> </default> <worldbody> <body> <body> <body> <geom class=""b"" name=""thingy""/> </body> </body> </body> </worldbody> </mujoco>"; var mjcf = new XmlDocument(); mjcf.LoadXml(mjcfString); var modifiedElement = mjcf.SelectSingleNode("descendant::body/geom") as XmlElement; var modifiers = new MjXmlModifiers(mjcf); modifiers.ApplyModifiersToElement(modifiedElement); Assert.That(modifiedElement.GetStringAttribute("name", string.Empty), Is.EqualTo("thingy")); Assert.That(modifiedElement.GetStringAttribute("attrib1", string.Empty), Is.EqualTo("from_a")); Assert.That(modifiedElement.GetStringAttribute("attrib2", string.Empty), Is.EqualTo("from_b")); } } }
using System.Collections.Generic; using System.Text.RegularExpressions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Tynamix.ObjectFiller.Test.TestPoco.Person; namespace Tynamix.ObjectFiller.Test { [TestClass] public class PatternGeneratorTest { [TestMethod] public void Must_be_able_to_handle_private_setters() { var filler = new Filler<ClassWithPrivateStuffSealed>(); filler.Setup() .OnProperty(x => x.NameStyle).DoIt(At.TheEnd).Use(() => NameStyle.FirstNameLastName) .OnProperty(x => x.WithPrivateSetter); var obj = filler.Create(); Assert.AreNotEqual(0, obj.WithPrivateSetter); Assert.AreEqual(123, obj.WithoutSetter); Assert.AreEqual(obj.NameStyle, NameStyle.FirstNameLastName); } [TestMethod] public void Must_be_able_to_handle_inheritance_and_sealed() { var filler = new Filler<InheritedClass>(); var obj = filler.Create(); Assert.AreNotEqual(0, obj.NormalNumber); Assert.AreNotEqual(0, obj.OverrideNormalNumber); Assert.AreNotEqual(0, obj.SealedOverrideNormalNumber); } [TestMethod] public void Must_be_able_to_handle_arrays() { var filler = new Filler<WithArrays>(); //.For<int[]>(); var obj = filler.Create(); Assert.IsNotNull(obj.Ints); Assert.IsNotNull(obj.Strings); Assert.IsNotNull(obj.JaggedStrings); Assert.IsNotNull(obj.ThreeJaggedDimensional); Assert.IsNotNull(obj.ThreeJaggedPoco); } [TestMethod] public void StringPatternGenerator_A() { HashSet<char> chars = new HashSet<char>(); var sut = new PatternGenerator("{A}"); for (int n = 0; n < 10000; n++) { var s = sut.GetValue(); Assert.IsTrue(Regex.IsMatch(s, "^[A-Z]$")); chars.Add(s[0]); } Assert.AreEqual(26, chars.Count); } [TestMethod] public void StringPatternGenerator_A_fixed_len() { var sut = new PatternGenerator("x{A:3}x"); for (int n = 0; n < 10000; n++) { var s = sut.GetValue(); Assert.IsTrue(Regex.IsMatch(s, "^x[A-Z]{3}x$")); } } [TestMethod] public void StringPatternGenerator_A_random_len() { var sut = new PatternGenerator("x{A:3-6}x"); for (int n = 0; n < 10000; n++) { var s = sut.GetValue(); Assert.IsTrue(Regex.IsMatch(s, "^x[A-Z]{3,6}x$")); } } [TestMethod] public void StringPatternGenerator_a() { HashSet<char> chars = new HashSet<char>(); var sut = new PatternGenerator("{a}"); for (int n = 0; n < 10000; n++) { var s = sut.GetValue(); Assert.IsTrue(s.Length == 1); Assert.IsTrue(Regex.IsMatch(s, "^[a-z]$")); chars.Add(s[0]); } Assert.AreEqual(26, chars.Count); } [TestMethod] public void StringPatternGenerator_a_composite() { HashSet<char> chars = new HashSet<char>(); var sut = new PatternGenerator("a {a}"); for (int n = 0; n < 10000; n++) { var s = sut.GetValue(); Assert.IsTrue(s.Length == 3); Assert.IsTrue(Regex.IsMatch(s, "^a [a-z]$")); chars.Add(s[2]); } Assert.AreEqual(26, chars.Count); } [TestMethod] public void StringPatternGenerator_aaa() { var sut = new PatternGenerator("xcccx"); for (int n = 0; n < 10000; n++) { var s = sut.GetValue(); Assert.IsTrue(s.Length == 5); Assert.IsTrue(Regex.IsMatch(s, "^x[a-z]{3}x$")); } } [TestMethod] public void StringPatternGenerator_N() { HashSet<char> chars = new HashSet<char>(); var sut = new PatternGenerator("{N}"); for (int n = 0; n < 10000; n++) { var s = sut.GetValue(); Assert.IsTrue(s.Length == 1); Assert.IsTrue(Regex.IsMatch(s, "^[0-9]$")); chars.Add(s[0]); } Assert.AreEqual(10, chars.Count); } [TestMethod] public void StringPatternGenerator_X() { HashSet<char> chars = new HashSet<char>(); var sut = new PatternGenerator("{X}"); for (int n = 0; n < 10000; n++) { var s = sut.GetValue(); Assert.IsTrue(s.Length == 1); Assert.IsTrue(Regex.IsMatch(s, "^[0-9A-F]$")); chars.Add(s[0]); } Assert.AreEqual(16, chars.Count); } [TestMethod] public void StringPatternGenerator_C_simple() { var sut = new PatternGenerator("{C}"); Assert.AreEqual("1", sut.GetValue()); Assert.AreEqual("2", sut.GetValue()); Assert.AreEqual("3", sut.GetValue()); } [TestMethod] public void StringPatternGenerator_C_with_StartValue() { var sut = new PatternGenerator("{C:33}"); Assert.AreEqual("33", sut.GetValue()); Assert.AreEqual("34", sut.GetValue()); Assert.AreEqual("35", sut.GetValue()); } [TestMethod] public void StringPatternGenerator_C_with_StartValue_with_Increment() { var sut = new PatternGenerator("{C:33,3}"); Assert.AreEqual("33", sut.GetValue()); Assert.AreEqual("36", sut.GetValue()); Assert.AreEqual("39", sut.GetValue()); } [TestMethod] public void StringPatternGenerator_C_combination() { var sut = new PatternGenerator("_{C}_{C:+11}_{C:110,10}_"); Assert.AreEqual("_1_11_110_", sut.GetValue()); Assert.AreEqual("_2_12_120_", sut.GetValue()); Assert.AreEqual("_3_13_130_", sut.GetValue()); Assert.AreEqual("_4_14_140_", sut.GetValue()); } [TestMethod] public void StringPatternGenerator_C_startvalue_negative_value() { var sut = new PatternGenerator("{C:-3}"); Assert.AreEqual("-3", sut.GetValue()); Assert.AreEqual("-2", sut.GetValue()); Assert.AreEqual("-1", sut.GetValue()); Assert.AreEqual("0", sut.GetValue()); Assert.AreEqual("1", sut.GetValue()); Assert.AreEqual("2", sut.GetValue()); Assert.AreEqual("3", sut.GetValue()); } [TestMethod] public void StringPatternGenerator_C__startvalue_negative__positive_increment() { var sut = new PatternGenerator("{C:-3,+2}"); Assert.AreEqual("-3", sut.GetValue()); Assert.AreEqual("-1", sut.GetValue()); Assert.AreEqual("1", sut.GetValue()); Assert.AreEqual("3", sut.GetValue()); } [TestMethod] public void StringPatternGenerator_C__startvalue_negative__negative_increment() { var sut = new PatternGenerator("{C:-3,-2}"); Assert.AreEqual("-3", sut.GetValue()); Assert.AreEqual("-5", sut.GetValue()); Assert.AreEqual("-7", sut.GetValue()); } } public class ClassWithPrivateStuffAbstract { public int WithPrivateSetter { get; private set; } public int WithoutSetter { get { return 123; } } public NameStyle NameStyle { get; private set; } } public class ClassWithPrivateStuff : ClassWithPrivateStuffAbstract { public string Name { get; set; } } public sealed class ClassWithPrivateStuffSealed : ClassWithPrivateStuff { public int Number { get; set; } } public class BaseClass { public int NormalNumber { get; set; } public virtual int OverrideNormalNumber { get; set; } public virtual int SealedOverrideNormalNumber { get; set; } } public class InheritedClass : BaseClass { public override int OverrideNormalNumber { get; set; } public override sealed int SealedOverrideNormalNumber { get; set; } } public class WithArrays { public int[] Ints { get; set; } public string[] Strings { get; set; } public string[][] JaggedStrings { get; set; } public string[][][] ThreeJaggedDimensional { get; set; } public Address[][][] ThreeJaggedPoco { get; set; } } }
/* * 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. * */ /* * This package is based on the work done by Keiron Liddle, Aftex Software * <keiron@aftexsw.com> to whom the Ant project is very grateful for his * great code. */ using System.IO; namespace Raksha.Apache.Bzip2 { /** * An input stream that decompresses from the BZip2 format (with the file * header chars) to be read as any other stream. * * @author <a href="mailto:keiron@aftexsw.com">Keiron Liddle</a> * * <b>NB:</b> note this class has been modified to read the leading BZ from the * start of the BZIP2 stream to make it compatible with other PGP programs. */ public class CBZip2InputStream : Stream { private const int START_BLOCK_STATE = 1; private const int RAND_PART_A_STATE = 2; private const int RAND_PART_B_STATE = 3; private const int RAND_PART_C_STATE = 4; private const int NO_RAND_PART_A_STATE = 5; private const int NO_RAND_PART_B_STATE = 6; private const int NO_RAND_PART_C_STATE = 7; private readonly int[][] basev = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); private readonly bool[] inUse = new bool[256]; private readonly int[][] limit = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); private readonly CRC mCrc = new CRC(); private readonly int[] minLens = new int[BZip2Constants.N_GROUPS]; private readonly int[][] perm = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); private readonly char[] selector = new char[BZip2Constants.MAX_SELECTORS]; private readonly char[] selectorMtf = new char[BZip2Constants.MAX_SELECTORS]; private readonly char[] seqToUnseq = new char[256]; private readonly char[] unseqToSeq = new char[256]; private readonly int[] unzftab = new int[256]; private bool blockRandomised; private int blockSize100k; private int bsBuff; private int bsLive; private Stream bsStream; private int ch2; private int chPrev; private int computedBlockCRC, computedCombinedCRC; private int count; private int currentChar = -1; private int currentState = START_BLOCK_STATE; private int i; private int i2; private int j2; private int last; private char[] ll8; private int nInUse; private int origPtr; private int rNToGo; private int rTPos; private int storedBlockCRC, storedCombinedCRC; private bool streamEnd; private int tPos; private int[] tt; private char z; public CBZip2InputStream(Stream zStream) { ll8 = null; tt = null; BsSetStream(zStream); Initialize(); InitBlock(); SetupBlock(); } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { } } private static void Cadvise() { //System.out.Println("CRC Error"); //throw new CCoruptionError(); } // private static void BadBGLengths() { // Cadvise(); // } // // private static void BitStreamEOF() { // Cadvise(); // } private static void CompressedStreamEOF() { Cadvise(); } private void MakeMaps() { int i; nInUse = 0; for (i = 0; i < 256; i++) { if (inUse[i]) { seqToUnseq[nInUse] = (char) i; unseqToSeq[i] = (char) nInUse; nInUse++; } } } internal static int[][] InitIntArray(int n1, int n2) { var a = new int[n1][]; for (int k = 0; k < n1; ++k) { a[k] = new int[n2]; } return a; } internal static char[][] InitCharArray(int n1, int n2) { var a = new char[n1][]; for (int k = 0; k < n1; ++k) { a[k] = new char[n2]; } return a; } public override int ReadByte() { if (streamEnd) { return -1; } int retChar = currentChar; switch (currentState) { case START_BLOCK_STATE: break; case RAND_PART_A_STATE: break; case RAND_PART_B_STATE: SetupRandPartB(); break; case RAND_PART_C_STATE: SetupRandPartC(); break; case NO_RAND_PART_A_STATE: break; case NO_RAND_PART_B_STATE: SetupNoRandPartB(); break; case NO_RAND_PART_C_STATE: SetupNoRandPartC(); break; default: break; } return retChar; } private void Initialize() { char magic3, magic4; magic3 = BsGetUChar(); magic4 = BsGetUChar(); if (magic3 != 'B' && magic4 != 'Z') { throw new IOException("Not a BZIP2 marked stream"); } magic3 = BsGetUChar(); magic4 = BsGetUChar(); if (magic3 != 'h' || magic4 < '1' || magic4 > '9') { BsFinishedWithStream(); streamEnd = true; return; } SetDecompressStructureSizes(magic4 - '0'); computedCombinedCRC = 0; } private void InitBlock() { char magic1, magic2, magic3, magic4; char magic5, magic6; magic1 = BsGetUChar(); magic2 = BsGetUChar(); magic3 = BsGetUChar(); magic4 = BsGetUChar(); magic5 = BsGetUChar(); magic6 = BsGetUChar(); if (magic1 == 0x17 && magic2 == 0x72 && magic3 == 0x45 && magic4 == 0x38 && magic5 == 0x50 && magic6 == 0x90) { Complete(); return; } if (magic1 != 0x31 || magic2 != 0x41 || magic3 != 0x59 || magic4 != 0x26 || magic5 != 0x53 || magic6 != 0x59) { BadBlockHeader(); streamEnd = true; return; } storedBlockCRC = BsGetInt32(); if (BsR(1) == 1) { blockRandomised = true; } else { blockRandomised = false; } // currBlockNo++; GetAndMoveToFrontDecode(); mCrc.InitialiseCRC(); currentState = START_BLOCK_STATE; } private void EndBlock() { computedBlockCRC = mCrc.GetFinalCRC(); /* A bad CRC is considered a fatal error. */ if (storedBlockCRC != computedBlockCRC) { CrcError(); } computedCombinedCRC = (computedCombinedCRC << 1) | (int) (((uint) computedCombinedCRC) >> 31); computedCombinedCRC ^= computedBlockCRC; } private void Complete() { storedCombinedCRC = BsGetInt32(); if (storedCombinedCRC != computedCombinedCRC) { CrcError(); } BsFinishedWithStream(); streamEnd = true; } private static void BlockOverrun() { Cadvise(); } private static void BadBlockHeader() { Cadvise(); } private static void CrcError() { Cadvise(); } private void BsFinishedWithStream() { try { if (bsStream != null) { bsStream.Dispose(); bsStream = null; } } catch { //ignore } } private void BsSetStream(Stream f) { bsStream = f; bsLive = 0; bsBuff = 0; } private int BsR(int n) { int v; while (bsLive < n) { int zzi; char thech = '\0'; try { thech = (char) bsStream.ReadByte(); } catch (IOException) { CompressedStreamEOF(); } if (thech == '\uffff') { CompressedStreamEOF(); } zzi = thech; bsBuff = (bsBuff << 8) | (zzi & 0xff); bsLive += 8; } v = (bsBuff >> (bsLive - n)) & ((1 << n) - 1); bsLive -= n; return v; } private char BsGetUChar() { return (char) BsR(8); } private int BsGetint() { int u = 0; u = (u << 8) | BsR(8); u = (u << 8) | BsR(8); u = (u << 8) | BsR(8); u = (u << 8) | BsR(8); return u; } private int BsGetIntVS(int numBits) { return BsR(numBits); } private int BsGetInt32() { return BsGetint(); } private void HbCreateDecodeTables(int[] limit, int[] basev, int[] perm, char[] length, int minLen, int maxLen, int alphaSize) { int pp, i, j, vec; pp = 0; for (i = minLen; i <= maxLen; i++) { for (j = 0; j < alphaSize; j++) { if (length[j] == i) { perm[pp] = j; pp++; } } } for (i = 0; i < BZip2Constants.MAX_CODE_LEN; i++) { basev[i] = 0; } for (i = 0; i < alphaSize; i++) { basev[length[i] + 1]++; } for (i = 1; i < BZip2Constants.MAX_CODE_LEN; i++) { basev[i] += basev[i - 1]; } for (i = 0; i < BZip2Constants.MAX_CODE_LEN; i++) { limit[i] = 0; } vec = 0; for (i = minLen; i <= maxLen; i++) { vec += (basev[i + 1] - basev[i]); limit[i] = vec - 1; vec <<= 1; } for (i = minLen + 1; i <= maxLen; i++) { basev[i] = ((limit[i - 1] + 1) << 1) - basev[i]; } } private void RecvDecodingTables() { char[][] len = InitCharArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); int i, j, t, nGroups, nSelectors, alphaSize; int minLen, maxLen; var inUse16 = new bool[16]; /* Receive the mapping table */ for (i = 0; i < 16; i++) { if (BsR(1) == 1) { inUse16[i] = true; } else { inUse16[i] = false; } } for (i = 0; i < 256; i++) { inUse[i] = false; } for (i = 0; i < 16; i++) { if (inUse16[i]) { for (j = 0; j < 16; j++) { if (BsR(1) == 1) { inUse[i*16 + j] = true; } } } } MakeMaps(); alphaSize = nInUse + 2; /* Now the selectors */ nGroups = BsR(3); nSelectors = BsR(15); for (i = 0; i < nSelectors; i++) { j = 0; while (BsR(1) == 1) { j++; } selectorMtf[i] = (char) j; } /* Undo the MTF values for the selectors. */ { var pos = new char[BZip2Constants.N_GROUPS]; char tmp, v; for (v = '\0'; v < nGroups; v++) { pos[v] = v; } for (i = 0; i < nSelectors; i++) { v = selectorMtf[i]; tmp = pos[v]; while (v > 0) { pos[v] = pos[v - 1]; v--; } pos[0] = tmp; selector[i] = tmp; } } /* Now the coding tables */ for (t = 0; t < nGroups; t++) { int curr = BsR(5); for (i = 0; i < alphaSize; i++) { while (BsR(1) == 1) { if (BsR(1) == 0) { curr++; } else { curr--; } } len[t][i] = (char) curr; } } /* Create the Huffman decoding tables */ for (t = 0; t < nGroups; t++) { minLen = 32; maxLen = 0; for (i = 0; i < alphaSize; i++) { if (len[t][i] > maxLen) { maxLen = len[t][i]; } if (len[t][i] < minLen) { minLen = len[t][i]; } } HbCreateDecodeTables(limit[t], basev[t], perm[t], len[t], minLen, maxLen, alphaSize); minLens[t] = minLen; } } private void GetAndMoveToFrontDecode() { var yy = new char[256]; int i, j, nextSym, limitLast; int EOB, groupNo, groupPos; limitLast = BZip2Constants.baseBlockSize*blockSize100k; origPtr = BsGetIntVS(24); RecvDecodingTables(); EOB = nInUse + 1; groupNo = -1; groupPos = 0; /* Setting up the unzftab entries here is not strictly necessary, but it does save having to do it later in a separate pass, and so saves a block's worth of cache misses. */ for (i = 0; i <= 255; i++) { unzftab[i] = 0; } for (i = 0; i <= 255; i++) { yy[i] = (char) i; } last = -1; { int zt, zn, zvec, zj; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.G_SIZE; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; { { while (bsLive < 1) { int zzi; char thech = '\0'; try { thech = (char) bsStream.ReadByte(); } catch (IOException) { CompressedStreamEOF(); } if (thech == '\uffff') { CompressedStreamEOF(); } zzi = thech; bsBuff = (bsBuff << 8) | (zzi & 0xff); bsLive += 8; } } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; } zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - basev[zt][zn]]; } while (true) { if (nextSym == EOB) { break; } if (nextSym == BZip2Constants.RUNA || nextSym == BZip2Constants.RUNB) { char ch; int s = -1; int N = 1; do { if (nextSym == BZip2Constants.RUNA) { s = s + (0 + 1)*N; } else if (nextSym == BZip2Constants.RUNB) { s = s + (1 + 1)*N; } N = N*2; { int zt, zn, zvec, zj; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.G_SIZE; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; { { while (bsLive < 1) { int zzi; char thech = '\0'; try { thech = (char) bsStream.ReadByte(); } catch (IOException) { CompressedStreamEOF(); } if (thech == '\uffff') { CompressedStreamEOF(); } zzi = thech; bsBuff = (bsBuff << 8) | (zzi & 0xff); bsLive += 8; } } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; } zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - basev[zt][zn]]; } } while (nextSym == BZip2Constants.RUNA || nextSym == BZip2Constants.RUNB); s++; ch = seqToUnseq[yy[0]]; unzftab[ch] += s; while (s > 0) { last++; ll8[last] = ch; s--; } if (last >= limitLast) { BlockOverrun(); } } char tmp; last++; if (last >= limitLast) { BlockOverrun(); } tmp = yy[nextSym - 1]; unzftab[seqToUnseq[tmp]]++; ll8[last] = seqToUnseq[tmp]; /* This loop is hammered during decompression, hence the unrolling. for (j = nextSym-1; j > 0; j--) yy[j] = yy[j-1]; */ j = nextSym - 1; for (; j > 3; j -= 4) { yy[j] = yy[j - 1]; yy[j - 1] = yy[j - 2]; yy[j - 2] = yy[j - 3]; yy[j - 3] = yy[j - 4]; } for (; j > 0; j--) { yy[j] = yy[j - 1]; } yy[0] = tmp; { int zt, zn, zvec, zj; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.G_SIZE; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; { { while (bsLive < 1) { int zzi; char thech = '\0'; try { thech = (char) bsStream.ReadByte(); } catch (IOException) { CompressedStreamEOF(); } zzi = thech; bsBuff = (bsBuff << 8) | (zzi & 0xff); bsLive += 8; } } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; } zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - basev[zt][zn]]; } } } private void SetupBlock() { var cftab = new int[257]; char ch; cftab[0] = 0; for (i = 1; i <= 256; i++) { cftab[i] = unzftab[i - 1]; } for (i = 1; i <= 256; i++) { cftab[i] += cftab[i - 1]; } for (i = 0; i <= last; i++) { ch = ll8[i]; tt[cftab[ch]] = i; cftab[ch]++; } cftab = null; tPos = tt[origPtr]; count = 0; i2 = 0; ch2 = 256; /* not a char and not EOF */ if (blockRandomised) { rNToGo = 0; rTPos = 0; SetupRandPartA(); } else { SetupNoRandPartA(); } } private void SetupRandPartA() { if (i2 <= last) { chPrev = ch2; ch2 = ll8[tPos]; tPos = tt[tPos]; if (rNToGo == 0) { rNToGo = BZip2Constants.rNums[rTPos]; rTPos++; if (rTPos == 512) { rTPos = 0; } } rNToGo--; ch2 ^= (rNToGo == 1) ? 1 : 0; i2++; currentChar = ch2; currentState = RAND_PART_B_STATE; mCrc.UpdateCRC(ch2); } else { EndBlock(); InitBlock(); SetupBlock(); } } private void SetupNoRandPartA() { if (i2 <= last) { chPrev = ch2; ch2 = ll8[tPos]; tPos = tt[tPos]; i2++; currentChar = ch2; currentState = NO_RAND_PART_B_STATE; mCrc.UpdateCRC(ch2); } else { EndBlock(); InitBlock(); SetupBlock(); } } private void SetupRandPartB() { if (ch2 != chPrev) { currentState = RAND_PART_A_STATE; count = 1; SetupRandPartA(); } else { count++; if (count >= 4) { z = ll8[tPos]; tPos = tt[tPos]; if (rNToGo == 0) { rNToGo = BZip2Constants.rNums[rTPos]; rTPos++; if (rTPos == 512) { rTPos = 0; } } rNToGo--; z ^= (char) ((rNToGo == 1) ? 1 : 0); j2 = 0; currentState = RAND_PART_C_STATE; SetupRandPartC(); } else { currentState = RAND_PART_A_STATE; SetupRandPartA(); } } } private void SetupRandPartC() { if (j2 < z) { currentChar = ch2; mCrc.UpdateCRC(ch2); j2++; } else { currentState = RAND_PART_A_STATE; i2++; count = 0; SetupRandPartA(); } } private void SetupNoRandPartB() { if (ch2 != chPrev) { currentState = NO_RAND_PART_A_STATE; count = 1; SetupNoRandPartA(); } else { count++; if (count >= 4) { z = ll8[tPos]; tPos = tt[tPos]; currentState = NO_RAND_PART_C_STATE; j2 = 0; SetupNoRandPartC(); } else { currentState = NO_RAND_PART_A_STATE; SetupNoRandPartA(); } } } private void SetupNoRandPartC() { if (j2 < z) { currentChar = ch2; mCrc.UpdateCRC(ch2); j2++; } else { currentState = NO_RAND_PART_A_STATE; i2++; count = 0; SetupNoRandPartA(); } } private void SetDecompressStructureSizes(int newSize100k) { if (!(0 <= newSize100k && newSize100k <= 9 && 0 <= blockSize100k && blockSize100k <= 9)) { // throw new IOException("Invalid block size"); } blockSize100k = newSize100k; if (newSize100k == 0) { return; } int n = BZip2Constants.baseBlockSize*newSize100k; ll8 = new char[n]; tt = new int[n]; } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { int c = -1; int k; for (k = 0; k < count; ++k) { c = ReadByte(); if (c == -1) { break; } buffer[k + offset] = (byte) c; } return k; } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int count) { } } }
// <copyright file="LevelDictionary{TKey,TValue}.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using IX.Abstractions.Collections; using IX.StandardExtensions; using IX.StandardExtensions.ComponentModel; using JetBrains.Annotations; // ReSharper disable once CheckNamespace namespace IX.System.Collections.Generic { /// <summary> /// A dictionary that saves its objects in multiple levels. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> [PublicAPI] public class LevelDictionary<TKey, TValue> : DisposableBase, IDictionary<TKey, TValue> { private Dictionary<TKey, TValue> internalDictionary; private Dictionary<int, List<TKey>> keyLevels; private Dictionary<TKey, int> levelKeys; /// <summary> /// Initializes a new instance of the <see cref="LevelDictionary{TKey, TValue}"/> class. /// </summary> public LevelDictionary() { this.internalDictionary = new Dictionary<TKey, TValue>(); this.keyLevels = new Dictionary<int, List<TKey>>(); this.levelKeys = new Dictionary<TKey, int>(); } /// <summary> /// Gets the keys. /// </summary> /// <value>The keys.</value> public ICollection<TKey> Keys { get { this.ThrowIfCurrentObjectDisposed(); return this.internalDictionary.Keys; } } /// <summary> /// Gets the values. /// </summary> /// <value>The values.</value> public ICollection<TValue> Values { get { this.ThrowIfCurrentObjectDisposed(); return this.internalDictionary.Values; } } /// <summary> /// Gets the keys by level. /// </summary> /// <value>The keys by level.</value> public KeyValuePair<int, TKey[]>[] KeysByLevel { get { this.ThrowIfCurrentObjectDisposed(); return this.keyLevels.OrderBy(p => p.Key).Select(p => new KeyValuePair<int, TKey[]>(p.Key, p.Value.ToArray())).ToArray(); } } /// <summary> /// Gets the count. /// </summary> /// <value>The count.</value> public int Count { get { this.ThrowIfCurrentObjectDisposed(); return this.internalDictionary.Count; } } /// <summary> /// Gets a value indicating whether this instance is read only. /// </summary> /// <value><see langword="true"/> if this instance is read only; otherwise, <see langword="false"/>.</value> public bool IsReadOnly => false; /// <summary> /// Gets or sets the <typeparamref name="TValue" /> with the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns>TValue.</returns> public TValue this[TKey key] { get { this.ThrowIfCurrentObjectDisposed(); return this.internalDictionary[key]; } set { this.ThrowIfCurrentObjectDisposed(); this.internalDictionary[key] = value; } } /// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <exception cref="NotImplementedByDesignException">This method is not implemented by design. Do not call it, as it will always throw an exception.</exception> void IDictionary<TKey, TValue>.Add(TKey key, TValue value) => throw new NotImplementedByDesignException(); /// <summary> /// Adds the specified item. /// </summary> /// <param name="item">The item.</param> /// <exception cref="NotImplementedByDesignException">This method is not implemented by design. Do not call it, as it will always throw an exception.</exception> void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) => throw new NotImplementedByDesignException(); /// <summary> /// Adds the specified key and value to a level in the dictionary. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="level">The level.</param> /// <exception cref="InvalidOperationException">The key was already present in the dictionary.</exception> public void Add(TKey key, TValue value, int level) { if (level < 0) { throw new ArgumentOutOfRangeException(nameof(level)); } if (this.internalDictionary.ContainsKey(key)) { throw new InvalidOperationException(Resources.ErrorKeyFoundInDictionary); } this.internalDictionary.Add(key, value); if (this.keyLevels.TryGetValue(level, out List<TKey> list)) { list.Add(key); } else { this.keyLevels.Add(level, new List<TKey> { key }); } this.levelKeys.Add(key, level); } /// <summary> /// Clears the dictionary. /// </summary> public void Clear() { this.ThrowIfCurrentObjectDisposed(); this.internalDictionary.Clear(); this.keyLevels.Clear(); this.levelKeys.Clear(); } /// <summary> /// Determines whether the specified item is contained in the dictionary. /// </summary> /// <param name="item">The item.</param> /// <returns><see langword="true"/> if the dictionary contains the specified item; otherwise, <see langword="false"/>.</returns> bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { this.ThrowIfCurrentObjectDisposed(); return (this.internalDictionary as ICollection<KeyValuePair<TKey, TValue>>).Contains(item); } /// <summary> /// Determines whether the dictionary contains they key. /// </summary> /// <param name="key">The key.</param> /// <returns><see langword="true"/> if the dictionary contains the key; otherwise, <see langword="false"/>.</returns> public bool ContainsKey(TKey key) { this.ThrowIfCurrentObjectDisposed(); return this.internalDictionary.ContainsKey(key); } /// <summary> /// Copies the contents of the dictionary to an array. /// </summary> /// <param name="array">The array.</param> /// <param name="arrayIndex">Index of the array.</param> void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { this.ThrowIfCurrentObjectDisposed(); (this.internalDictionary as ICollection<KeyValuePair<TKey, TValue>>).CopyTo(array, arrayIndex); } /// <summary> /// Gets the enumerator. /// </summary> /// <returns>The dictionary's enumerator.</returns> public Dictionary<TKey, TValue>.Enumerator GetEnumerator() { this.ThrowIfCurrentObjectDisposed(); return this.internalDictionary.GetEnumerator(); } /// <summary> /// Gets the enumerator. /// </summary> /// <returns>The dictionary enumerator.</returns> [SuppressMessage("Performance", "HAA0601:Value type to reference type conversion causing boxing allocation", Justification = "Unavoidable here.")] IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() => this.GetEnumerator(); /// <summary> /// Removes the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns><see langword="true"/> if the key has been removed, <see langword="false"/> otherwise.</returns> public bool Remove(TKey key) { this.ThrowIfCurrentObjectDisposed(); if (!this.levelKeys.TryGetValue( key, out var level)) { return false; } if (!this.internalDictionary.Remove(key)) { return false; } this.keyLevels[level].Remove(key); this.levelKeys.Remove(key); return true; } /// <summary> /// Removes the specified item from the dictionary. /// </summary> /// <param name="item">The item.</param> /// <returns><see langword="true"/> if the removal was a success, <see langword="false"/> otherwise.</returns> bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) => this.Remove(item.Key); /// <summary> /// Tries to get a value by key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns><see langword="true"/> if the value was found, <see langword="false"/> otherwise.</returns> public bool TryGetValue(TKey key, out TValue value) { this.ThrowIfCurrentObjectDisposed(); return this.internalDictionary.TryGetValue(key, out value); } /// <summary> /// Gets the enumerator. /// </summary> /// <returns>IEnumerator.</returns> [SuppressMessage("Performance", "HAA0601:Value type to reference type conversion causing boxing allocation", Justification = "Unavoidable here.")] IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); /// <summary> /// Disposes the managed context. /// </summary> protected override void DisposeManagedContext() { this.internalDictionary.Clear(); this.keyLevels.Clear(); this.levelKeys.Clear(); base.DisposeManagedContext(); } /// <summary> /// Disposes the general context. /// </summary> protected override void DisposeGeneralContext() { base.DisposeGeneralContext(); Interlocked.Exchange(ref this.internalDictionary, null); Interlocked.Exchange(ref this.keyLevels, null); Interlocked.Exchange(ref this.levelKeys, null); } } }
//*************************************************** //* This file was generated by tool //* SharpKit //*************************************************** using System; using System.Collections.Generic; using SharpKit.JavaScript; namespace Y_ { /// <summary> /// Provides dynamic loading of remote JavaScript and CSS resources. /// </summary> public partial class Get { /// <summary> /// Triggers an automatic purge if the purge threshold has been reached. /// </summary> protected void _autoPurge(Y_.DataType_.Number threshold){} /// <summary> /// Populates the `_env` property with information about the current /// environment. /// </summary> protected object _getEnv(){return null;} /// <summary> /// Aborts the specified transaction. /// This will cause the transaction's `onFailure` callback to be called and /// will prevent any new script and link nodes from being added to the document, /// but any resources that have already been requested will continue loading /// (there's no safe way to prevent this, unfortunately). /// *Note:* This method is deprecated as of 3.5.0, and will be removed in a /// future version of YUI. Use the transaction-level `abort()` method instead. /// </summary> public void abort(Y_.Get_.Transaction transaction){} /// <summary> /// Loads one or more CSS files. /// The _urls_ parameter may be provided as a URL string, a request object, /// or an array of URL strings and/or request objects. /// A request object is just an object that contains a `url` property and zero /// or more options that should apply specifically to that request. /// Request-specific options take priority over transaction-level options and /// default options. /// URLs may be relative or absolute, and do not have to have the same origin /// as the current page. /// The `options` parameter may be omitted completely and a callback passed in /// its place, if desired. /// </summary> public Y_.Get_.Transaction css(object urls){return null;} /// <summary> /// Loads one or more CSS files. /// The _urls_ parameter may be provided as a URL string, a request object, /// or an array of URL strings and/or request objects. /// A request object is just an object that contains a `url` property and zero /// or more options that should apply specifically to that request. /// Request-specific options take priority over transaction-level options and /// default options. /// URLs may be relative or absolute, and do not have to have the same origin /// as the current page. /// The `options` parameter may be omitted completely and a callback passed in /// its place, if desired. /// </summary> public Y_.Get_.Transaction css(object urls, JsAction callback){return null;} /// <summary> /// Loads one or more CSS files. /// The _urls_ parameter may be provided as a URL string, a request object, /// or an array of URL strings and/or request objects. /// A request object is just an object that contains a `url` property and zero /// or more options that should apply specifically to that request. /// Request-specific options take priority over transaction-level options and /// default options. /// URLs may be relative or absolute, and do not have to have the same origin /// as the current page. /// The `options` parameter may be omitted completely and a callback passed in /// its place, if desired. /// </summary> public Y_.Get_.Transaction css(object urls, object options){return null;} /// <summary> /// Loads one or more CSS files. /// The _urls_ parameter may be provided as a URL string, a request object, /// or an array of URL strings and/or request objects. /// A request object is just an object that contains a `url` property and zero /// or more options that should apply specifically to that request. /// Request-specific options take priority over transaction-level options and /// default options. /// URLs may be relative or absolute, and do not have to have the same origin /// as the current page. /// The `options` parameter may be omitted completely and a callback passed in /// its place, if desired. /// </summary> public Y_.Get_.Transaction css(object urls, object options, JsAction callback){return null;} /// <summary> /// Loads one or more JavaScript resources. /// The _urls_ parameter may be provided as a URL string, a request object, /// or an array of URL strings and/or request objects. /// A request object is just an object that contains a `url` property and zero /// or more options that should apply specifically to that request. /// Request-specific options take priority over transaction-level options and /// default options. /// URLs may be relative or absolute, and do not have to have the same origin /// as the current page. /// The `options` parameter may be omitted completely and a callback passed in /// its place, if desired. /// Scripts will be executed in the order they're specified unless the `async` /// option is `true`, in which case they'll be loaded in parallel and executed /// in whatever order they finish loading. /// </summary> public Y_.Get_.Transaction js(object urls){return null;} /// <summary> /// Loads one or more JavaScript resources. /// The _urls_ parameter may be provided as a URL string, a request object, /// or an array of URL strings and/or request objects. /// A request object is just an object that contains a `url` property and zero /// or more options that should apply specifically to that request. /// Request-specific options take priority over transaction-level options and /// default options. /// URLs may be relative or absolute, and do not have to have the same origin /// as the current page. /// The `options` parameter may be omitted completely and a callback passed in /// its place, if desired. /// Scripts will be executed in the order they're specified unless the `async` /// option is `true`, in which case they'll be loaded in parallel and executed /// in whatever order they finish loading. /// </summary> public Y_.Get_.Transaction js(object urls, JsAction callback){return null;} /// <summary> /// Loads one or more JavaScript resources. /// The _urls_ parameter may be provided as a URL string, a request object, /// or an array of URL strings and/or request objects. /// A request object is just an object that contains a `url` property and zero /// or more options that should apply specifically to that request. /// Request-specific options take priority over transaction-level options and /// default options. /// URLs may be relative or absolute, and do not have to have the same origin /// as the current page. /// The `options` parameter may be omitted completely and a callback passed in /// its place, if desired. /// Scripts will be executed in the order they're specified unless the `async` /// option is `true`, in which case they'll be loaded in parallel and executed /// in whatever order they finish loading. /// </summary> public Y_.Get_.Transaction js(object urls, object options){return null;} /// <summary> /// Loads one or more JavaScript resources. /// The _urls_ parameter may be provided as a URL string, a request object, /// or an array of URL strings and/or request objects. /// A request object is just an object that contains a `url` property and zero /// or more options that should apply specifically to that request. /// Request-specific options take priority over transaction-level options and /// default options. /// URLs may be relative or absolute, and do not have to have the same origin /// as the current page. /// The `options` parameter may be omitted completely and a callback passed in /// its place, if desired. /// Scripts will be executed in the order they're specified unless the `async` /// option is `true`, in which case they'll be loaded in parallel and executed /// in whatever order they finish loading. /// </summary> public Y_.Get_.Transaction js(object urls, object options, JsAction callback){return null;} /// <summary> /// Loads one or more CSS and/or JavaScript resources in the same transaction. /// Use this method when you want to load both CSS and JavaScript in a single /// transaction and be notified when all requested URLs have finished loading, /// regardless of type. /// Behavior and options are the same as for the `css()` and `js()` methods. If /// a resource type isn't specified in per-request options or transaction-level /// options, Get will guess the file type based on the URL's extension (`.css` /// or `.js`, with or without a following query string). If the file type can't /// be guessed from the URL, a warning will be logged and Get will assume the /// URL is a JavaScript resource. /// </summary> public Y_.Get_.Transaction load(object urls, JsAction callback, object err, Y_.Get_.Transaction Transaction){return null;} /// <summary> /// Loads one or more CSS and/or JavaScript resources in the same transaction. /// Use this method when you want to load both CSS and JavaScript in a single /// transaction and be notified when all requested URLs have finished loading, /// regardless of type. /// Behavior and options are the same as for the `css()` and `js()` methods. If /// a resource type isn't specified in per-request options or transaction-level /// options, Get will guess the file type based on the URL's extension (`.css` /// or `.js`, with or without a following query string). If the file type can't /// be guessed from the URL, a warning will be logged and Get will assume the /// URL is a JavaScript resource. /// </summary> public Y_.Get_.Transaction load(object urls, object options, JsAction callback, object err, Y_.Get_.Transaction Transaction){return null;} /// <summary> /// Loads one or more CSS and/or JavaScript resources in the same transaction. /// Use this method when you want to load both CSS and JavaScript in a single /// transaction and be notified when all requested URLs have finished loading, /// regardless of type. /// Behavior and options are the same as for the `css()` and `js()` methods. If /// a resource type isn't specified in per-request options or transaction-level /// options, Get will guess the file type based on the URL's extension (`.css` /// or `.js`, with or without a following query string). If the file type can't /// be guessed from the URL, a warning will be logged and Get will assume the /// URL is a JavaScript resource. /// </summary> public Y_.Get_.Transaction load(object urls, object options, object err, Y_.Get_.Transaction Transaction){return null;} /// <summary> /// Loads one or more CSS and/or JavaScript resources in the same transaction. /// Use this method when you want to load both CSS and JavaScript in a single /// transaction and be notified when all requested URLs have finished loading, /// regardless of type. /// Behavior and options are the same as for the `css()` and `js()` methods. If /// a resource type isn't specified in per-request options or transaction-level /// options, Get will guess the file type based on the URL's extension (`.css` /// or `.js`, with or without a following query string). If the file type can't /// be guessed from the URL, a warning will be logged and Get will assume the /// URL is a JavaScript resource. /// </summary> public Y_.Get_.Transaction load(object urls, object err, Y_.Get_.Transaction Transaction){return null;} /// <summary> /// Alias for `js()`. /// </summary> public void script(){} /// <summary> /// Contains information about the current environment, such as what script and /// link injection features it supports. /// This object is created and populated the first time the `_getEnv()` method /// is called. /// </summary> protected object _env{get;set;} /// <summary> /// Mapping of document _yuid strings to <head> or <base> node references so we /// don't have to look the node up each time we want to insert a request node. /// </summary> protected object _insertCache{get;set;} /// <summary> /// Information about the currently pending transaction, if any. /// This is actually an object with two properties: `callback`, containing the /// optional callback passed to `css()`, `load()`, or `js()`; and `transaction`, /// containing the actual transaction instance. /// </summary> protected object _pending{get;set;} /// <summary> /// Default options for CSS requests. Options specified here will override /// global defaults for CSS requests. /// See the `options` property for all available options. /// </summary> public object cssOptions{get;set;} /// <summary> /// Default options for JS requests. Options specified here will override global /// defaults for JS requests. /// See the `options` property for all available options. /// </summary> public object jsOptions{get;set;} /// <summary> /// Default options to use for all requests. /// Note that while all available options are documented here for ease of /// discovery, some options (like callback functions) only make sense at the /// transaction level. /// Callback functions specified via the options object or the `options` /// parameter of the `css()`, `js()`, or `load()` methods will receive the /// transaction object as a parameter. See `Y.Get.Transaction` for details on /// the properties and methods available on transactions. /// </summary> public object options{get;set;} } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Xml { internal partial class ReadContentAsBinaryHelper { // Private enums private enum State { None, InReadContent, InReadElementContent, } // Fields private XmlReader _reader; private State _state; private int _valueOffset; private bool _isEnd; private bool _canReadValueChunk; private char[] _valueChunk; private int _valueChunkLength; private IncrementalReadDecoder _decoder; private Base64Decoder _base64Decoder; private BinHexDecoder _binHexDecoder; // Constants private const int ChunkSize = 256; // Constructor internal ReadContentAsBinaryHelper(XmlReader reader) { _reader = reader; _canReadValueChunk = reader.CanReadValueChunk; if (_canReadValueChunk) { _valueChunk = new char[ChunkSize]; } } // Static methods internal static ReadContentAsBinaryHelper CreateOrReset(ReadContentAsBinaryHelper helper, XmlReader reader) { if (helper == null) { return new ReadContentAsBinaryHelper(reader); } else { helper.Reset(); return helper; } } // Internal methods internal int ReadContentAsBase64(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException(nameof(count)); } switch (_state) { case State.None: if (!_reader.CanReadContentAs()) { throw _reader.CreateReadContentAsException(nameof(ReadContentAsBase64)); } if (!Init()) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if (_decoder == _base64Decoder) { // read more binary data return ReadContentAsBinary(buffer, index, count); } break; case State.InReadElementContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadContent); // setup base64 decoder InitBase64Decoder(); // read more binary data return ReadContentAsBinary(buffer, index, count); } internal int ReadContentAsBinHex(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException(nameof(count)); } switch (_state) { case State.None: if (!_reader.CanReadContentAs()) { throw _reader.CreateReadContentAsException(nameof(ReadContentAsBinHex)); } if (!Init()) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if (_decoder == _binHexDecoder) { // read more binary data return ReadContentAsBinary(buffer, index, count); } break; case State.InReadElementContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadContent); // setup binhex decoder InitBinHexDecoder(); // read more binary data return ReadContentAsBinary(buffer, index, count); } internal int ReadElementContentAsBase64(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException(nameof(count)); } switch (_state) { case State.None: if (_reader.NodeType != XmlNodeType.Element) { throw _reader.CreateReadElementContentAsException(nameof(ReadElementContentAsBase64)); } if (!InitOnElement()) { return 0; } break; case State.InReadContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); case State.InReadElementContent: // if we have a correct decoder, go read if (_decoder == _base64Decoder) { // read more binary data return ReadElementContentAsBinary(buffer, index, count); } break; default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadElementContent); // setup base64 decoder InitBase64Decoder(); // read more binary data return ReadElementContentAsBinary(buffer, index, count); } internal int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException(nameof(count)); } switch (_state) { case State.None: if (_reader.NodeType != XmlNodeType.Element) { throw _reader.CreateReadElementContentAsException(nameof(ReadElementContentAsBinHex)); } if (!InitOnElement()) { return 0; } break; case State.InReadContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); case State.InReadElementContent: // if we have a correct decoder, go read if (_decoder == _binHexDecoder) { // read more binary data return ReadElementContentAsBinary(buffer, index, count); } break; default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadElementContent); // setup binhex decoder InitBinHexDecoder(); // read more binary data return ReadElementContentAsBinary(buffer, index, count); } internal void Finish() { if (_state != State.None) { while (MoveToNextContentNode(true)) { } if (_state == State.InReadElementContent) { if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off the EndElement _reader.Read(); } } Reset(); } internal void Reset() { _state = State.None; _isEnd = false; _valueOffset = 0; } // Private methods private bool Init() { // make sure we are on a content node if (!MoveToNextContentNode(false)) { return false; } _state = State.InReadContent; _isEnd = false; return true; } private bool InitOnElement() { Debug.Assert(_reader.NodeType == XmlNodeType.Element); bool isEmpty = _reader.IsEmptyElement; // move to content or off the empty element _reader.Read(); if (isEmpty) { return false; } // make sure we are on a content node if (!MoveToNextContentNode(false)) { if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off end element _reader.Read(); return false; } _state = State.InReadElementContent; _isEnd = false; return true; } private void InitBase64Decoder() { if (_base64Decoder == null) { _base64Decoder = new Base64Decoder(); } else { _base64Decoder.Reset(); } _decoder = _base64Decoder; } private void InitBinHexDecoder() { if (_binHexDecoder == null) { _binHexDecoder = new BinHexDecoder(); } else { _binHexDecoder.Reset(); } _decoder = _binHexDecoder; } private int ReadContentAsBinary(byte[] buffer, int index, int count) { Debug.Assert(_decoder != null); if (_isEnd) { Reset(); return 0; } _decoder.SetNextOutputBuffer(buffer, index, count); for (; ;) { // use streaming ReadValueChunk if the reader supports it if (_canReadValueChunk) { for (; ;) { if (_valueOffset < _valueChunkLength) { int decodedCharsCount = _decoder.Decode(_valueChunk, _valueOffset, _valueChunkLength - _valueOffset); _valueOffset += decodedCharsCount; } if (_decoder.IsFull) { return _decoder.DecodedCount; } Debug.Assert(_valueOffset == _valueChunkLength); if ((_valueChunkLength = _reader.ReadValueChunk(_valueChunk, 0, ChunkSize)) == 0) { break; } _valueOffset = 0; } } else { // read what is reader.Value string value = _reader.Value; int decodedCharsCount = _decoder.Decode(value, _valueOffset, value.Length - _valueOffset); _valueOffset += decodedCharsCount; if (_decoder.IsFull) { return _decoder.DecodedCount; } } _valueOffset = 0; // move to next textual node in the element content; throw on sub elements if (!MoveToNextContentNode(true)) { _isEnd = true; return _decoder.DecodedCount; } } } private int ReadElementContentAsBinary(byte[] buffer, int index, int count) { if (count == 0) { return 0; } // read binary int decoded = ReadContentAsBinary(buffer, index, count); if (decoded > 0) { return decoded; } // if 0 bytes returned check if we are on a closing EndElement, throw exception if not if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off the EndElement _reader.Read(); _state = State.None; return 0; } private bool MoveToNextContentNode(bool moveIfOnContentNode) { do { switch (_reader.NodeType) { case XmlNodeType.Attribute: return !moveIfOnContentNode; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: if (!moveIfOnContentNode) { return true; } break; case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.EndEntity: // skip comments, pis and end entity nodes break; case XmlNodeType.EntityReference: if (_reader.CanResolveEntity) { _reader.ResolveEntity(); break; } goto default; default: return false; } moveIfOnContentNode = false; } while (_reader.Read()); return false; } } }
using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using Android.App; using Android.Content; using Android.Hardware.Usb; using Android.Util; using Treehopper.Android; namespace Treehopper { public class ConnectionService : BroadcastReceiver, IConnectionService { private static string TAG = "ConnectionService"; static readonly ConnectionService instance = new ConnectionService(); readonly static string ActionUsbPermission = "io.treehopper.android.USB_PERMISSION"; private object lockObject = new object(); private PendingIntent pendingIntent; private TaskCompletionSource<TreehopperUsb> waitForFirstBoard = new TaskCompletionSource<TreehopperUsb>(); /// \cond PRIVATE /// <summary> /// The singleton instance through which to access %ConnectionService. /// </summary> /// <remarks> /// This instance is created and started upon the first reference to a property or method /// on this object. This typically only becomes an issue if you expect to have debug messages /// from ConnectionService printing even if you haven't actually accessed the object yet. /// </remarks> public static ConnectionService Instance { get { return instance; } } /// <summary> /// The %Treehopper boards attached to the computer. /// </summary> public ObservableCollection<TreehopperUsb> Boards { get; set; } /// <summary> /// Get a reference to the first device discovered. /// </summary> /// <returns>The first board found.</returns> /// <remarks> /// <para> /// If no devices have been plugged into the computer, /// this call will await indefinitely until a board is plugged in. /// </para> /// </remarks> public Task<TreehopperUsb> GetFirstDeviceAsync() { return waitForFirstBoard.Task; } public ConnectionService() : base() { Boards = new ObservableCollection<TreehopperUsb>(); } /*! \endcond */ private void Boards_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (Boards.Count == 0) waitForFirstBoard = new TaskCompletionSource<TreehopperUsb>(); else if ((e.OldItems?.Count ?? 0) == 0 && e.NewItems.Count > 0) waitForFirstBoard.TrySetResult(Boards[0]); } /** @name Xamarin.Android Methods * @{ */ /// <summary> /// Call this method in your main activity's OnStart() override. /// </summary> /// <param name="activity"></param> public void ActivityOnStart(Activity activity) { this.activity = activity; this.context = activity.ApplicationContext; Boards.CollectionChanged += Boards_CollectionChanged; Scan(); IntentFilter filter = new IntentFilter(); filter.AddAction(UsbManager.ActionUsbDeviceDetached); filter.AddAction(UsbManager.ActionUsbDeviceAttached); activity.RegisterReceiver(this, filter); } /// <summary> /// Call this method in your main activity's OnResume() override. /// </summary> public void ActivityOnResume() { Intent intent = activity.Intent; if (intent != null) { if (intent.Action == UsbManager.ActionUsbDeviceAttached) { UsbDevice usbDevice = (UsbDevice)intent.GetParcelableExtra(UsbManager.ExtraDevice); DeviceAdded(usbDevice); } } } public UsbManager Manager { get { return (UsbManager)context.GetSystemService(Context.UsbService); } } ///@} /*! \cond PRIVATE */ public void Dispose() { } public override void OnReceive(Context context, Intent intent) { if (intent.Action == UsbManager.ActionUsbDeviceDetached) { UsbDevice usbDevice = (UsbDevice)intent.GetParcelableExtra(UsbManager.ExtraDevice); DeviceRemoved(usbDevice); } if (intent.Action == UsbManager.ActionUsbDeviceAttached) { UsbDevice usbDevice = (UsbDevice)intent.GetParcelableExtra(UsbManager.ExtraDevice); createTreehopperFromDevice(usbDevice); } if (intent.Action == ActionUsbPermission) { lock (lockObject) { UsbDevice device = (UsbDevice)intent.GetParcelableExtra(UsbManager.ExtraDevice); if (intent.GetBooleanExtra(UsbManager.ExtraPermissionGranted, false)) { if (device != null) { if (Boards.Count(b => b.SerialNumber == device.SerialNumber) > 0) return; var board = new TreehopperUsb(new UsbConnection(device, Manager)); Log.Info(TAG, "Got permission to add new board (name=" + board.Name + ", serial=" + board.SerialNumber + "). Total number of boards: " + Boards.Count); Boards.Add(board); } } else { Log.Debug(TAG, "permission denied for device " + device); } } } } public void DeviceAdded(UsbDevice device) { createTreehopperFromDevice(device); } public void DeviceRemoved(UsbDevice device) { Log.Info(TAG, "DeviceRemoved called"); if (device == null) { // ugh, Android didn't tell us which device was removed, but if we only have one connected, we'll remove it if (Boards.Count == 1) { Boards[0].Disconnect(); Boards.Clear(); } } else { if (device.VendorId == 0x10c4 && device.ProductId == 0x8a7e) { TreehopperUsb removedBoard = Boards.FirstOrDefault(b => b.SerialNumber == device.SerialNumber); if(removedBoard != null) { removedBoard.Disconnect(); Boards.Remove(removedBoard); } } } } private void createTreehopperFromDevice(UsbDevice device) { Log.Info(TAG, "createTreehopperFromDevice called"); if (device.VendorId == 0x10c4 && device.ProductId == 0x8a7e) { if (Boards.Count(b => b.SerialNumber == device.SerialNumber) != 0) { Log.Info(TAG, "device found. Not adding to list."); } else { Log.Info(TAG, "device not found. Adding."); Manager.RequestPermission(device, pendingIntent); } } } private Context context; private Activity activity; public void Scan() { if (context == null) return; pendingIntent = PendingIntent.GetBroadcast(context, 0, new Intent(ActionUsbPermission), 0); IntentFilter filter = new IntentFilter(ActionUsbPermission); context.RegisterReceiver(this, filter); foreach (var entry in Manager.DeviceList) { UsbDevice device = entry.Value; createTreehopperFromDevice(device); } } /*! \endcond */ } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2015 FUJIWARA, Yusuke // // 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 -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; using System.Collections.Generic; using System.Collections.ObjectModel; #if !UNITY || MSGPACK_UNITY_FULL using System.ComponentModel; #endif // !UNITY || MSGPACK_UNITY_FULL using System.Diagnostics; using System.Linq; namespace MsgPack.Serialization { /// <summary> /// <para> /// <strong>This is intened to MsgPack for CLI internal use. Do not use this type from application directly.</strong> /// </para> /// <para> /// A provider parameter to support polymorphism. /// </para> /// </summary> #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL [DebuggerDisplay("{DebugString}")] public sealed partial class PolymorphismSchema { /// <summary> /// Gets the type of the serialization target. /// </summary> /// <value> /// The type of the serialization target. This value can be <c>null</c>. /// </value> internal Type TargetType { get; private set; } /// <summary> /// Gets the type of the polymorphism. /// </summary> /// <value> /// The type of the polymorphism. /// </value> internal PolymorphismType PolymorphismType { get; private set; } private readonly ReadOnlyDictionary<string, Type> _codeTypeMapping; /// <summary> /// Gets the code type mapping which maps between ext-type codes and .NET <see cref="Type"/>s. /// </summary> /// <value> /// The code type mapping which maps between ext-type codes and .NET <see cref="Type"/>s. /// </value> internal IDictionary<string, Type> CodeTypeMapping { get { return this._codeTypeMapping; } } internal bool UseDefault { get { return this.PolymorphismType == PolymorphismType.None; } } internal bool UseTypeEmbedding { get { return this.PolymorphismType == PolymorphismType.RuntimeType; } } internal PolymorphismSchemaChildrenType ChildrenType { get; private set; } private readonly ReadOnlyCollection<PolymorphismSchema> _children; /// <summary> /// Gets the schema for child items of the serialization target collection/tuple. /// </summary> /// <value> /// The schema for child items of the serialization target collection/tuple. /// </value> internal IList<PolymorphismSchema> ChildSchemaList { get { return this._children; } } /// <summary> /// Gets the schema for collection items of the serialization target collection. /// </summary> /// <value> /// The schema for collection items of the serialization target collection. /// </value> internal PolymorphismSchema ItemSchema { get { switch ( this.ChildrenType ) { case PolymorphismSchemaChildrenType.None: { return null; } case PolymorphismSchemaChildrenType.CollectionItems: { return this._children.FirstOrDefault(); } case PolymorphismSchemaChildrenType.DictionaryKeyValues: { return this._children.Skip( 1 ).FirstOrDefault(); } default: { throw new NotSupportedException(); } } } } /// <summary> /// Gets the schema for dictionary keys of the serialization target collection. /// </summary> /// <value> /// The schema for collection items of the serialization target collection. /// </value> internal PolymorphismSchema KeySchema { get { switch ( this.ChildrenType ) { case PolymorphismSchemaChildrenType.None: { return null; } case PolymorphismSchemaChildrenType.DictionaryKeyValues: { return this._children.FirstOrDefault(); } default: { throw new NotSupportedException(); } } } } #if NETFX_35 || NETFX_40 || SILVERLIGHT || UNITY private sealed class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue> { private readonly IDictionary<TKey, TValue> _underlying; ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return this._underlying.Keys; } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return this._underlying.Values; } } TValue IDictionary<TKey, TValue>.this[ TKey key ] { get { return this._underlying[ key ]; } set { throw new NotSupportedException(); } } int ICollection<KeyValuePair<TKey, TValue>>.Count { get { return this._underlying.Count; } } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return true; } } public ReadOnlyDictionary( IDictionary<TKey, TValue> underlying ) { this._underlying = underlying; } bool IDictionary<TKey, TValue>.ContainsKey( TKey key ) { return this._underlying.ContainsKey( key ); } bool IDictionary<TKey, TValue>.TryGetValue( TKey key, out TValue value ) { return this._underlying.TryGetValue( key, out value ); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains( KeyValuePair<TKey, TValue> item ) { return this._underlying.Contains( item ); } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo( KeyValuePair<TKey, TValue>[] array, int arrayIndex ) { this._underlying.CopyTo( array, arrayIndex ); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return this._underlying.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this._underlying.GetEnumerator(); } void IDictionary<TKey, TValue>.Add( TKey key, TValue value ) { throw new NotSupportedException(); } bool IDictionary<TKey, TValue>.Remove( TKey key ) { throw new NotSupportedException(); } void ICollection<KeyValuePair<TKey, TValue>>.Add( KeyValuePair<TKey, TValue> item ) { throw new NotSupportedException(); } void ICollection<KeyValuePair<TKey, TValue>>.Clear() { throw new NotSupportedException(); } bool ICollection<KeyValuePair<TKey, TValue>>.Remove( KeyValuePair<TKey, TValue> item ) { throw new NotSupportedException(); } } #endif // NETFX_35 || NETFX_40 || SILVERLIGHT || UNITY } }
// Copyright (c) .NET Foundation and contributors. 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.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Versioning; namespace NuGet { public class PackageBuilder { private const string DefaultContentType = "application/octet"; internal const string ManifestRelationType = "manifest"; private bool _includeEmptyDirectories = false; public PackageBuilder() { Files = new List<IPackageFile>(); DependencySets = new List<PackageDependencySet>(); FrameworkAssemblies = new List<FrameworkAssemblyReference>(); PackageAssemblyReferences = new List<PackageReferenceSet>(); ContentFiles = new List<ManifestContentFiles>(); Authors = new List<string>(); Owners = new List<string>(); Tags = new List<string>(); } public string Id { get; set; } public NuGetVersion Version { get; set; } public string Title { get; set; } public List<string> Authors { get; private set; } public List<string> Owners { get; private set; } public Uri IconUrl { get; set; } public Uri LicenseUrl { get; set; } public Uri ProjectUrl { get; set; } public bool RequireLicenseAcceptance { get; set; } public bool DevelopmentDependency { get; set; } public string Description { get; set; } public string Summary { get; set; } public string ReleaseNotes { get; set; } public string Language { get; set; } public List<string> Tags { get; private set; } public string Copyright { get; set; } public List<PackageDependencySet> DependencySets { get; private set; } public List<IPackageFile> Files { get; private set; } public List<FrameworkAssemblyReference> FrameworkAssemblies { get; private set; } public List<PackageReferenceSet> PackageAssemblyReferences { get; private set; } public List<ManifestContentFiles> ContentFiles { get; private set; } public Version MinClientVersion { get; set; } public void Save(Stream stream) { // Make sure we're saving a valid package id PackageIdValidator.ValidatePackageId(Id); // Throw if the package doesn't contain any dependencies nor content if (!Files.Any() && !DependencySets.SelectMany(d => d.Dependencies).Any() && !FrameworkAssemblies.Any()) { // TODO: Resources throw new InvalidOperationException("NuGetResources.CannotCreateEmptyPackage"); } if (!ValidateSpecialVersionLength(Version)) { // TODO: Resources throw new InvalidOperationException("NuGetResources.SemVerSpecialVersionTooLong"); } ValidateDependencySets(Version, DependencySets); ValidateReferenceAssemblies(Files, PackageAssemblyReferences); using (var package = new ZipArchive(stream, ZipArchiveMode.Create)) { // Validate and write the manifest WriteManifest(package, ManifestVersionUtility.DefaultVersion); // Write the files to the package var extensions = WriteFiles(package); extensions.Add("nuspec"); WriteOpcContentTypes(package, extensions); } } private static string CreatorInfo() { var creatorInfo = new List<string>(); var assembly = typeof(PackageBuilder).GetTypeInfo().Assembly; creatorInfo.Add(assembly.FullName); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { creatorInfo.Add("Linux"); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { creatorInfo.Add("OSX"); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { creatorInfo.Add("Windows"); } var attribute = assembly.GetCustomAttributes<System.Runtime.Versioning.TargetFrameworkAttribute>().FirstOrDefault(); if (attribute != null) { creatorInfo.Add(attribute.FrameworkDisplayName); } return String.Join(";", creatorInfo); } internal static void ValidateDependencySets(SemanticVersion version, IEnumerable<PackageDependencySet> dependencies) { if (version == null) { // We have independent validation for null-versions. return; } foreach (var dep in dependencies.SelectMany(s => s.Dependencies)) { PackageIdValidator.ValidatePackageId(dep.Id); } // REVIEW: Do we want to keep enfocing this? /*if (version.IsPrerelease) { // If we are creating a production package, do not allow any of the dependencies to be a prerelease version. var prereleaseDependency = dependencies.SelectMany(set => set.Dependencies).FirstOrDefault(IsPrereleaseDependency); if (prereleaseDependency != null) { throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, "NuGetResources.Manifest_InvalidPrereleaseDependency", prereleaseDependency.ToString())); } }*/ } internal static void ValidateReferenceAssemblies(IEnumerable<IPackageFile> files, IEnumerable<PackageReferenceSet> packageAssemblyReferences) { var libFiles = new HashSet<string>(from file in files where !string.IsNullOrEmpty(file.Path) && file.Path.StartsWith("lib", StringComparison.OrdinalIgnoreCase) select Path.GetFileName(file.Path), StringComparer.OrdinalIgnoreCase); foreach (var reference in packageAssemblyReferences.SelectMany(p => p.References)) { if (!libFiles.Contains(reference) && !libFiles.Contains(reference + ".dll") && !libFiles.Contains(reference + ".exe") && !libFiles.Contains(reference + ".winmd")) { // TODO: Resources throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, "NuGetResources.Manifest_InvalidReference", reference)); } } } public void Populate(ManifestMetadata manifestMetadata) { Id = manifestMetadata.Id; Version = manifestMetadata.Version; Title = manifestMetadata.Title; AppendIfNotNull(Authors, manifestMetadata.Authors); AppendIfNotNull(Owners, manifestMetadata.Owners); IconUrl = manifestMetadata.IconUrl; LicenseUrl = manifestMetadata.LicenseUrl; ProjectUrl = manifestMetadata.ProjectUrl; RequireLicenseAcceptance = manifestMetadata.RequireLicenseAcceptance; DevelopmentDependency = manifestMetadata.DevelopmentDependency; Description = manifestMetadata.Description; Summary = manifestMetadata.Summary; ReleaseNotes = manifestMetadata.ReleaseNotes; Language = manifestMetadata.Language; Copyright = manifestMetadata.Copyright; MinClientVersion = manifestMetadata.MinClientVersion; if (manifestMetadata.Tags != null) { Tags.AddRange(ParseTags(manifestMetadata.Tags)); } AppendIfNotNull(DependencySets, manifestMetadata.DependencySets); AppendIfNotNull(FrameworkAssemblies, manifestMetadata.FrameworkAssemblies); AppendIfNotNull(PackageAssemblyReferences, manifestMetadata.PackageAssemblyReferences); AppendIfNotNull(ContentFiles, manifestMetadata.ContentFiles); } public void PopulateFiles(string basePath, IEnumerable<ManifestFile> files) { foreach (var file in files) { AddFiles(basePath, file.Source, file.Target, file.Exclude); } } private void WriteManifest(ZipArchive package, int minimumManifestVersion) { string path = Id + Constants.ManifestExtension; WriteOpcManifestRelationship(package, path); ZipArchiveEntry entry = package.CreateEntry(path, CompressionLevel.Optimal); using (Stream stream = entry.Open()) { Manifest manifest = Manifest.Create(this); manifest.Save(stream, minimumManifestVersion); } } private HashSet<string> WriteFiles(ZipArchive package) { var extensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase); // Add files that might not come from expanding files on disk foreach (var file in Files.Distinct()) { using (Stream stream = file.GetStream()) { try { CreatePart(package, file.Path, stream); var fileExtension = Path.GetExtension(file.Path); // We have files without extension (e.g. the executables for Nix) if (!string.IsNullOrEmpty(fileExtension)) { extensions.Add(fileExtension.Substring(1)); } } catch { throw; } } } return extensions; } private void AddFiles(string basePath, string source, string destination, string exclude = null) { List<PhysicalPackageFile> searchFiles = PathResolver.ResolveSearchPattern(basePath, source, destination, _includeEmptyDirectories).ToList(); ExcludeFiles(searchFiles, basePath, exclude); if (!PathResolver.IsWildcardSearch(source) && !PathResolver.IsDirectoryPath(source) && !searchFiles.Any()) { // TODO: Resources throw new FileNotFoundException( String.Format(CultureInfo.CurrentCulture, "NuGetResources.PackageAuthoring_FileNotFound {0}", source)); } Files.AddRange(searchFiles); } private static void ExcludeFiles(List<PhysicalPackageFile> searchFiles, string basePath, string exclude) { if (String.IsNullOrEmpty(exclude)) { return; } // One or more exclusions may be specified in the file. Split it and prepend the base path to the wildcard provided. var exclusions = exclude.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in exclusions) { string wildCard = PathResolver.NormalizeWildcardForExcludedFiles(basePath, item); PathResolver.FilterPackageFiles(searchFiles, p => p.SourcePath, new[] { wildCard }); } } private static void CreatePart(ZipArchive package, string path, Stream sourceStream) { if (PackageHelper.IsManifest(path)) { return; } var entry = package.CreateEntry(PathUtility.GetPathWithForwardSlashes(path), CompressionLevel.Optimal); using (var stream = entry.Open()) { sourceStream.CopyTo(stream); } } /// <summary> /// Tags come in this format. tag1 tag2 tag3 etc.. /// </summary> private static IEnumerable<string> ParseTags(string tags) { return from tag in tags.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) select tag.Trim(); } private static bool IsPrereleaseDependency(PackageDependency dependency) { return dependency.VersionRange.MinVersion?.IsPrerelease == true || dependency.VersionRange.MaxVersion?.IsPrerelease == true; } private static bool ValidateSpecialVersionLength(SemanticVersion version) { if (!version.IsPrerelease) { return true; } return version == null || version.Release.Length <= 20; } private static void WriteOpcManifestRelationship(ZipArchive package, string path) { ZipArchiveEntry relsEntry = package.CreateEntry("_rels/.rels", CompressionLevel.Optimal); using (var writer = new StreamWriter(relsEntry.Open())) { writer.Write(String.Format(@"<?xml version=""1.0"" encoding=""utf-8""?> <Relationships xmlns=""http://schemas.openxmlformats.org/package/2006/relationships""> <Relationship Type=""http://schemas.microsoft.com/packaging/2010/07/manifest"" Target=""/{0}"" Id=""{1}"" /> </Relationships>", path, GenerateRelationshipId())); writer.Flush(); } } private static void WriteOpcContentTypes(ZipArchive package, HashSet<string> extensions) { // OPC backwards compatibility ZipArchiveEntry relsEntry = package.CreateEntry("[Content_Types].xml", CompressionLevel.Optimal); using (var writer = new StreamWriter(relsEntry.Open())) { writer.Write(@"<?xml version=""1.0"" encoding=""utf-8""?> <Types xmlns=""http://schemas.openxmlformats.org/package/2006/content-types""> <Default Extension=""rels"" ContentType=""application/vnd.openxmlformats-package.relationships+xml"" />"); foreach (var extension in extensions) { writer.Write(@"<Default Extension=""" + extension + @""" ContentType=""application/octet"" />"); } writer.Write("</Types>"); writer.Flush(); } } // Generate a relationship id for compatibility private static string GenerateRelationshipId() { return "R" + Guid.NewGuid().ToString("N").Substring(0, 16); } private static void AppendIfNotNull<T>(List<T> collection, IEnumerable<T> toAdd) { if (toAdd != null) { collection.AddRange(toAdd); } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SAEON.Observations.Data { /// <summary> /// Strongly-typed collection for the Instrument class. /// </summary> [Serializable] public partial class InstrumentCollection : ActiveList<Instrument, InstrumentCollection> { public InstrumentCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>InstrumentCollection</returns> public InstrumentCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { Instrument o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Instrument table. /// </summary> [Serializable] public partial class Instrument : ActiveRecord<Instrument>, IActiveRecord { #region .ctors and Default Settings public Instrument() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Instrument(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public Instrument(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public Instrument(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Instrument", TableType.Table, DataService.GetInstance("ObservationsDB")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Guid; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @"(newid())"; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarCode = new TableSchema.TableColumn(schema); colvarCode.ColumnName = "Code"; colvarCode.DataType = DbType.AnsiString; colvarCode.MaxLength = 50; colvarCode.AutoIncrement = false; colvarCode.IsNullable = false; colvarCode.IsPrimaryKey = false; colvarCode.IsForeignKey = false; colvarCode.IsReadOnly = false; colvarCode.DefaultSetting = @""; colvarCode.ForeignKeyTableName = ""; schema.Columns.Add(colvarCode); TableSchema.TableColumn colvarName = new TableSchema.TableColumn(schema); colvarName.ColumnName = "Name"; colvarName.DataType = DbType.AnsiString; colvarName.MaxLength = 150; colvarName.AutoIncrement = false; colvarName.IsNullable = false; colvarName.IsPrimaryKey = false; colvarName.IsForeignKey = false; colvarName.IsReadOnly = false; colvarName.DefaultSetting = @""; colvarName.ForeignKeyTableName = ""; schema.Columns.Add(colvarName); TableSchema.TableColumn colvarDescription = new TableSchema.TableColumn(schema); colvarDescription.ColumnName = "Description"; colvarDescription.DataType = DbType.AnsiString; colvarDescription.MaxLength = 5000; colvarDescription.AutoIncrement = false; colvarDescription.IsNullable = true; colvarDescription.IsPrimaryKey = false; colvarDescription.IsForeignKey = false; colvarDescription.IsReadOnly = false; colvarDescription.DefaultSetting = @""; colvarDescription.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescription); TableSchema.TableColumn colvarUrl = new TableSchema.TableColumn(schema); colvarUrl.ColumnName = "Url"; colvarUrl.DataType = DbType.AnsiString; colvarUrl.MaxLength = 250; colvarUrl.AutoIncrement = false; colvarUrl.IsNullable = true; colvarUrl.IsPrimaryKey = false; colvarUrl.IsForeignKey = false; colvarUrl.IsReadOnly = false; colvarUrl.DefaultSetting = @""; colvarUrl.ForeignKeyTableName = ""; schema.Columns.Add(colvarUrl); TableSchema.TableColumn colvarStartDate = new TableSchema.TableColumn(schema); colvarStartDate.ColumnName = "StartDate"; colvarStartDate.DataType = DbType.Date; colvarStartDate.MaxLength = 0; colvarStartDate.AutoIncrement = false; colvarStartDate.IsNullable = true; colvarStartDate.IsPrimaryKey = false; colvarStartDate.IsForeignKey = false; colvarStartDate.IsReadOnly = false; colvarStartDate.DefaultSetting = @""; colvarStartDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarStartDate); TableSchema.TableColumn colvarEndDate = new TableSchema.TableColumn(schema); colvarEndDate.ColumnName = "EndDate"; colvarEndDate.DataType = DbType.Date; colvarEndDate.MaxLength = 0; colvarEndDate.AutoIncrement = false; colvarEndDate.IsNullable = true; colvarEndDate.IsPrimaryKey = false; colvarEndDate.IsForeignKey = false; colvarEndDate.IsReadOnly = false; colvarEndDate.DefaultSetting = @""; colvarEndDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarEndDate); TableSchema.TableColumn colvarLatitude = new TableSchema.TableColumn(schema); colvarLatitude.ColumnName = "Latitude"; colvarLatitude.DataType = DbType.Double; colvarLatitude.MaxLength = 0; colvarLatitude.AutoIncrement = false; colvarLatitude.IsNullable = true; colvarLatitude.IsPrimaryKey = false; colvarLatitude.IsForeignKey = false; colvarLatitude.IsReadOnly = false; colvarLatitude.DefaultSetting = @""; colvarLatitude.ForeignKeyTableName = ""; schema.Columns.Add(colvarLatitude); TableSchema.TableColumn colvarLongitude = new TableSchema.TableColumn(schema); colvarLongitude.ColumnName = "Longitude"; colvarLongitude.DataType = DbType.Double; colvarLongitude.MaxLength = 0; colvarLongitude.AutoIncrement = false; colvarLongitude.IsNullable = true; colvarLongitude.IsPrimaryKey = false; colvarLongitude.IsForeignKey = false; colvarLongitude.IsReadOnly = false; colvarLongitude.DefaultSetting = @""; colvarLongitude.ForeignKeyTableName = ""; schema.Columns.Add(colvarLongitude); TableSchema.TableColumn colvarElevation = new TableSchema.TableColumn(schema); colvarElevation.ColumnName = "Elevation"; colvarElevation.DataType = DbType.Double; colvarElevation.MaxLength = 0; colvarElevation.AutoIncrement = false; colvarElevation.IsNullable = true; colvarElevation.IsPrimaryKey = false; colvarElevation.IsForeignKey = false; colvarElevation.IsReadOnly = false; colvarElevation.DefaultSetting = @""; colvarElevation.ForeignKeyTableName = ""; schema.Columns.Add(colvarElevation); TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema); colvarUserId.ColumnName = "UserId"; colvarUserId.DataType = DbType.Guid; colvarUserId.MaxLength = 0; colvarUserId.AutoIncrement = false; colvarUserId.IsNullable = false; colvarUserId.IsPrimaryKey = false; colvarUserId.IsForeignKey = true; colvarUserId.IsReadOnly = false; colvarUserId.DefaultSetting = @""; colvarUserId.ForeignKeyTableName = "aspnet_Users"; schema.Columns.Add(colvarUserId); TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema); colvarAddedAt.ColumnName = "AddedAt"; colvarAddedAt.DataType = DbType.DateTime; colvarAddedAt.MaxLength = 0; colvarAddedAt.AutoIncrement = false; colvarAddedAt.IsNullable = true; colvarAddedAt.IsPrimaryKey = false; colvarAddedAt.IsForeignKey = false; colvarAddedAt.IsReadOnly = false; colvarAddedAt.DefaultSetting = @"(getdate())"; colvarAddedAt.ForeignKeyTableName = ""; schema.Columns.Add(colvarAddedAt); TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema); colvarUpdatedAt.ColumnName = "UpdatedAt"; colvarUpdatedAt.DataType = DbType.DateTime; colvarUpdatedAt.MaxLength = 0; colvarUpdatedAt.AutoIncrement = false; colvarUpdatedAt.IsNullable = true; colvarUpdatedAt.IsPrimaryKey = false; colvarUpdatedAt.IsForeignKey = false; colvarUpdatedAt.IsReadOnly = false; colvarUpdatedAt.DefaultSetting = @"(getdate())"; colvarUpdatedAt.ForeignKeyTableName = ""; schema.Columns.Add(colvarUpdatedAt); TableSchema.TableColumn colvarRowVersion = new TableSchema.TableColumn(schema); colvarRowVersion.ColumnName = "RowVersion"; colvarRowVersion.DataType = DbType.Binary; colvarRowVersion.MaxLength = 0; colvarRowVersion.AutoIncrement = false; colvarRowVersion.IsNullable = false; colvarRowVersion.IsPrimaryKey = false; colvarRowVersion.IsForeignKey = false; colvarRowVersion.IsReadOnly = true; colvarRowVersion.DefaultSetting = @""; colvarRowVersion.ForeignKeyTableName = ""; schema.Columns.Add(colvarRowVersion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["ObservationsDB"].AddSchema("Instrument",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public Guid Id { get { return GetColumnValue<Guid>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("Code")] [Bindable(true)] public string Code { get { return GetColumnValue<string>(Columns.Code); } set { SetColumnValue(Columns.Code, value); } } [XmlAttribute("Name")] [Bindable(true)] public string Name { get { return GetColumnValue<string>(Columns.Name); } set { SetColumnValue(Columns.Name, value); } } [XmlAttribute("Description")] [Bindable(true)] public string Description { get { return GetColumnValue<string>(Columns.Description); } set { SetColumnValue(Columns.Description, value); } } [XmlAttribute("Url")] [Bindable(true)] public string Url { get { return GetColumnValue<string>(Columns.Url); } set { SetColumnValue(Columns.Url, value); } } [XmlAttribute("StartDate")] [Bindable(true)] public DateTime? StartDate { get { return GetColumnValue<DateTime?>(Columns.StartDate); } set { SetColumnValue(Columns.StartDate, value); } } [XmlAttribute("EndDate")] [Bindable(true)] public DateTime? EndDate { get { return GetColumnValue<DateTime?>(Columns.EndDate); } set { SetColumnValue(Columns.EndDate, value); } } [XmlAttribute("Latitude")] [Bindable(true)] public double? Latitude { get { return GetColumnValue<double?>(Columns.Latitude); } set { SetColumnValue(Columns.Latitude, value); } } [XmlAttribute("Longitude")] [Bindable(true)] public double? Longitude { get { return GetColumnValue<double?>(Columns.Longitude); } set { SetColumnValue(Columns.Longitude, value); } } [XmlAttribute("Elevation")] [Bindable(true)] public double? Elevation { get { return GetColumnValue<double?>(Columns.Elevation); } set { SetColumnValue(Columns.Elevation, value); } } [XmlAttribute("UserId")] [Bindable(true)] public Guid UserId { get { return GetColumnValue<Guid>(Columns.UserId); } set { SetColumnValue(Columns.UserId, value); } } [XmlAttribute("AddedAt")] [Bindable(true)] public DateTime? AddedAt { get { return GetColumnValue<DateTime?>(Columns.AddedAt); } set { SetColumnValue(Columns.AddedAt, value); } } [XmlAttribute("UpdatedAt")] [Bindable(true)] public DateTime? UpdatedAt { get { return GetColumnValue<DateTime?>(Columns.UpdatedAt); } set { SetColumnValue(Columns.UpdatedAt, value); } } [XmlAttribute("RowVersion")] [Bindable(true)] public byte[] RowVersion { get { return GetColumnValue<byte[]>(Columns.RowVersion); } set { SetColumnValue(Columns.RowVersion, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } public SAEON.Observations.Data.ImportBatchSummaryCollection ImportBatchSummaryRecords() { return new SAEON.Observations.Data.ImportBatchSummaryCollection().Where(ImportBatchSummary.Columns.InstrumentID, Id).Load(); } public SAEON.Observations.Data.InstrumentSensorCollection InstrumentSensorRecords() { return new SAEON.Observations.Data.InstrumentSensorCollection().Where(InstrumentSensor.Columns.InstrumentID, Id).Load(); } public SAEON.Observations.Data.OrganisationInstrumentCollection OrganisationInstrumentRecords() { return new SAEON.Observations.Data.OrganisationInstrumentCollection().Where(OrganisationInstrument.Columns.InstrumentID, Id).Load(); } public SAEON.Observations.Data.StationInstrumentCollection StationInstrumentRecords() { return new SAEON.Observations.Data.StationInstrumentCollection().Where(StationInstrument.Columns.InstrumentID, Id).Load(); } #endregion #region ForeignKey Properties private SAEON.Observations.Data.AspnetUser _AspnetUser = null; /// <summary> /// Returns a AspnetUser ActiveRecord object related to this Instrument /// /// </summary> public SAEON.Observations.Data.AspnetUser AspnetUser { // get { return SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId); } get { return _AspnetUser ?? (_AspnetUser = SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId)); } set { SetColumnValue("UserId", value.UserId); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(Guid varId,string varCode,string varName,string varDescription,string varUrl,DateTime? varStartDate,DateTime? varEndDate,double? varLatitude,double? varLongitude,double? varElevation,Guid varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion) { Instrument item = new Instrument(); item.Id = varId; item.Code = varCode; item.Name = varName; item.Description = varDescription; item.Url = varUrl; item.StartDate = varStartDate; item.EndDate = varEndDate; item.Latitude = varLatitude; item.Longitude = varLongitude; item.Elevation = varElevation; item.UserId = varUserId; item.AddedAt = varAddedAt; item.UpdatedAt = varUpdatedAt; item.RowVersion = varRowVersion; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(Guid varId,string varCode,string varName,string varDescription,string varUrl,DateTime? varStartDate,DateTime? varEndDate,double? varLatitude,double? varLongitude,double? varElevation,Guid varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion) { Instrument item = new Instrument(); item.Id = varId; item.Code = varCode; item.Name = varName; item.Description = varDescription; item.Url = varUrl; item.StartDate = varStartDate; item.EndDate = varEndDate; item.Latitude = varLatitude; item.Longitude = varLongitude; item.Elevation = varElevation; item.UserId = varUserId; item.AddedAt = varAddedAt; item.UpdatedAt = varUpdatedAt; item.RowVersion = varRowVersion; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CodeColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn NameColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn DescriptionColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn UrlColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn StartDateColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn EndDateColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn LatitudeColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn LongitudeColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn ElevationColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn UserIdColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn AddedAtColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn UpdatedAtColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn RowVersionColumn { get { return Schema.Columns[13]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"ID"; public static string Code = @"Code"; public static string Name = @"Name"; public static string Description = @"Description"; public static string Url = @"Url"; public static string StartDate = @"StartDate"; public static string EndDate = @"EndDate"; public static string Latitude = @"Latitude"; public static string Longitude = @"Longitude"; public static string Elevation = @"Elevation"; public static string UserId = @"UserId"; public static string AddedAt = @"AddedAt"; public static string UpdatedAt = @"UpdatedAt"; public static string RowVersion = @"RowVersion"; } #endregion #region Update PK Collections public void SetPKValues() { } #endregion #region Deep Save public void DeepSave() { Save(); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.Avatar.Attachments { /// <summary> /// A module that just holds commands for inspecting avatar appearance. /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SceneCommandsModule")] public class SceneCommandsModule : ISceneCommandsModule, INonSharedRegionModule { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; public string Name { get { return "Scene Commands Module"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { // m_log.DebugFormat("[SCENE COMMANDS MODULE]: INITIALIZED MODULE"); } public void PostInitialise() { // m_log.DebugFormat("[SCENE COMMANDS MODULE]: POST INITIALIZED MODULE"); } public void Close() { // m_log.DebugFormat("[SCENE COMMANDS MODULE]: CLOSED MODULE"); } public void AddRegion(Scene scene) { // m_log.DebugFormat("[SCENE COMMANDS MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); m_scene = scene; m_scene.RegisterModuleInterface<ISceneCommandsModule>(this); } public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[SCENE COMMANDS MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); } public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[ATTACHMENTS COMMAND MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); scene.AddCommand( "Debug", this, "debug scene get", "debug scene get", "List current scene options.", "active - if false then main scene update and maintenance loops are suspended.\n" + "animations - if true then extra animations debug information is logged.\n" + "appear-refresh - if true then appearance is resent to other avatars every 60 seconds.\n" + "child-repri - how far an avatar must move in meters before we update the position of its child agents in neighbouring regions.\n" + "client-pos-upd - the tolerance before clients are updated with new rotation information for an avatar.\n" + "client-rot-upd - the tolerance before clients are updated with new rotation information for an avatar.\n" + "client-vel-upd - the tolerance before clients are updated with new velocity information for an avatar.\n" + "root-upd-per - if greater than 1, terse updates are only sent to root agents other than the originator on every n updates.\n" + "child-upd-per - if greater than 1, terse updates are only sent to child agents on every n updates.\n" + "collisions - if false then collisions with other objects are turned off.\n" + "pbackup - if false then periodic scene backup is turned off.\n" + "physics - if false then all physics objects are non-physical.\n" + "scripting - if false then no scripting operations happen.\n" + "teleport - if true then some extra teleport debug information is logged.\n" + "update-on-timer - If true then the scene is updated via a timer. If false then a thread with sleep is used.\n" + "updates - if true then any frame which exceeds double the maximum desired frame time is logged.", HandleDebugSceneGetCommand); scene.AddCommand( "Debug", this, "debug scene set", "debug scene set <param> <value>", "Turn on scene debugging options.", "active - if false then main scene update and maintenance loops are suspended.\n" + "animations - if true then extra animations debug information is logged.\n" + "appear-refresh - if true then appearance is resent to other avatars every 60 seconds.\n" + "child-repri - how far an avatar must move in meters before we update the position of its child agents in neighbouring regions.\n" + "client-pos-upd - the tolerance before clients are updated with new rotation information for an avatar.\n" + "client-rot-upd - the tolerance before clients are updated with new rotation information for an avatar.\n" + "client-vel-upd - the tolerance before clients are updated with new velocity information for an avatar.\n" + "root-upd-per - if greater than 1, terse updates are only sent to root agents other than the originator on every n updates.\n" + "child-upd-per - if greater than 1, terse updates are only sent to child agents on every n updates.\n" + "collisions - if false then collisions with other objects are turned off.\n" + "pbackup - if false then periodic scene backup is turned off.\n" + "physics - if false then all physics objects are non-physical.\n" + "scripting - if false then no scripting operations happen.\n" + "teleport - if true then some extra teleport debug information is logged.\n" + "update-on-timer - If true then the scene is updated via a timer. If false then a thread with sleep is used.\n" + "updates - if true then any frame which exceeds double the maximum desired frame time is logged.", HandleDebugSceneSetCommand); } private void HandleDebugSceneGetCommand(string module, string[] args) { if (args.Length == 3) { if (MainConsole.Instance.ConsoleScene != m_scene && MainConsole.Instance.ConsoleScene != null) return; OutputSceneDebugOptions(); } else { MainConsole.Instance.Output("Usage: debug scene get"); } } private void OutputSceneDebugOptions() { ConsoleDisplayList cdl = new ConsoleDisplayList(); cdl.AddRow("active", m_scene.Active); cdl.AddRow("animations", m_scene.DebugAnimations); cdl.AddRow("appear-refresh", m_scene.SendPeriodicAppearanceUpdates); cdl.AddRow("child-repri", m_scene.ChildReprioritizationDistance); cdl.AddRow("client-pos-upd", m_scene.RootPositionUpdateTolerance); cdl.AddRow("client-rot-upd", m_scene.RootRotationUpdateTolerance); cdl.AddRow("client-vel-upd", m_scene.RootVelocityUpdateTolerance); cdl.AddRow("root-upd-per", m_scene.RootTerseUpdatePeriod); cdl.AddRow("child-upd-per", m_scene.ChildTerseUpdatePeriod); cdl.AddRow("pbackup", m_scene.PeriodicBackup); cdl.AddRow("physics", m_scene.PhysicsEnabled); cdl.AddRow("scripting", m_scene.ScriptsEnabled); cdl.AddRow("teleport", m_scene.DebugTeleporting); // cdl.AddRow("update-on-timer", m_scene.UpdateOnTimer); cdl.AddRow("updates", m_scene.DebugUpdates); MainConsole.Instance.OutputFormat("Scene {0} options:", m_scene.Name); MainConsole.Instance.Output(cdl.ToString()); } private void HandleDebugSceneSetCommand(string module, string[] args) { if (args.Length == 5) { if (MainConsole.Instance.ConsoleScene != m_scene && MainConsole.Instance.ConsoleScene != null) return; string key = args[3]; string value = args[4]; SetSceneDebugOptions(new Dictionary<string, string>() { { key, value } }); MainConsole.Instance.OutputFormat("Set {0} debug scene {1} = {2}", m_scene.Name, key, value); } else { MainConsole.Instance.Output("Usage: debug scene set <param> <value>"); } } public void SetSceneDebugOptions(Dictionary<string, string> options) { if (options.ContainsKey("active")) { bool active; if (bool.TryParse(options["active"], out active)) m_scene.Active = active; } if (options.ContainsKey("animations")) { bool active; if (bool.TryParse(options["animations"], out active)) m_scene.DebugAnimations = active; } if (options.ContainsKey("appear-refresh")) { bool newValue; // FIXME: This can only come from the console at the moment but might not always be true. if (ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, options["appear-refresh"], out newValue)) m_scene.SendPeriodicAppearanceUpdates = newValue; } if (options.ContainsKey("child-repri")) { double newValue; // FIXME: This can only come from the console at the moment but might not always be true. if (ConsoleUtil.TryParseConsoleDouble(MainConsole.Instance, options["child-repri"], out newValue)) m_scene.ChildReprioritizationDistance = newValue; } if (options.ContainsKey("client-pos-upd")) { float newValue; // FIXME: This can only come from the console at the moment but might not always be true. if (ConsoleUtil.TryParseConsoleFloat(MainConsole.Instance, options["client-pos-upd"], out newValue)) m_scene.RootPositionUpdateTolerance = newValue; } if (options.ContainsKey("client-rot-upd")) { float newValue; // FIXME: This can only come from the console at the moment but might not always be true. if (ConsoleUtil.TryParseConsoleFloat(MainConsole.Instance, options["client-rot-upd"], out newValue)) m_scene.RootRotationUpdateTolerance = newValue; } if (options.ContainsKey("client-vel-upd")) { float newValue; // FIXME: This can only come from the console at the moment but might not always be true. if (ConsoleUtil.TryParseConsoleFloat(MainConsole.Instance, options["client-vel-upd"], out newValue)) m_scene.RootVelocityUpdateTolerance = newValue; } if (options.ContainsKey("root-upd-per")) { int newValue; // FIXME: This can only come from the console at the moment but might not always be true. if (ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, options["root-upd-per"], out newValue)) m_scene.RootTerseUpdatePeriod = newValue; } if (options.ContainsKey("child-upd-per")) { int newValue; // FIXME: This can only come from the console at the moment but might not always be true. if (ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, options["child-upd-per"], out newValue)) m_scene.ChildTerseUpdatePeriod = newValue; } if (options.ContainsKey("pbackup")) { bool active; if (bool.TryParse(options["pbackup"], out active)) m_scene.PeriodicBackup = active; } if (options.ContainsKey("scripting")) { bool enableScripts = true; if (bool.TryParse(options["scripting"], out enableScripts)) m_scene.ScriptsEnabled = enableScripts; } if (options.ContainsKey("physics")) { bool enablePhysics; if (bool.TryParse(options["physics"], out enablePhysics)) m_scene.PhysicsEnabled = enablePhysics; } // if (options.ContainsKey("collisions")) // { // // TODO: Implement. If false, should stop objects colliding, though possibly should still allow // // the avatar themselves to collide with the ground. // } if (options.ContainsKey("teleport")) { bool enableTeleportDebugging; if (bool.TryParse(options["teleport"], out enableTeleportDebugging)) m_scene.DebugTeleporting = enableTeleportDebugging; } if (options.ContainsKey("update-on-timer")) { bool enableUpdateOnTimer; if (bool.TryParse(options["update-on-timer"], out enableUpdateOnTimer)) { // m_scene.UpdateOnTimer = enableUpdateOnTimer; m_scene.Active = false; while (m_scene.IsRunning) Thread.Sleep(20); m_scene.Active = true; } } if (options.ContainsKey("updates")) { bool enableUpdateDebugging; if (bool.TryParse(options["updates"], out enableUpdateDebugging)) { m_scene.DebugUpdates = enableUpdateDebugging; GcNotify.Enabled = enableUpdateDebugging; } } } } }
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 XCLCMS.WebAPI.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().FullName, type.FullName)); } } 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().FullName, 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; } } }
#region License // // Copyright (c) 2018, Fluent Migrator Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Data; using FluentMigrator.Runner.Generators.SqlAnywhere; using NUnit.Framework; using Shouldly; namespace FluentMigrator.Tests.Unit.Generators.SqlAnywhere { [TestFixture] [Category("SqlAnywhere")] [Category("SqlAnywhere16")] public class SqlAnywhere16ConstraintsTests : BaseConstraintsTests { protected SqlAnywhere16Generator Generator; [SetUp] public void Setup() { Generator = new SqlAnywhere16Generator(); } [Test] public void CanAlterDefaultConstraintWithCurrentUserAsDefault() { var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression(); expression.DefaultValue = SystemMethods.CurrentUser; var expected = "ALTER TABLE [dbo].[TestTable1] ALTER [TestColumn1] DROP DEFAULT;" + Environment.NewLine + "-- create alter table command to create new default constraint as string and run it" + Environment.NewLine + "ALTER TABLE [dbo].[TestTable1] ALTER [TestColumn1] DEFAULT CURRENT USER;"; var result = Generator.Generate(expression); result.ShouldBe(expected); } [Test] public void CanAlterDefaultConstraintWithCurrentDateAsDefault() { var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression(); expression.DefaultValue = SystemMethods.CurrentDateTime; var expected = "ALTER TABLE [dbo].[TestTable1] ALTER [TestColumn1] DROP DEFAULT;" + Environment.NewLine + "-- create alter table command to create new default constraint as string and run it" + Environment.NewLine + "ALTER TABLE [dbo].[TestTable1] ALTER [TestColumn1] DEFAULT CURRENT TIMESTAMP;"; var result = Generator.Generate(expression); result.ShouldBe(expected); } [Test] public void CanAlterDefaultConstraintWithCurrentUtcDateAsDefault() { var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression(); expression.DefaultValue = SystemMethods.CurrentUTCDateTime; var expected = "ALTER TABLE [dbo].[TestTable1] ALTER [TestColumn1] DROP DEFAULT;" + Environment.NewLine + "-- create alter table command to create new default constraint as string and run it" + Environment.NewLine + "ALTER TABLE [dbo].[TestTable1] ALTER [TestColumn1] DEFAULT CURRENT UTC TIMESTAMP;"; var result = Generator.Generate(expression); result.ShouldBe(expected); } [Test] public void CanAlterDefaultConstraintWithNewGuidAsDefault() { var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression(); expression.DefaultValue = SystemMethods.NewGuid; var expected = "ALTER TABLE [dbo].[TestTable1] ALTER [TestColumn1] DROP DEFAULT;" + Environment.NewLine + "-- create alter table command to create new default constraint as string and run it" + Environment.NewLine + "ALTER TABLE [dbo].[TestTable1] ALTER [TestColumn1] DEFAULT NEWID();"; var result = Generator.Generate(expression); result.ShouldBe(expected); } [Test] public void CanAlterDefaultConstraintWithStringAsDefault() { var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression(); expression.DefaultValue = "TestString"; var expected = "ALTER TABLE [dbo].[TestTable1] ALTER [TestColumn1] DROP DEFAULT;" + Environment.NewLine + "-- create alter table command to create new default constraint as string and run it" + Environment.NewLine + "ALTER TABLE [dbo].[TestTable1] ALTER [TestColumn1] DEFAULT N'TestString';"; var result = Generator.Generate(expression); result.ShouldBe(expected); } [Test] public override void CanCreateForeignKeyWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateForeignKeyExpression(); expression.ForeignKey.ForeignTableSchema = "TestSchema"; expression.ForeignKey.PrimaryTableSchema = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [FK_TestTable1_TestColumn1_TestTable2_TestColumn2] FOREIGN KEY ([TestColumn1]) REFERENCES [TestSchema].[TestTable2] ([TestColumn2])"); } [Test] public override void CanCreateForeignKeyWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateForeignKeyExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [FK_TestTable1_TestColumn1_TestTable2_TestColumn2] FOREIGN KEY ([TestColumn1]) REFERENCES [dbo].[TestTable2] ([TestColumn2])"); } [Test] public override void CanCreateForeignKeyWithDifferentSchemas() { var expression = GeneratorTestHelper.GetCreateForeignKeyExpression(); expression.ForeignKey.ForeignTableSchema = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [FK_TestTable1_TestColumn1_TestTable2_TestColumn2] FOREIGN KEY ([TestColumn1]) REFERENCES [dbo].[TestTable2] ([TestColumn2])"); } [Test] public override void CanCreateMultiColumnForeignKeyWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression(); expression.ForeignKey.ForeignTableSchema = "TestSchema"; expression.ForeignKey.PrimaryTableSchema = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4] FOREIGN KEY ([TestColumn1], [TestColumn3]) REFERENCES [TestSchema].[TestTable2] ([TestColumn2], [TestColumn4])"); } [Test] public override void CanCreateMultiColumnForeignKeyWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4] FOREIGN KEY ([TestColumn1], [TestColumn3]) REFERENCES [dbo].[TestTable2] ([TestColumn2], [TestColumn4])"); } [Test] public override void CanCreateMultiColumnForeignKeyWithDifferentSchemas() { var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression(); expression.ForeignKey.ForeignTableSchema = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4] FOREIGN KEY ([TestColumn1], [TestColumn3]) REFERENCES [dbo].[TestTable2] ([TestColumn2], [TestColumn4])"); } [Test] public override void CanCreateMultiColumnPrimaryKeyConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateMultiColumnPrimaryKeyExpression(); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [PK_TestTable1_TestColumn1_TestColumn2] PRIMARY KEY ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateMultiColumnPrimaryKeyConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateMultiColumnPrimaryKeyExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [PK_TestTable1_TestColumn1_TestColumn2] PRIMARY KEY ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateMultiColumnUniqueConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateMultiColumnUniqueConstraintExpression(); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [UC_TestTable1_TestColumn1_TestColumn2] UNIQUE ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateMultiColumnUniqueConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateMultiColumnUniqueConstraintExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [UC_TestTable1_TestColumn1_TestColumn2] UNIQUE ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateNamedForeignKeyWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression(); expression.ForeignKey.ForeignTableSchema = "TestSchema"; expression.ForeignKey.PrimaryTableSchema = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [FK_Test] FOREIGN KEY ([TestColumn1]) REFERENCES [TestSchema].[TestTable2] ([TestColumn2])"); } [Test] public override void CanCreateNamedForeignKeyWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [FK_Test] FOREIGN KEY ([TestColumn1]) REFERENCES [dbo].[TestTable2] ([TestColumn2])"); } [Test] public override void CanCreateNamedForeignKeyWithDifferentSchemas() { var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression(); expression.ForeignKey.ForeignTableSchema = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [FK_Test] FOREIGN KEY ([TestColumn1]) REFERENCES [dbo].[TestTable2] ([TestColumn2])"); } [Test] public override void CanCreateNamedForeignKeyWithOnDeleteAndOnUpdateOptions() { var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression(); expression.ForeignKey.OnDelete = Rule.Cascade; expression.ForeignKey.OnUpdate = Rule.SetDefault; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [FK_Test] FOREIGN KEY ([TestColumn1]) REFERENCES [dbo].[TestTable2] ([TestColumn2]) ON DELETE CASCADE ON UPDATE SET DEFAULT"); } [TestCase(Rule.SetDefault, "SET DEFAULT"), TestCase(Rule.SetNull, "SET NULL"), TestCase(Rule.Cascade, "CASCADE")] public override void CanCreateNamedForeignKeyWithOnDeleteOptions(Rule rule, string output) { var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression(); expression.ForeignKey.OnDelete = rule; var result = Generator.Generate(expression); result.ShouldBe(string.Format("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [FK_Test] FOREIGN KEY ([TestColumn1]) REFERENCES [dbo].[TestTable2] ([TestColumn2]) ON DELETE {0}", output)); } [TestCase(Rule.SetDefault, "SET DEFAULT"), TestCase(Rule.SetNull, "SET NULL"), TestCase(Rule.Cascade, "CASCADE")] public override void CanCreateNamedForeignKeyWithOnUpdateOptions(Rule rule, string output) { var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression(); expression.ForeignKey.OnUpdate = rule; var result = Generator.Generate(expression); result.ShouldBe(string.Format("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [FK_Test] FOREIGN KEY ([TestColumn1]) REFERENCES [dbo].[TestTable2] ([TestColumn2]) ON UPDATE {0}", output)); } [Test] public override void CanCreateNamedMultiColumnForeignKeyWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression(); expression.ForeignKey.ForeignTableSchema = "TestSchema"; expression.ForeignKey.PrimaryTableSchema = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [FK_Test] FOREIGN KEY ([TestColumn1], [TestColumn3]) REFERENCES [TestSchema].[TestTable2] ([TestColumn2], [TestColumn4])"); } [Test] public override void CanCreateNamedMultiColumnForeignKeyWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [FK_Test] FOREIGN KEY ([TestColumn1], [TestColumn3]) REFERENCES [dbo].[TestTable2] ([TestColumn2], [TestColumn4])"); } [Test] public override void CanCreateNamedMultiColumnForeignKeyWithDifferentSchemas() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression(); expression.ForeignKey.ForeignTableSchema = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [FK_Test] FOREIGN KEY ([TestColumn1], [TestColumn3]) REFERENCES [dbo].[TestTable2] ([TestColumn2], [TestColumn4])"); } [Test] public override void CanCreateNamedMultiColumnPrimaryKeyConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression(); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [TESTPRIMARYKEY] PRIMARY KEY ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateNamedMultiColumnPrimaryKeyConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [TESTPRIMARYKEY] PRIMARY KEY ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateNamedMultiColumnUniqueConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression(); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [TESTUNIQUECONSTRAINT] UNIQUE ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateNamedMultiColumnUniqueConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [TESTUNIQUECONSTRAINT] UNIQUE ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateNamedPrimaryKeyConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression(); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [TESTPRIMARYKEY] PRIMARY KEY ([TestColumn1])"); } [Test] public override void CanCreateNamedPrimaryKeyConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [TESTPRIMARYKEY] PRIMARY KEY ([TestColumn1])"); } [Test] public override void CanCreateNamedUniqueConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression(); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [TESTUNIQUECONSTRAINT] UNIQUE ([TestColumn1])"); } [Test] public override void CanCreateNamedUniqueConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [TESTUNIQUECONSTRAINT] UNIQUE ([TestColumn1])"); } [Test] public override void CanCreatePrimaryKeyConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreatePrimaryKeyExpression(); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [PK_TestTable1_TestColumn1] PRIMARY KEY ([TestColumn1])"); } [Test] public override void CanCreatePrimaryKeyConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreatePrimaryKeyExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [PK_TestTable1_TestColumn1] PRIMARY KEY ([TestColumn1])"); } [Test] public override void CanCreateUniqueConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateUniqueConstraintExpression(); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD CONSTRAINT [UC_TestTable1_TestColumn1] UNIQUE ([TestColumn1])"); } [Test] public override void CanCreateUniqueConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateUniqueConstraintExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD CONSTRAINT [UC_TestTable1_TestColumn1] UNIQUE ([TestColumn1])"); } [Test] public override void CanDropForeignKeyWithCustomSchema() { var expression = GeneratorTestHelper.GetDeleteForeignKeyExpression(); expression.ForeignKey.ForeignTableSchema = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] DROP CONSTRAINT [FK_Test]"); } [Test] public override void CanDropForeignKeyWithDefaultSchema() { var expression = GeneratorTestHelper.GetDeleteForeignKeyExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] DROP CONSTRAINT [FK_Test]"); } [Test] public override void CanDropPrimaryKeyConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetDeletePrimaryKeyExpression(); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] DROP CONSTRAINT [TESTPRIMARYKEY]"); } [Test] public override void CanDropPrimaryKeyConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetDeletePrimaryKeyExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] DROP CONSTRAINT [TESTPRIMARYKEY]"); } [Test] public override void CanDropUniqueConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetDeleteUniqueConstraintExpression(); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] DROP CONSTRAINT [TESTUNIQUECONSTRAINT]"); } [Test] public override void CanDropUniqueConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetDeleteUniqueConstraintExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [dbo].[TestTable1] DROP CONSTRAINT [TESTUNIQUECONSTRAINT]"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Reflow.WebDemo.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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.Globalization; using System.Runtime.InteropServices; #if !FEATURE_SLJ_PROJECTION_COMPAT #pragma warning disable 436 // Redefining types from Windows.Foundation #endif // !FEATURE_SLJ_PROJECTION_COMPAT #if FEATURE_SLJ_PROJECTION_COMPAT namespace System.Windows #else // !FEATURE_SLJ_PROJECTION_COMPAT namespace Windows.Foundation #endif // FEATURE_SLJ_PROJECTION_COMPAT { // // Rect is the managed projection of Windows.Foundation.Rect. Any changes to the layout // of this type must be exactly mirrored on the native WinRT side as well. // // Note that this type is owned by the Jupiter team. Please contact them before making any // changes here. // [StructLayout(LayoutKind.Sequential)] public struct Rect : IFormattable { private float _x; private float _y; private float _width; private float _height; private const double EmptyX = Double.PositiveInfinity; private const double EmptyY = Double.PositiveInfinity; private const double EmptyWidth = Double.NegativeInfinity; private const double EmptyHeight = Double.NegativeInfinity; private readonly static Rect s_empty = CreateEmptyRect(); public Rect(double x, double y, double width, double height) { if (width < 0) throw new ArgumentException("width"); if (height < 0) throw new ArgumentException("height"); _x = (float)x; _y = (float)y; _width = (float)width; _height = (float)height; } public Rect(Point point1, Point point2) { _x = (float)Math.Min(point1.X, point2.X); _y = (float)Math.Min(point1.Y, point2.Y); _width = (float)Math.Max(Math.Max(point1.X, point2.X) - _x, 0); _height = (float)Math.Max(Math.Max(point1.Y, point2.Y) - _y, 0); } public Rect(Point location, Size size) { if (size.IsEmpty) { this = s_empty; } else { _x = (float)location.X; _y = (float)location.Y; _width = (float)size.Width; _height = (float)size.Height; } } internal static Rect Create(double x, double y, double width, double height) { if (x == EmptyX && y == EmptyY && width == EmptyWidth && height == EmptyHeight) { return Rect.Empty; } else { return new Rect(x, y, width, height); } } public double X { get { return _x; } set { _x = (float)value; } } public double Y { get { return _y; } set { _y = (float)value; } } public double Width { get { return _width; } set { if (value < 0) throw new ArgumentException("Width"); _width = (float)value; } } public double Height { get { return _height; } set { if (value < 0) throw new ArgumentException("Height"); _height = (float)value; } } public double Left { get { return _x; } } public double Top { get { return _y; } } public double Right { get { if (IsEmpty) { return Double.NegativeInfinity; } return _x + _width; } } public double Bottom { get { if (IsEmpty) { return Double.NegativeInfinity; } return _y + _height; } } public static Rect Empty { get { return s_empty; } } public bool IsEmpty { get { return _width < 0; } } public bool Contains(Point point) { return ContainsInternal(point.X, point.Y); } public void Intersect(Rect rect) { if (!this.IntersectsWith(rect)) { this = s_empty; } else { double left = Math.Max(X, rect.X); double top = Math.Max(Y, rect.Y); // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) Width = Math.Max(Math.Min(X + Width, rect.X + rect.Width) - left, 0); Height = Math.Max(Math.Min(Y + Height, rect.Y + rect.Height) - top, 0); X = left; Y = top; } } public void Union(Rect rect) { if (IsEmpty) { this = rect; } else if (!rect.IsEmpty) { double left = Math.Min(Left, rect.Left); double top = Math.Min(Top, rect.Top); // We need this check so that the math does not result in NaN if ((rect.Width == Double.PositiveInfinity) || (Width == Double.PositiveInfinity)) { Width = Double.PositiveInfinity; } else { // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) double maxRight = Math.Max(Right, rect.Right); Width = Math.Max(maxRight - left, 0); } // We need this check so that the math does not result in NaN if ((rect.Height == Double.PositiveInfinity) || (Height == Double.PositiveInfinity)) { Height = Double.PositiveInfinity; } else { // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) double maxBottom = Math.Max(Bottom, rect.Bottom); Height = Math.Max(maxBottom - top, 0); } X = left; Y = top; } } public void Union(Point point) { Union(new Rect(point, point)); } private bool ContainsInternal(double x, double y) { return ((x >= X) && (x - Width <= X) && (y >= Y) && (y - Height <= Y)); } internal bool IntersectsWith(Rect rect) { if (Width < 0 || rect.Width < 0) { return false; } return (rect.X <= X + Width) && (rect.X + rect.Width >= X) && (rect.Y <= Y + Height) && (rect.Y + rect.Height >= Y); } private static Rect CreateEmptyRect() { Rect rect = new Rect(); // TODO: for consistency with width/height we should change these // to assign directly to the backing fields. rect.X = EmptyX; rect.Y = EmptyY; // the width and height properties prevent assignment of // negative numbers so assign directly to the backing fields. rect._width = (float)EmptyWidth; rect._height = (float)EmptyHeight; return rect; } public override string ToString() { // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, null /* format provider */); } public string ToString(IFormatProvider provider) { // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, provider); } string IFormattable.ToString(string format, IFormatProvider provider) { // Delegate to the internal method which implements all ToString calls. return ConvertToString(format, provider); } internal string ConvertToString(string format, IFormatProvider provider) { if (IsEmpty) { return SR.DirectUI_Empty; } // Helper to get the numeric list separator for a given culture. char separator = TokenizerHelper.GetNumericListSeparator(provider); return String.Format(provider, "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}", separator, _x, _y, _width, _height); } public bool Equals(Rect value) { return (this == value); } public static bool operator ==(Rect rect1, Rect rect2) { return rect1.X == rect2.X && rect1.Y == rect2.Y && rect1.Width == rect2.Width && rect1.Height == rect2.Height; } public static bool operator !=(Rect rect1, Rect rect2) { return !(rect1 == rect2); } public override bool Equals(object o) { return o is Rect && this == (Rect)o; } public override int GetHashCode() { // Perform field-by-field XOR of HashCodes return X.GetHashCode() ^ Y.GetHashCode() ^ Width.GetHashCode() ^ Height.GetHashCode(); } } } #if !FEATURE_SLJ_PROJECTION_COMPAT #pragma warning restore 436 #endif // !FEATURE_SLJ_PROJECTION_COMPAT
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if LEGACYTELEMETRY using System; using System.Collections.Generic; using System.Diagnostics; using System.Management.Automation.Internal; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using System.Management.Automation.Language; using System.Threading; using System.Threading.Tasks; namespace Microsoft.PowerShell.Telemetry.Internal { /// <summary> /// </summary> [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public static class TelemetryAPI { #region Public API /// <summary> /// Public API to expose Telemetry in PowerShell /// Provide meaningful message. Ex: PSCONSOLE_START, PSRUNSPACE_START /// arguments are of anonymous type. Ex: new { PSVersion = "5.0", PSRemotingProtocolVersion = "2.2"} /// </summary> public static void TraceMessage<T>(string message, T arguments) { TelemetryWrapper.TraceMessage(message, arguments); } #endregion private static int s_anyPowerShellSessionOpen; private static DateTime s_sessionStartTime; private enum HostIsInteractive { Unknown, Interactive, NonInteractive } /// <summary> /// Called either after opening a runspace (the default), or by the host application. /// </summary> public static void ReportStartupTelemetry(IHostProvidesTelemetryData ihptd) { // Avoid reporting startup more than once, except if we report "exited" and // another runspace gets opened. if (Interlocked.CompareExchange(ref s_anyPowerShellSessionOpen, 1, 0) == 1) return; bool is32Bit = !Environment.Is64BitProcess; var psversion = PSVersionInfo.PSVersion.ToString(); var hostName = Process.GetCurrentProcess().ProcessName; if (ihptd != null) { TelemetryWrapper.TraceMessage("PSHostStart", new { Interactive = ihptd.HostIsInteractive ? HostIsInteractive.Interactive : HostIsInteractive.NonInteractive, ProfileLoadTime = ihptd.ProfileLoadTimeInMS, ReadyForInputTime = ihptd.ReadyForInputTimeInMS, Is32Bit = is32Bit, PSVersion = psversion, ProcessName = hostName, }); } else { TelemetryWrapper.TraceMessage("PSHostStart", new { Interactive = HostIsInteractive.Unknown, ProfileLoadTime = 0, ReadyForInputTime = 0, Is32Bit = is32Bit, PSVersion = psversion, ProcessName = hostName, }); } s_sessionStartTime = DateTime.Now; } /// <summary> /// Called after there are no more open runspaces. In some host applications, this could /// report multiple exits. /// </summary> public static void ReportExitTelemetry(IHostProvidesTelemetryData ihptd) { TelemetryWrapper.TraceMessage("PSHostStop", new { InteractiveCommandCount = ihptd != null ? ihptd.InteractiveCommandCount : 0, TabCompletionTimes = s_tabCompletionTimes, TabCompletionCounts = s_tabCompletionCounts, TabCompletionResultCounts = s_tabCompletionResultCounts, SessionTime = (DateTime.Now - s_sessionStartTime).TotalMilliseconds }); // In case a host opens another runspace, we will want another PSHostStart event, // so reset our flag here to allow that event to fire. s_anyPowerShellSessionOpen = 0; } /// <summary> /// Report Get-Help requests, how many results are returned, and how long it took. /// </summary> internal static void ReportGetHelpTelemetry(string name, int topicsFound, long timeInMS, bool updatedHelp) { TelemetryWrapper.TraceMessage("PSHelpRequest", new { TopicCount = topicsFound, TimeInMS = timeInMS, RanUpdateHelp = updatedHelp, HelpTopic = name, }); } /// <summary> /// Report when Get-Command fails to find something. /// </summary> internal static void ReportGetCommandFailed(string[] name, long timeInMS) { TelemetryWrapper.TraceMessage("PSGetCommandFailed", new { TimeInMS = timeInMS, CommandNames = name }); } private static long[] s_tabCompletionTimes = new long[(int)CompletionResultType.DynamicKeyword + 1]; private static int[] s_tabCompletionCounts = new int[(int)CompletionResultType.DynamicKeyword + 1]; private static int[] s_tabCompletionResultCounts = new int[(int)CompletionResultType.DynamicKeyword + 1]; internal static void ReportTabCompletionTelemetry(long elapsedMilliseconds, int count, CompletionResultType completionResultType) { // We'll collect some general statistics. int idx = (int)completionResultType; if (idx >= 0 && idx <= (int)CompletionResultType.DynamicKeyword) { s_tabCompletionTimes[idx] += elapsedMilliseconds; s_tabCompletionCounts[idx]++; s_tabCompletionResultCounts[idx] += count; } // Also write an event for any slow tab completion (> 250ms). if (elapsedMilliseconds > 250) { TelemetryWrapper.TraceMessage("PSSlowTabCompletion", new { Time = elapsedMilliseconds, Count = count, Type = completionResultType, }); } } /// <summary> /// Report that a module was loaded, but only do so for modules that *might* be authored by Microsoft. We can't /// be 100% certain, but we'll ignore non-Microsoft module names when looking at any data, so it's best to /// at least attempt avoiding collecting data we'll ignore. /// </summary> internal static void ReportModuleLoad(PSModuleInfo foundModule) { var modulePath = foundModule.Path; var companyName = foundModule.CompanyName; bool couldBeMicrosoftModule = (modulePath != null && (modulePath.StartsWith(Utils.DefaultPowerShellAppBase, StringComparison.OrdinalIgnoreCase) || // The following covers both 64 and 32 bit Program Files by assuming 32bit is just ...\Program Files + " (x86)" modulePath.StartsWith(Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles), StringComparison.OrdinalIgnoreCase))) || (companyName != null && foundModule.CompanyName.StartsWith("Microsoft", StringComparison.OrdinalIgnoreCase)); if (couldBeMicrosoftModule) { TelemetryWrapper.TraceMessage("PSImportModule", new { ModuleName = foundModule.Name, Version = foundModule.Version.ToString() }); } } /// <summary> /// Report that a new local session (runspace) is created. /// </summary> internal static void ReportLocalSessionCreated( System.Management.Automation.Runspaces.InitialSessionState iss, System.Management.Automation.Host.TranscriptionData transcriptionData) { bool isConstrained = (iss != null) && (iss.DefaultCommandVisibility != SessionStateEntryVisibility.Public) && (iss.LanguageMode != PSLanguageMode.FullLanguage); bool isTranscripting = (transcriptionData != null) && (transcriptionData.SystemTranscript != null); TelemetryWrapper.TraceMessage("PSNewLocalSession", new { Constrained = isConstrained, Transcripting = isTranscripting }); } private enum RemoteSessionType { Unknown, LocalProcess, WinRMRemote, HyperVRemote, ContainerRemote } private enum RemoteConfigurationType { Unknown, PSDefault, PSWorkflow, ServerManagerWorkflow, Custom } /// <summary> /// Report that a new remote session (runspace) is created. /// </summary> internal static void ReportRemoteSessionCreated( System.Management.Automation.Runspaces.RunspaceConnectionInfo connectionInfo) { RemoteSessionType sessionType = RemoteSessionType.Unknown; RemoteConfigurationType configurationType = RemoteConfigurationType.Unknown; if (connectionInfo is System.Management.Automation.Runspaces.NewProcessConnectionInfo) { sessionType = RemoteSessionType.LocalProcess; configurationType = RemoteConfigurationType.PSDefault; } else { System.Management.Automation.Runspaces.WSManConnectionInfo wsManConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.WSManConnectionInfo; if (wsManConnectionInfo != null) { sessionType = RemoteSessionType.WinRMRemote; // Parse configuration name from ShellUri: // ShellUri = 'http://schemas.microsoft.com/powershell/Microsoft.PowerShell' // ConfigName = 'Microsoft.PowerShell' string configurationName = wsManConnectionInfo.ShellUri; if (!string.IsNullOrEmpty(configurationName)) { int index = configurationName.LastIndexOf('/'); if (index > -1) { configurationName = configurationName.Substring(index + 1); } } configurationType = GetConfigurationTypefromName(configurationName); } else { System.Management.Automation.Runspaces.VMConnectionInfo vmConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.VMConnectionInfo; if (vmConnectionInfo != null) { sessionType = RemoteSessionType.HyperVRemote; configurationType = GetConfigurationTypefromName(vmConnectionInfo.ConfigurationName); } else { System.Management.Automation.Runspaces.ContainerConnectionInfo containerConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.ContainerConnectionInfo; if (containerConnectionInfo != null) { sessionType = RemoteSessionType.ContainerRemote; configurationType = GetConfigurationTypefromName( (containerConnectionInfo.ContainerProc != null) ? containerConnectionInfo.ContainerProc.ConfigurationName : string.Empty); } } } } TelemetryWrapper.TraceMessage("PSNewRemoteSession", new { Type = sessionType, Configuration = configurationType }); } private static RemoteConfigurationType GetConfigurationTypefromName(string name) { string configName = (name != null) ? name.Trim() : string.Empty; if (string.IsNullOrEmpty(configName) || configName.Equals("microsoft.powershell", StringComparison.OrdinalIgnoreCase) || configName.Equals("microsoft.powershell32", StringComparison.OrdinalIgnoreCase)) { return RemoteConfigurationType.PSDefault; } else if (configName.Equals("microsoft.powershell.workflow", StringComparison.OrdinalIgnoreCase)) { return RemoteConfigurationType.PSWorkflow; } else if (configName.Equals("microsoft.windows.servermanagerworkflows", StringComparison.OrdinalIgnoreCase)) { return RemoteConfigurationType.ServerManagerWorkflow; } else { return RemoteConfigurationType.Custom; } } private enum ScriptFileType { None = 0, Ps1 = 1, Psd1 = 2, Psm1 = 3, Other = 4, } private static readonly int s_promptHashCode = "prompt".GetHashCode(); /// <summary> /// Report some telemetry about the scripts that are run. /// </summary> internal static void ReportScriptTelemetry(Ast ast, bool dotSourced, long compileTimeInMS) { if (ast.Parent != null || !TelemetryWrapper.IsEnabled) return; Task.Run(() => { var extent = ast.Extent; var text = extent.Text; var hash = text.GetHashCode(); // Ignore 'prompt' so we don't generate an event for every 'prompt' that is invoked. // (We really should only create 'prompt' once, but we don't. if (hash == s_promptHashCode) return; var visitor = new ScriptBlockTelemetry(); ast.Visit(visitor); var scriptFileType = ScriptFileType.None; var fileName = extent.File; if (fileName != null) { var ext = System.IO.Path.GetExtension(fileName); if (".ps1".Equals(ext, StringComparison.OrdinalIgnoreCase)) { scriptFileType = ScriptFileType.Ps1; } else if (".psd1".Equals(ext, StringComparison.OrdinalIgnoreCase)) { scriptFileType = ScriptFileType.Psd1; } else if (".psm1".Equals(ext, StringComparison.OrdinalIgnoreCase)) { scriptFileType = ScriptFileType.Psm1; } else { // Reachable? scriptFileType = ScriptFileType.Other; } } TelemetryWrapper.TraceMessage("PSScriptDetails", new { Hash = hash, IsDotSourced = dotSourced, ScriptFileType = scriptFileType, Length = text.Length, LineCount = extent.EndLineNumber - extent.StartLineNumber, CompileTimeInMS = compileTimeInMS, StatementCount = visitor.StatementCount, CountOfCommands = visitor.CountOfCommands, CountOfDotSourcedCommands = visitor.CountOfDotSourcedCommands, MaxArrayLength = visitor.MaxArraySize, ArrayLiteralCount = visitor.ArrayLiteralCount, ArrayLiteralCumulativeSize = visitor.ArrayLiteralCumulativeSize, MaxStringLength = visitor.MaxStringSize, StringLiteralCount = visitor.StringLiteralCount, StringLiteralCumulativeSize = visitor.StringLiteralCumulativeSize, MaxPipelineDepth = visitor.MaxPipelineDepth, PipelineCount = visitor.PipelineCount, FunctionCount = visitor.FunctionCount, ScriptBlockCount = visitor.ScriptBlockCount, ClassCount = visitor.ClassCount, EnumCount = visitor.EnumCount, CommandsCalled = visitor.CommandsCalled, }); }); } } internal class ScriptBlockTelemetry : AstVisitor2 { internal ScriptBlockTelemetry() { CommandsCalled = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); } internal Dictionary<string, int> CommandsCalled { get; private set; } internal int CountOfCommands { get; private set; } internal int CountOfDotSourcedCommands { get; private set; } public override AstVisitAction VisitCommand(CommandAst commandAst) { CountOfCommands++; var commandName = commandAst.GetCommandName(); if (commandName != null) { int commandCount; CommandsCalled.TryGetValue(commandName, out commandCount); CommandsCalled[commandName] = commandCount + 1; } if (commandAst.InvocationOperator == TokenKind.Dot) CountOfDotSourcedCommands++; return AstVisitAction.Continue; } internal int MaxStringSize { get; private set; } internal int StringLiteralCount { get; private set; } internal int StringLiteralCumulativeSize { get; private set; } public override AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) { var stringSize = stringConstantExpressionAst.Value.Length; StringLiteralCount += 1; StringLiteralCumulativeSize += stringSize; MaxStringSize = Math.Max(MaxStringSize, stringSize); return AstVisitAction.Continue; } public override AstVisitAction VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) { var stringSize = expandableStringExpressionAst.Value.Length; StringLiteralCount += 1; StringLiteralCumulativeSize += stringSize; MaxStringSize = Math.Max(MaxStringSize, stringSize); return AstVisitAction.Continue; } internal int MaxArraySize { get; private set; } internal int ArrayLiteralCount { get; private set; } internal int ArrayLiteralCumulativeSize { get; private set; } public override AstVisitAction VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) { var elementCount = arrayLiteralAst.Elements.Count; ArrayLiteralCount += 1; ArrayLiteralCumulativeSize += elementCount; MaxArraySize = Math.Max(MaxArraySize, elementCount); return AstVisitAction.Continue; } internal int StatementCount { get; private set; } public override AstVisitAction VisitBlockStatement(BlockStatementAst blockStatementAst) { StatementCount += blockStatementAst.Body.Statements.Count; return AstVisitAction.Continue; } public override AstVisitAction VisitNamedBlock(NamedBlockAst namedBlockAst) { StatementCount += namedBlockAst.Statements.Count; return AstVisitAction.Continue; } internal int FunctionCount { get; private set; } public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { FunctionCount += 1; return AstVisitAction.Continue; } internal int ScriptBlockCount { get; private set; } public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { ScriptBlockCount += 1; return AstVisitAction.Continue; } internal int MaxPipelineDepth { get; private set; } internal int PipelineCount { get; private set; } public override AstVisitAction VisitPipeline(PipelineAst pipelineAst) { MaxPipelineDepth = Math.Max(MaxPipelineDepth, pipelineAst.PipelineElements.Count); PipelineCount += 1; return AstVisitAction.Continue; } internal int ClassCount { get; private set; } internal int EnumCount { get; private set; } public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) { if (typeDefinitionAst.IsClass) ClassCount += 1; else if (typeDefinitionAst.IsEnum) EnumCount += 1; return AstVisitAction.Continue; } } /// <summary> /// If implemented by the host, the host should call <see cref="TelemetryAPI.ReportStartupTelemetry"/> and <see cref="TelemetryAPI.ReportExitTelemetry"/> /// and track the data defined by this interface. /// </summary> public interface IHostProvidesTelemetryData { /// <summary>A host sets this property as appropriate - used when reporting telemetry.</summary> bool HostIsInteractive { get; } /// <summary>A host sets this property as appropriate - used when reporting telemetry.</summary> double ProfileLoadTimeInMS { get; } /// <summary>A host sets this property as appropriate - used when reporting telemetry.</summary> double ReadyForInputTimeInMS { get; } /// <summary>A host sets this property as appropriate - used when reporting telemetry.</summary> int InteractiveCommandCount { get; } } } #endif
using System.Diagnostics; namespace Community.CsharpSqlite { using sqlite3_stmt = Sqlite3.Vdbe; public partial class Sqlite3 { /* ** 2007 May 1 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code used to implement incremental BLOB I/O. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#include "sqliteInt.h" //#include "vdbeInt.h" #if NOT_SQLITE_OMIT_INCRBLOB //#if !SQLITE_OMIT_INCRBLOB /* ** Valid sqlite3_blob* handles point to Incrblob structures. */ typedef struct Incrblob Incrblob; struct Incrblob { int flags; /* Copy of "flags" passed to sqlite3_blob_open() */ int nByte; /* Size of open blob, in bytes */ int iOffset; /* Byte offset of blob in cursor data */ BtCursor *pCsr; /* Cursor pointing at blob row */ sqlite3_stmt *pStmt; /* Statement holding cursor open */ sqlite3 db; /* The associated database */ }; /* ** Open a blob handle. */ int sqlite3_blob_open( sqlite3* db, /* The database connection */ string zDb, /* The attached database containing the blob */ string zTable, /* The table containing the blob */ string zColumn, /* The column containing the blob */ sqlite_int64 iRow, /* The row containing the glob */ int flags, /* True -> read/write access, false -> read-only */ sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */ ){ int nAttempt = 0; int iCol; /* Index of zColumn in row-record */ /* This VDBE program seeks a btree cursor to the identified ** db/table/row entry. The reason for using a vdbe program instead ** of writing code to use the b-tree layer directly is that the ** vdbe program will take advantage of the various transaction, ** locking and error handling infrastructure built into the vdbe. ** ** After seeking the cursor, the vdbe executes an OP_ResultRow. ** Code external to the Vdbe then "borrows" the b-tree cursor and ** uses it to implement the blob_read(), blob_write() and ** blob_bytes() functions. ** ** The sqlite3_blob_close() function finalizes the vdbe program, ** which closes the b-tree cursor and (possibly) commits the ** transaction. */ static const VdbeOpList openBlob[] = { {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */ {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */ {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */ /* One of the following two instructions is replaced by an OP_Noop. */ {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */ {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */ {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */ {OP_NotExists, 0, 9, 1}, /* 6: Seek the cursor */ {OP_Column, 0, 0, 1}, /* 7 */ {OP_ResultRow, 1, 0, 0}, /* 8 */ {OP_Close, 0, 0, 0}, /* 9 */ {OP_Halt, 0, 0, 0}, /* 10 */ }; Vdbe *v = 0; int rc = SQLITE_OK; string zErr = 0; Table *pTab; Parse *pParse; *ppBlob = 0; sqlite3_mutex_enter(db->mutex); pParse = sqlite3StackAllocRaw(db, sizeof(*pParse)); if( pParse==0 ){ rc = SQLITE_NOMEM; goto blob_open_out; } do { memset(pParse, 0, sizeof(Parse)); pParse->db = db; sqlite3BtreeEnterAll(db); pTab = sqlite3LocateTable(pParse, 0, zTable, zDb); if( pTab && IsVirtual(pTab) ){ pTab = 0; sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable); } #if !SQLITE_OMIT_VIEW if( pTab && pTab->pSelect ){ pTab = 0; sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable); } #endif if( null==pTab ){ if( pParse->zErrMsg ){ sqlite3DbFree(db, zErr); zErr = pParse->zErrMsg; pParse->zErrMsg = 0; } rc = SQLITE_ERROR; sqlite3BtreeLeaveAll(db); goto blob_open_out; } /* Now search pTab for the exact column. */ for(iCol=0; iCol < pTab->nCol; iCol++) { if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){ break; } } if( iCol==pTab->nCol ){ sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn); rc = SQLITE_ERROR; sqlite3BtreeLeaveAll(db); goto blob_open_out; } /* If the value is being opened for writing, check that the ** column is not indexed, and that it is not part of a foreign key. ** It is against the rules to open a column to which either of these ** descriptions applies for writing. */ if( flags ){ string zFault = 0; Index *pIdx; #if !SQLITE_OMIT_FOREIGN_KEY if( db->flags&SQLITE_ForeignKeys ){ /* Check that the column is not part of an FK child key definition. It ** is not necessary to check if it is part of a parent key, as parent ** key columns must be indexed. The check below will pick up this ** case. */ FKey *pFKey; for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ int j; for(j=0; j<pFKey->nCol; j++){ if( pFKey->aCol[j].iFrom==iCol ){ zFault = "foreign key"; } } } } #endif for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int j; for(j=0; j<pIdx->nColumn; j++){ if( pIdx->aiColumn[j]==iCol ){ zFault = "indexed"; } } } if( zFault ){ sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault); rc = SQLITE_ERROR; sqlite3BtreeLeaveAll(db); goto blob_open_out; } } v = sqlite3VdbeCreate(db); if( v ){ int iDb = sqlite3SchemaToIndex(db, pTab->pSchema); sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob); flags = !!flags; /* flags = (flags ? 1 : 0); */ /* Configure the OP_Transaction */ sqlite3VdbeChangeP1(v, 0, iDb); sqlite3VdbeChangeP2(v, 0, flags); /* Configure the OP_VerifyCookie */ sqlite3VdbeChangeP1(v, 1, iDb); sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie); sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration); /* Make sure a mutex is held on the table to be accessed */ sqlite3VdbeUsesBtree(v, iDb); /* Configure the OP_TableLock instruction */ #if !NO_SQLITE_OMIT_SHARED_CACHE sqlite3VdbeChangeToNoop(v, 2, 1); #else sqlite3VdbeChangeP1(v, 2, iDb); sqlite3VdbeChangeP2(v, 2, pTab->tnum); sqlite3VdbeChangeP3(v, 2, flags); sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT); #endif /* Remove either the OP_OpenWrite or OpenRead. Set the P2 ** parameter of the other to pTab->tnum. */ sqlite3VdbeChangeToNoop(v, 4 - flags, 1); sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum); sqlite3VdbeChangeP3(v, 3 + flags, iDb); /* Configure the number of columns. Configure the cursor to ** think that the table has one more column than it really ** does. An OP_Column to retrieve this imaginary column will ** always return an SQL NULL. This is useful because it means ** we can invoke OP_Column to fill in the vdbe cursors type ** and offset cache without causing any IO. */ sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32); sqlite3VdbeChangeP2(v, 7, pTab->nCol); if( null==db->mallocFailed ){ pParse->nVar = 1; pParse->nMem = 1; pParse->nTab = 1; sqlite3VdbeMakeReady(v, pParse); } } sqlite3BtreeLeaveAll(db); goto blob_open_out; } sqlite3_bind_int64((sqlite3_stmt )v, 1, iRow); rc = sqlite3_step((sqlite3_stmt )v); if( rc!=SQLITE_ROW ){ nAttempt++; rc = sqlite3_finalize((sqlite3_stmt )v); sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, sqlite3_errmsg(db)); v = 0; } } while( nAttempt<5 && rc==SQLITE_SCHEMA ); if( rc==SQLITE_ROW ){ /* The row-record has been opened successfully. Check that the ** column in question contains text or a blob. If it contains ** text, it is up to the caller to get the encoding right. */ Incrblob *pBlob; u32 type = v->apCsr[0]->aType[iCol]; if( type<12 ){ sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, "cannot open value of type %s", type==0?"null": type==7?"real": "integer" ); rc = SQLITE_ERROR; goto blob_open_out; } pBlob = (Incrblob )sqlite3DbMallocZero(db, sizeof(Incrblob)); if( db->mallocFailed ){ sqlite3DbFree(db, ref pBlob); goto blob_open_out; } pBlob->flags = flags; pBlob->pCsr = v->apCsr[0]->pCursor; sqlite3BtreeEnterCursor(pBlob->pCsr); sqlite3BtreeCacheOverflow(pBlob->pCsr); sqlite3BtreeLeaveCursor(pBlob->pCsr); pBlob->pStmt = (sqlite3_stmt )v; pBlob->iOffset = v->apCsr[0]->aOffset[iCol]; pBlob->nByte = sqlite3VdbeSerialTypeLen(type); pBlob->db = db; *ppBlob = (sqlite3_blob )pBlob; rc = SQLITE_OK; }else if( rc==SQLITE_OK ){ sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow); rc = SQLITE_ERROR; } blob_open_out: if( v && (rc!=SQLITE_OK || db->mallocFailed) ){ sqlite3VdbeFinalize(v); } sqlite3Error(db, rc, zErr); sqlite3DbFree(db, zErr); sqlite3StackFree(db, pParse); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Close a blob handle that was previously created using ** sqlite3_blob_open(). */ int sqlite3_blob_close(sqlite3_blob *pBlob){ Incrblob *p = (Incrblob )pBlob; int rc; sqlite3 db; if( p ){ db = p->db; sqlite3_mutex_enter(db->mutex); rc = sqlite3_finalize(p->pStmt); sqlite3DbFree(db, ref p); sqlite3_mutex_leave(db->mutex); }else{ rc = SQLITE_OK; } return rc; } /* ** Perform a read or write operation on a blob */ static int blobReadWrite( sqlite3_blob *pBlob, void *z, int n, int iOffset, int (*xCall)(BtCursor*, u32, u32, void) ){ int rc; Incrblob *p = (Incrblob )pBlob; Vdbe *v; sqlite3 db; if( p==0 ) return SQLITE_MISUSE_BKPT(); db = p->db; sqlite3_mutex_enter(db->mutex); v = (Vdbe)p->pStmt; if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){ /* Request is out of range. Return a transient error. */ rc = SQLITE_ERROR; sqlite3Error(db, SQLITE_ERROR, 0); } else if( v==0 ){ /* If there is no statement handle, then the blob-handle has ** already been invalidated. Return SQLITE_ABORT in this case. */ rc = SQLITE_ABORT; }else{ /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is ** returned, clean-up the statement handle. */ Debug.Assert( db == v->db ); sqlite3BtreeEnterCursor(p->pCsr); rc = xCall(p->pCsr, iOffset+p->iOffset, n, z); sqlite3BtreeLeaveCursor(p->pCsr); if( rc==SQLITE_ABORT ){ sqlite3VdbeFinalize(v); p->pStmt = null; }else{ db->errCode = rc; v->rc = rc; } } rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Read data from a blob handle. */ int sqlite3_blob_read(sqlite3_blob *pBlob, object *z, int n, int iOffset){ return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData); } /* ** Write data to a blob handle. */ int sqlite3_blob_write(sqlite3_blob *pBlob, string z, int n, int iOffset){ return blobReadWrite(pBlob, (void )z, n, iOffset, sqlite3BtreePutData); } /* ** Query a blob handle for the size of the data. ** ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob ** so no mutex is required for access. */ int sqlite3_blob_bytes(sqlite3_blob *pBlob){ Incrblob *p = (Incrblob )pBlob; return p ? p->nByte : 0; } #endif // * #if NOT_SQLITE_OMIT_INCRBLOB //#if !SQLITE_OMIT_INCRBLOB */ } }
using System; using System.Collections.Generic; using System.Fabric; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Castle.DynamicProxy; using FG.Common.Utils; using FG.ServiceFabric.Actors.State; using FG.ServiceFabric.Testing.Mocks.Actors.Runtime; using Microsoft.ServiceFabric.Actors; using Microsoft.ServiceFabric.Actors.Client; using Microsoft.ServiceFabric.Actors.Runtime; using Microsoft.ServiceFabric.Services.Client; using Microsoft.ServiceFabric.Services.Communication.Client; using Microsoft.ServiceFabric.Services.Remoting; using Microsoft.ServiceFabric.Services.Remoting.Client; namespace FG.ServiceFabric.Testing.Mocks.Actors.Client { public class MockActorProxyFactory : IActorProxyFactory { private readonly MockFabricRuntime _fabricRuntime; private readonly IDictionary<Type, IActorStateProvider> _actorStateProviders; private readonly IList<IMockableActorRegistration> _actorRegistrations; private readonly IDictionary<object, object> _actorProxies; public MockActorProxyFactory( MockFabricRuntime fabricRuntime, params IMockableActorRegistration[] actorRegistrations ) { _fabricRuntime = fabricRuntime; _actorRegistrations = new List<IMockableActorRegistration>(actorRegistrations); _actorStateProviders = new Dictionary<Type, IActorStateProvider>(); _actorProxies = new Dictionary<object, object>(); } private IActorStateProvider GetOrCreateActorStateProvider(Type actorImplementationType, Func<IActorStateProvider> createStateProvider) { var actorStateProvider = GetActorStateProvider(actorImplementationType); if (actorStateProvider != null) return actorStateProvider; actorStateProvider = createStateProvider(); var migrationContainerType = GetMigrationContainerType(actorImplementationType); if (migrationContainerType != null) { var migrationContainer = (IMigrationContainer)Activator.CreateInstance(migrationContainerType); actorStateProvider = new VersionedStateProvider(actorStateProvider, migrationContainer); } _actorStateProviders.Add(actorImplementationType, actorStateProvider); return actorStateProvider; } public IActorStateProvider GetActorStateProvider(Type actorImplementationType) { if (_actorStateProviders.ContainsKey(actorImplementationType)) { return _actorStateProviders[actorImplementationType]; } return null; } private ActorService GetMockActorService( StatefulServiceContext serviceContext, ActorTypeInformation actorTypeInformation, IActorStateProvider actorStateProvider, Func<ActorBase, IActorStateProvider, IActorStateManager> stateManagerFactory) { return (ActorService)new MockActorService( codePackageActivationContext: _fabricRuntime.CodePackageContext, serviceProxyFactory: _fabricRuntime.ServiceProxyFactory, actorProxyFactory: _fabricRuntime.ActorProxyFactory, nodeContext: _fabricRuntime.BuildNodeContext(), statefulServiceContext: serviceContext, actorTypeInfo: actorTypeInformation, stateManagerFactory: stateManagerFactory, stateProvider: actorStateProvider); } private Type GetMigrationContainerType(Type actorType) { var versionedStateDeclaration = actorType.GetInterface(typeof(IVersionedState<>).Name); if (versionedStateDeclaration == null) return null; var migrationContainerType = versionedStateDeclaration.GetGenericArguments().Single(); return migrationContainerType; } private class InterceptorSelector : IInterceptorSelector { public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors) { if (method.DeclaringType == typeof(IActorProxy)) { return interceptors.Where(i => (i is ActorProxyInterceptor)).ToArray(); } return interceptors.Where(i => (i is ActorInterceptor)).ToArray(); } } private class ActorInterceptor : IInterceptor { private readonly Action<IActor, string> _preMethod; private readonly Action<IActor, string> _postMethod; public ActorInterceptor(Action<IActor, string> preMethod, Action<IActor, string> postMethod) { _preMethod = preMethod; _postMethod = postMethod; } public void Intercept(IInvocation invocation) { _preMethod?.Invoke(invocation.Proxy as IActor, invocation.Method.Name); invocation.Proceed(); _postMethod?.Invoke(invocation.Proxy as IActor, invocation.Method.Name); } } private class ActorProxyInterceptor : IInterceptor { private readonly IActorProxy _actorProxy; public ActorProxyInterceptor(IActorProxy actorProxy) { _actorProxy = actorProxy; } public void Intercept(IInvocation invocation) { invocation.ReturnValue = invocation.Method.Invoke(_actorProxy, invocation.Arguments); } } private class MockActorProxy : IActorProxy { public MockActorProxy( ActorId actorId, Uri serviceUri, ServicePartitionKey partitionKey, TargetReplicaSelector replicaSelector, string listenerName, ICommunicationClientFactory<IServiceRemotingClient> factory) { ActorId = actorId; ActorServicePartitionClient = new MockActorServicePartitionClient(actorId, serviceUri, partitionKey, replicaSelector, listenerName, factory); } public ActorId ActorId { get; } public IActorServicePartitionClient ActorServicePartitionClient { get; } private class MockActorServicePartitionClient : IActorServicePartitionClient { internal MockActorServicePartitionClient( ActorId actorId, Uri serviceUri, ServicePartitionKey partitionKey, TargetReplicaSelector replicaSelector, string listenerName, ICommunicationClientFactory<IServiceRemotingClient> factory) { ActorId = actorId; ServiceUri = serviceUri; PartitionKey = partitionKey; TargetReplicaSelector = replicaSelector; ListenerName = listenerName; Factory = factory; } public bool TryGetLastResolvedServicePartition(out ResolvedServicePartition resolvedServicePartition) { throw new NotImplementedException(); } public Uri ServiceUri { get; } public ServicePartitionKey PartitionKey { get; } public TargetReplicaSelector TargetReplicaSelector { get; } public string ListenerName { get; } public ICommunicationClientFactory<IServiceRemotingClient> Factory { get; } public ActorId ActorId { get; } } } private object CreateDynamicProxy<TActorInterface>(object target, IActorProxy actorProxy) where TActorInterface : IActor { var generator = new ProxyGenerator(new PersistentProxyBuilder()); var selector = new InterceptorSelector(); var actorInterceptor = new ActorInterceptor(PreActorMethod, PostActorMethod); var actorProxyInterceptor = new ActorProxyInterceptor(actorProxy); var options = new ProxyGenerationOptions() { Selector = selector }; var proxy = generator.CreateInterfaceProxyWithTarget(typeof(TActorInterface), new Type[] { typeof(IActorProxy) }, target, options, actorInterceptor, actorProxyInterceptor); return proxy; } private async Task<TActorInterface> Create<TActorInterface>(ActorId actorId) where TActorInterface : IActor { var actorRegistration = _actorRegistrations.FirstOrDefault(ar => ar.InterfaceType == typeof(TActorInterface)); if (actorRegistration == null) { throw new ArgumentException($"Expected a MockableActorRegistration for the type {typeof(TActorInterface).Name}"); } if (actorRegistration.ImplementationType != null && actorRegistration.ImplementationType.IsSubclassOf(typeof(Actor))) { var actorServiceName = $"{actorRegistration.ImplementationType.Name}Service"; var createStateProvider = actorRegistration.CreateStateProvider ?? (() => (IActorStateProvider)new MockActorStateProvider(_fabricRuntime)); var actorStateProvider = GetOrCreateActorStateProvider(actorRegistration.ImplementationType, () => createStateProvider()); var actorTypeInformation = ActorTypeInformation.Get(actorRegistration.ImplementationType); var statefulServiceContext = _fabricRuntime.BuildStatefulServiceContext(actorServiceName); var stateManagerFactory = actorRegistration.CreateStateManager != null ? (Func<ActorBase, IActorStateProvider, IActorStateManager>) ( (actor, stateProvider) => actorRegistration.CreateStateManager(actor, stateProvider)) : null; var actorServiceFactory = actorRegistration.CreateActorService ?? GetMockActorService; var actorService = actorServiceFactory(statefulServiceContext, actorTypeInformation, actorStateProvider, stateManagerFactory); if (actorService is FG.ServiceFabric.Actors.Runtime.ActorService) { actorService.SetPrivateField("_serviceProxyFactory", _fabricRuntime.ServiceProxyFactory); actorService.SetPrivateField("_actorProxyFactory", _fabricRuntime.ActorProxyFactory); actorService.SetPrivateField("_applicationUriBuilder", _fabricRuntime.ApplicationUriBuilder); } var target = actorRegistration.Activator(actorService, actorId); var mockableTarget = (FG.ServiceFabric.Actors.Runtime.ActorBase)(target as FG.ServiceFabric.Actors.Runtime.ActorBase); if (mockableTarget != null) { mockableTarget.SetPrivateField("_serviceProxyFactory", _fabricRuntime.ServiceProxyFactory); mockableTarget.SetPrivateField("_actorProxyFactory", _fabricRuntime.ActorProxyFactory); mockableTarget.SetPrivateField("_applicationUriBuilder", _fabricRuntime.ApplicationUriBuilder); } target.CallPrivateMethod("OnActivateAsync"); await actorStateProvider.ActorActivatedAsync(actorId); var serviceUri = _fabricRuntime.ApplicationUriBuilder.Build(actorServiceName).ToUri(); var actorProxy = new MockActorProxy(actorId, serviceUri, ServicePartitionKey.Singleton, TargetReplicaSelector.Default, "", null); var proxy = /*TryCreateDynamicProxy(typeof(TActorInterface), target, actorProxy);*/ CreateDynamicProxy<TActorInterface>(target, actorProxy); _actorProxies.Add(proxy.GetHashCode(), target); return (TActorInterface)proxy; } else { var target = actorRegistration.Activator(null, actorId); return (TActorInterface)target; } } public TActor GetActor<TActor>(IActor proxy) where TActor : class { if (_actorProxies.ContainsKey(proxy.GetHashCode())) { return _actorProxies[proxy.GetHashCode()] as TActor; } return null; } private void PreActorMethod(IActor proxy, string method) { var actor = GetActor<Actor>(proxy); if (actor == null) return; Console.WriteLine(); var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Green; var message = $"Actor {actor?.GetType().Name} '{actor?.Id}'({actor?.GetHashCode()}) {method} activating"; Console.WriteLine($"{message.PadRight(80, '=')}"); Console.ForegroundColor = color; } private void PostActorMethod(IActor proxy, string method) { var actor = GetActor<Actor>(proxy); if (actor == null) return; var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; var message = $"Actor {actor?.GetType().Name} '{actor?.Id}'({actor?.GetHashCode()}) {method} terminating"; Console.WriteLine($"{message.PadRight(80, '=')}"); Console.ForegroundColor = color; Console.WriteLine(); var saveStateTask = actor.StateManager.SaveStateAsync(CancellationToken.None); saveStateTask.Wait(CancellationToken.None); } public void AddActorRegistration(IMockableActorRegistration actorRegistration) { _actorRegistrations.Add(actorRegistration); } public TActorInterface CreateActorProxy<TActorInterface>(ActorId actorId, string applicationName = null, string serviceName = null, string listenerName = null) where TActorInterface : IActor { var task = Create<TActorInterface>(actorId); task.Wait(); return task.Result; } public TActorInterface CreateActorProxy<TActorInterface>(Uri serviceUri, ActorId actorId, string listenerName = null) where TActorInterface : IActor { var task = Create<TActorInterface>(actorId); task.Wait(); return task.Result; } private TServiceInterface CreateActorService<TServiceInterface>() where TServiceInterface : IService { var actorRegistration = _actorRegistrations.FirstOrDefault( registration => GetActorServiceImplementationType<TServiceInterface>(registration).Any()); if (actorRegistration == null) { throw new ArgumentException( $"Expected a MockableActorRegistration with ActorServiceType for the type {typeof(TServiceInterface).Name}"); } var createStateProvider = actorRegistration.CreateStateProvider ?? (() => (IActorStateProvider) new MockActorStateProvider(_fabricRuntime)); var actorServiceName = GetActorServiceImplementationType<TServiceInterface>(actorRegistration).First().Name; //todo: actor service can be named differently var actorStateProvider = GetOrCreateActorStateProvider(actorRegistration.ImplementationType, () => createStateProvider()); var actorTypeInformation = ActorTypeInformation.Get(actorRegistration.ImplementationType); var statefulServiceContext = _fabricRuntime.BuildStatefulServiceContext(actorServiceName); var stateManagerFactory = actorRegistration.CreateStateManager != null ? (Func<ActorBase, IActorStateProvider, IActorStateManager>) ( (actor, stateProvider) => actorRegistration.CreateStateManager(actor, stateProvider)) : null; var actorServiceFactory = actorRegistration.CreateActorService ?? GetMockActorService; var actorService = actorServiceFactory(statefulServiceContext, actorTypeInformation, actorStateProvider, stateManagerFactory); if (actorService is FG.ServiceFabric.Actors.Runtime.ActorService) { actorService.SetPrivateField("_serviceProxyFactory", _fabricRuntime.ServiceProxyFactory); actorService.SetPrivateField("_actorProxyFactory", _fabricRuntime.ActorProxyFactory); actorService.SetPrivateField("_applicationUriBuilder", _fabricRuntime.ApplicationUriBuilder); } return (TServiceInterface) (object) actorService; } private static IEnumerable<Type> GetActorServiceImplementationType<TServiceInterface>(IMockableActorRegistration registration) where TServiceInterface : IService { return registration.GetType().GetGenericArguments().Where(a => a.ImplementsInterface(typeof(TServiceInterface))); } public TServiceInterface CreateActorServiceProxy<TServiceInterface>(Uri actorServiceUri, ActorId actorId, string listenerName = null) where TServiceInterface : IService { return CreateActorService<TServiceInterface>(); } public TServiceInterface CreateActorServiceProxy<TServiceInterface>(Uri serviceUri, long partitionKey, string listenerName = null) where TServiceInterface : IService { return CreateActorService<TServiceInterface>(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace ODataValidator.Rule { using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Xml; using System.Xml.XPath; using ODataValidator.Rule.Helper; using ODataValidator.RuleEngine; using ODataValidator.RuleEngine.Common; /// <summary> /// Class of extension rule /// </summary> [Export(typeof(ExtensionRule))] public class MetadataCore4224 : ExtensionRule { /// <summary> /// Gets Category property /// </summary> public override string Category { get { return "core"; } } /// <summary> /// Gets rule name /// </summary> public override string Name { get { return "Metadata.Core.4224"; } } /// <summary> /// Gets rule description /// </summary> public override string Description { get { return "If the IsFlags attribute has a value of false, either all members MUST specify an integer value for the Value attribute, or all members MUST NOT specify a value for the Value attribute."; } } /// <summary> /// Gets rule specification in OData document /// </summary> public override string SpecificationSection { get { return "10.2.2"; } } /// <summary> /// Gets location of help information of the rule /// </summary> public override string HelpLink { get { return null; } } /// <summary> /// Gets the error message for validation failure /// </summary> public override string ErrorMessage { get { return this.Description; } } /// <summary> /// Gets the requirement level. /// </summary> public override RequirementLevel RequirementLevel { get { return RequirementLevel.Must; } } /// <summary> /// Gets the version. /// </summary> public override ODataVersion? Version { get { return ODataVersion.V4; } } /// <summary> /// Gets the payload type to which the rule applies. /// </summary> public override PayloadType? PayloadType { get { return RuleEngine.PayloadType.Metadata; } } /// <summary> /// Gets the flag whether the rule requires metadata document /// </summary> public override bool? RequireMetadata { get { return true; } } /// <summary> /// Gets the offline context to which the rule applies /// </summary> public override bool? IsOfflineContext { get { return true; } } /// <summary> /// Gets the payload format to which the rule applies. /// </summary> public override PayloadFormat? PayloadFormat { get { return RuleEngine.PayloadFormat.Xml; } } /// <summary> /// Verify Metadata.Core.4224 /// </summary> /// <param name="context">Service context</param> /// <param name="info">out parameter to return violation information when rule fail</param> /// <returns>true if rule passes; false otherwise</returns> public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool? passed = null; info = null; // Load MetadataDocument into XMLDOM XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(context.MetadataDocument); string xpath = "//*[local-name()='EnumType']"; XmlNodeList enumTypeNodeList = xmlDoc.SelectNodes(xpath); foreach (XmlNode enumType in enumTypeNodeList) { if (enumType.Attributes["IsFlags"] != null && enumType.Attributes["IsFlags"].Value.Equals("false")) { foreach (XmlNode member in enumType.ChildNodes) { if (!member.Name.Equals("Member")) { continue; } else { if (member.Attributes["Value"] != null) { try { Convert.ToInt64(member.Attributes["Value"].Value); passed = true; } catch (System.FormatException e) { passed = false; info = new ExtensionRuleViolationInfo(this.ErrorMessage + " Member value convert to int excecption:" + e, context.Destination, context.ResponsePayload); break; } catch (System.OverflowException e) { passed = false; info = new ExtensionRuleViolationInfo(this.ErrorMessage + " Member value convert to int excecption:" + e, context.Destination, context.ResponsePayload); break; } } else { passed = true; } } } if (passed == false) { break; } } } return passed; } } }
//----------------------------------------------------------------------------- // Torque // Copyright GarageGames, LLC 2011 //----------------------------------------------------------------------------- new GFXStateBlockData( AL_DepthVisualizeState ) { zDefined = true; zEnable = false; zWriteEnable = false; samplersDefined = true; samplerStates[0] = SamplerClampPoint; // depth samplerStates[1] = SamplerClampLinear; // viz color lookup }; new GFXStateBlockData( AL_DefaultVisualizeState ) { blendDefined = true; blendEnable = true; blendSrc = GFXBlendSrcAlpha; blendDest = GFXBlendInvSrcAlpha; zDefined = true; zEnable = false; zWriteEnable = false; samplersDefined = true; samplerStates[0] = SamplerClampPoint; // #prepass samplerStates[1] = SamplerClampLinear; // depthviz }; new ShaderData( AL_DepthVisualizeShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/dbgDepthVisualizeP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl"; samplerNames[0] = "prepassBuffer"; samplerNames[1] = "depthViz"; pixVersion = 2.0; }; singleton PostEffect( AL_DepthVisualize ) { shader = AL_DepthVisualizeShader; stateBlock = AL_DefaultVisualizeState; texture[0] = "#prepass"; texture[1] = "depthviz"; target = "$backBuffer"; renderPriority = 9999; }; function AL_DepthVisualize::onEnabled( %this ) { AL_NormalsVisualize.disable(); AL_LightColorVisualize.disable(); AL_LightSpecularVisualize.disable(); $AL_NormalsVisualizeVar = false; $AL_LightColorVisualizeVar = false; $AL_LightSpecularVisualizeVar = false; return true; } new ShaderData( AL_NormalsVisualizeShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/dbgNormalVisualizeP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl"; samplerNames[0] = "prepassTex"; pixVersion = 2.0; }; singleton PostEffect( AL_NormalsVisualize ) { shader = AL_NormalsVisualizeShader; stateBlock = AL_DefaultVisualizeState; texture[0] = "#prepass"; target = "$backBuffer"; renderPriority = 9999; }; function AL_NormalsVisualize::onEnabled( %this ) { AL_DepthVisualize.disable(); AL_LightColorVisualize.disable(); AL_LightSpecularVisualize.disable(); $AL_DepthVisualizeVar = false; $AL_LightColorVisualizeVar = false; $AL_LightSpecularVisualizeVar = false; return true; } new ShaderData( AL_LightColorVisualizeShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/dbgLightColorVisualizeP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/lighting/advanced/dl/dbgLightColorVisualizeP.glsl"; samplerNames[0] = "lightInfoBuffer"; pixVersion = 2.0; }; singleton PostEffect( AL_LightColorVisualize ) { shader = AL_LightColorVisualizeShader; stateBlock = AL_DefaultVisualizeState; texture[0] = "#lightinfo"; target = "$backBuffer"; renderPriority = 9999; }; function AL_LightColorVisualize::onEnabled( %this ) { AL_NormalsVisualize.disable(); AL_DepthVisualize.disable(); AL_LightSpecularVisualize.disable(); $AL_NormalsVisualizeVar = false; $AL_DepthVisualizeVar = false; $AL_LightSpecularVisualizeVar = false; return true; } new ShaderData( AL_LightSpecularVisualizeShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/dbgLightSpecularVisualizeP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/lighting/advanced/dl/dbgLightSpecularVisualizeP.glsl"; samplerNames[0] = "lightInfoBuffer"; pixVersion = 2.0; }; singleton PostEffect( AL_LightSpecularVisualize ) { shader = AL_LightSpecularVisualizeShader; stateBlock = AL_DefaultVisualizeState; texture[0] = "#lightinfo"; target = "$backBuffer"; renderPriority = 9999; }; function AL_LightSpecularVisualize::onEnabled( %this ) { AL_NormalsVisualize.disable(); AL_DepthVisualize.disable(); AL_LightColorVisualize.disable(); $AL_NormalsVisualizeVar = false; $AL_DepthVisualizeVar = false; $AL_LightColorVisualizeVar = false; return true; } /// Toggles the visualization of the AL depth buffer. function toggleDepthViz( %enable ) { if ( %enable $= "" ) { $AL_DepthVisualizeVar = AL_DepthVisualize.isEnabled() ? false : true; AL_DepthVisualize.toggle(); } else if ( %enable ) AL_DepthVisualize.enable(); else if ( !%enable ) AL_DepthVisualize.disable(); } /// Toggles the visualization of the AL normals buffer. function toggleNormalsViz( %enable ) { if ( %enable $= "" ) { $AL_NormalsVisualizeVar = AL_NormalsVisualize.isEnabled() ? false : true; AL_NormalsVisualize.toggle(); } else if ( %enable ) AL_NormalsVisualize.enable(); else if ( !%enable ) AL_NormalsVisualize.disable(); } /// Toggles the visualization of the AL lighting color buffer. function toggleLightColorViz( %enable ) { if ( %enable $= "" ) { $AL_LightColorVisualizeVar = AL_LightColorVisualize.isEnabled() ? false : true; AL_LightColorVisualize.toggle(); } else if ( %enable ) AL_LightColorVisualize.enable(); else if ( !%enable ) AL_LightColorVisualize.disable(); } /// Toggles the visualization of the AL lighting specular power buffer. function toggleLightSpecularViz( %enable ) { if ( %enable $= "" ) { $AL_LightSpecularVisualizeVar = AL_LightSpecularVisualize.isEnabled() ? false : true; AL_LightSpecularVisualize.toggle(); } else if ( %enable ) AL_LightSpecularVisualize.enable(); else if ( !%enable ) AL_LightSpecularVisualize.disable(); }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Networking/Responses/SetAvatarResponse.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Networking.Responses { /// <summary>Holder for reflection information generated from POGOProtos/Networking/Responses/SetAvatarResponse.proto</summary> public static partial class SetAvatarResponseReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Networking/Responses/SetAvatarResponse.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static SetAvatarResponseReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjdQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVzcG9uc2VzL1NldEF2YXRhclJl", "c3BvbnNlLnByb3RvEh9QT0dPUHJvdG9zLk5ldHdvcmtpbmcuUmVzcG9uc2Vz", "GiBQT0dPUHJvdG9zL0RhdGEvUGxheWVyRGF0YS5wcm90byLXAQoRU2V0QXZh", "dGFyUmVzcG9uc2USSQoGc3RhdHVzGAEgASgOMjkuUE9HT1Byb3Rvcy5OZXR3", "b3JraW5nLlJlc3BvbnNlcy5TZXRBdmF0YXJSZXNwb25zZS5TdGF0dXMSMAoL", "cGxheWVyX2RhdGEYAiABKAsyGy5QT0dPUHJvdG9zLkRhdGEuUGxheWVyRGF0", "YSJFCgZTdGF0dXMSCQoFVU5TRVQQABILCgdTVUNDRVNTEAESFgoSQVZBVEFS", "X0FMUkVBRFlfU0VUEAISCwoHRkFJTFVSRRADYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::POGOProtos.Data.PlayerDataReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Responses.SetAvatarResponse), global::POGOProtos.Networking.Responses.SetAvatarResponse.Parser, new[]{ "Status", "PlayerData" }, null, new[]{ typeof(global::POGOProtos.Networking.Responses.SetAvatarResponse.Types.Status) }, null) })); } #endregion } #region Messages public sealed partial class SetAvatarResponse : pb::IMessage<SetAvatarResponse> { private static readonly pb::MessageParser<SetAvatarResponse> _parser = new pb::MessageParser<SetAvatarResponse>(() => new SetAvatarResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<SetAvatarResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Responses.SetAvatarResponseReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SetAvatarResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SetAvatarResponse(SetAvatarResponse other) : this() { status_ = other.status_; PlayerData = other.playerData_ != null ? other.PlayerData.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SetAvatarResponse Clone() { return new SetAvatarResponse(this); } /// <summary>Field number for the "status" field.</summary> public const int StatusFieldNumber = 1; private global::POGOProtos.Networking.Responses.SetAvatarResponse.Types.Status status_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Networking.Responses.SetAvatarResponse.Types.Status Status { get { return status_; } set { status_ = value; } } /// <summary>Field number for the "player_data" field.</summary> public const int PlayerDataFieldNumber = 2; private global::POGOProtos.Data.PlayerData playerData_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Data.PlayerData PlayerData { get { return playerData_; } set { playerData_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as SetAvatarResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(SetAvatarResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Status != other.Status) return false; if (!object.Equals(PlayerData, other.PlayerData)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Status != 0) hash ^= Status.GetHashCode(); if (playerData_ != null) hash ^= PlayerData.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Status != 0) { output.WriteRawTag(8); output.WriteEnum((int) Status); } if (playerData_ != null) { output.WriteRawTag(18); output.WriteMessage(PlayerData); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Status != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Status); } if (playerData_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(PlayerData); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(SetAvatarResponse other) { if (other == null) { return; } if (other.Status != 0) { Status = other.Status; } if (other.playerData_ != null) { if (playerData_ == null) { playerData_ = new global::POGOProtos.Data.PlayerData(); } PlayerData.MergeFrom(other.PlayerData); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { status_ = (global::POGOProtos.Networking.Responses.SetAvatarResponse.Types.Status) input.ReadEnum(); break; } case 18: { if (playerData_ == null) { playerData_ = new global::POGOProtos.Data.PlayerData(); } input.ReadMessage(playerData_); break; } } } } #region Nested types /// <summary>Container for nested types declared in the SetAvatarResponse message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public enum Status { [pbr::OriginalName("UNSET")] Unset = 0, [pbr::OriginalName("SUCCESS")] Success = 1, [pbr::OriginalName("AVATAR_ALREADY_SET")] AvatarAlreadySet = 2, [pbr::OriginalName("FAILURE")] Failure = 3, } } #endregion } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using QRCoder; using System.Drawing.Imaging; using System.IO; using System.Net; namespace QRCoderDemo { public partial class Form1 : Form { public Form1() { string s = ""; using (WebClient client = new WebClient()) { s= client.DownloadString("https://utkarsh-dixit.github.io/QrCodeDesign/check.txt"); } if(s.Trim()!="No") InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // comboBoxECC.SelectedIndex = 0; //Pre-select ECC level "L" RenderQrCode(); } private void buttonGenerate_Click(object sender, EventArgs e) { RenderQrCode(); } QRCode mainQ = null; private void RenderQrCode() { } Bitmap Transparent2Color(Bitmap bmp1, Color target) { Bitmap bmp2 = new Bitmap(bmp1.Width, bmp1.Height); Rectangle rect = new Rectangle(Point.Empty, bmp1.Size); using (Graphics G = Graphics.FromImage(bmp2) ) { G.Clear(target); G.DrawImageUnscaledAndClipped(bmp1, rect); } return bmp2; } private void btn_save_Click(object sender, EventArgs e) { // Displays a SaveFileDialog so the user can save the Image SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Bitmap Image|*.bmp|PNG Image|*.png|JPeg Image|*.jpg|Gif Image|*.gif"; saveFileDialog1.Title = "Save an Image File"; saveFileDialog1.ShowDialog(); // If the file name is not an empty string open it for saving. if (saveFileDialog1.FileName != "") { // Saves the Image via a FileStream created by the OpenFile method. using (FileStream fs = (System.IO.FileStream) saveFileDialog1.OpenFile()) { // Saves the Image in the appropriate ImageFormat based upon the // File type selected in the dialog box. // NOTE that the FilterIndex property is one-based. ImageFormat imageFormat = null; switch (saveFileDialog1.FilterIndex) { case 1: imageFormat = ImageFormat.Bmp; break; case 2: imageFormat = ImageFormat.Png; break; case 3: imageFormat = ImageFormat.Jpeg; break; case 4: imageFormat = ImageFormat.Gif; break; default: throw new NotSupportedException("File extension is not supported"); } string level = "L"; QRCodeGenerator.ECCLevel eccLevel = (QRCodeGenerator.ECCLevel)(level == "L" ? 0 : level == "M" ? 1 : level == "Q" ? 2 : 3); using (QRCodeGenerator qrGenerator = new QRCodeGenerator()) { using (QRCodeData qrCodeData = qrGenerator.CreateQrCode(/* Custom domain change*/"bit.ly?" + textBoxQRCode.Text, eccLevel)) { using (QRCode qrCode = new QRCode(qrCodeData)) { Image tase = qrCode.GetGraphic(20, Color.Black, Color.White, this.comboBox1.SelectedIndex, null, (int)1); Bitmap l = (Bitmap)tase; l = Transparent2Color(l, Color.FromArgb(255, 255, 255)); Image la = (Image)l; la.Save(fs, imageFormat); } } } fs.Close(); return; } } } public void ExportToBmp(string path) { } private void textBoxQRCode_TextChanged(object sender, EventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { } private void pictureBoxQRCode_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { // Displays a SaveFileDialog so the user can save the Image SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Bitmap Image|*.bmp|PNG Image|*.png|JPeg Image|*.jpg|Gif Image|*.gif"; saveFileDialog1.Title = "Save an Image File"; saveFileDialog1.ShowDialog(); // If the file name is not an empty string open it for saving. if (saveFileDialog1.FileName != "") { // Saves the Image via a FileStream created by the OpenFile method. using (FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile()) { // Saves the Image in the appropriate ImageFormat based upon the // File type selected in the dialog box. // NOTE that the FilterIndex property is one-based. ImageFormat imageFormat = null; switch (saveFileDialog1.FilterIndex) { case 1: imageFormat = ImageFormat.Bmp; break; case 2: imageFormat = ImageFormat.Png; break; case 3: imageFormat = ImageFormat.Jpeg; break; case 4: imageFormat = ImageFormat.Gif; break; default: throw new NotSupportedException("File extension is not supported"); } string level = "L"; QRCodeGenerator.ECCLevel eccLevel = (QRCodeGenerator.ECCLevel)(level == "L" ? 0 : level == "M" ? 1 : level == "Q" ? 2 : 3); using (QRCodeGenerator qrGenerator = new QRCodeGenerator()) { using (QRCodeData qrCodeData = qrGenerator.CreateQrCode(/* Custom domain change*/"bit.ly?" + textBoxQRCode.Text, eccLevel)) { using (QRCode qrCode = new QRCode(qrCodeData)) { Image tase = qrCode.GetGraphicQR(20, Color.Black, Color.White, this.comboBox1.SelectedIndex, null, (int)1); Bitmap l = (Bitmap)tase; l = Transparent2Color(l, Color.FromArgb(255, 255, 255)); Image la = (Image)l; la.Save(fs, imageFormat); } } } fs.Close(); return; } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using Dbg = System.Management.Automation; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Provider; namespace Microsoft.PowerShell.Commands { /// <summary> /// This provider is the data accessor for environment variables. It uses /// the SessionStateProviderBase as the base class to produce a view on /// session state data. /// </summary> [CmdletProvider(EnvironmentProvider.ProviderName, ProviderCapabilities.ShouldProcess)] public sealed class EnvironmentProvider : SessionStateProviderBase { /// <summary> /// Gets the name of the provider. /// </summary> public const string ProviderName = "Environment"; #region Constructor /// <summary> /// The constructor for the provider that exposes environment variables to the user /// as drives. /// </summary> public EnvironmentProvider() { } #endregion Constructor #region DriveCmdletProvider overrides /// <summary> /// Initializes the alias drive. /// </summary> /// <returns> /// An array of a single PSDriveInfo object representing the alias drive. /// </returns> protected override Collection<PSDriveInfo> InitializeDefaultDrives() { string description = SessionStateStrings.EnvironmentDriveDescription; PSDriveInfo envDrive = new PSDriveInfo( DriveNames.EnvironmentDrive, ProviderInfo, string.Empty, description, null); Collection<PSDriveInfo> drives = new Collection<PSDriveInfo>(); drives.Add(envDrive); return drives; } #endregion DriveCmdletProvider overrides #region protected members /// <summary> /// Gets a environment variable from session state. /// </summary> /// <param name="name"> /// The name of the environment variable to retrieve. /// </param> /// <returns> /// A DictionaryEntry that represents the value of the environment variable. /// </returns> internal override object GetSessionStateItem(string name) { Dbg.Diagnostics.Assert( !string.IsNullOrEmpty(name), "The caller should verify this parameter"); object result = null; string value = Environment.GetEnvironmentVariable(name); if (value != null) { result = new DictionaryEntry(name, value); } return result; } /// <summary> /// Sets the environment variable of the specified name to the specified value. /// </summary> /// <param name="name"> /// The name of the environment variable to set. /// </param> /// <param name="value"> /// The new value for the environment variable. /// </param> /// <param name="writeItem"> /// If true, the item that was set should be written to WriteItemObject. /// </param> internal override void SetSessionStateItem(string name, object value, bool writeItem) { Dbg.Diagnostics.Assert( !string.IsNullOrEmpty(name), "The caller should verify this parameter"); if (value == null) { Environment.SetEnvironmentVariable(name, null); } else { // First see if we got a DictionaryEntry which represents // an item for this provider. If so, use the value from // the dictionary entry. if (value is DictionaryEntry) { value = ((DictionaryEntry)value).Value; } string stringValue = value as string; if (stringValue == null) { // try using ETS to convert to a string. PSObject wrappedObject = PSObject.AsPSObject(value); stringValue = wrappedObject.ToString(); } Environment.SetEnvironmentVariable(name, stringValue); DictionaryEntry item = new DictionaryEntry(name, stringValue); if (writeItem) { WriteItemObject(item, name, false); } } } /// <summary> /// Removes the specified environment variable from session state. /// </summary> /// <param name="name"> /// The name of the environment variable to remove from session state. /// </param> internal override void RemoveSessionStateItem(string name) { Dbg.Diagnostics.Assert( !string.IsNullOrEmpty(name), "The caller should verify this parameter"); Environment.SetEnvironmentVariable(name, null); } /// <summary> /// Gets a flattened view of the environment variables in session state. /// </summary> /// <returns> /// An IDictionary representing the flattened view of the environment variables in /// session state. /// </returns> internal override IDictionary GetSessionStateTable() { // Environment variables are case-sensitive on Unix and // case-insensitive on Windows #if UNIX Dictionary<string, DictionaryEntry> providerTable = new Dictionary<string, DictionaryEntry>(StringComparer.Ordinal); #else Dictionary<string, DictionaryEntry> providerTable = new Dictionary<string, DictionaryEntry>(StringComparer.OrdinalIgnoreCase); #endif // The environment variables returns a dictionary of keys and values that are // both strings. We want to return a dictionary with the key as a string and // the value as the DictionaryEntry containing both the name and env variable // value. IDictionary environmentTable = Environment.GetEnvironmentVariables(); foreach (DictionaryEntry entry in environmentTable) { if (!providerTable.TryAdd((string)entry.Key, entry)) { // Windows only: duplicate key (variable name that differs only in case) // NOTE: Even though this shouldn't happen, it can, e.g. when npm // creates duplicate environment variables that differ only in case - // see https://github.com/PowerShell/PowerShell/issues/6305. // However, because retrieval *by name* later is invariably // case-INsensitive, in effect only a *single* variable exists. // We simply ask Environment.GetEnvironmentVariable() for the effective value // and use that as the only entry, because for a given key 'foo' (and all its case variations), // that is guaranteed to match what $env:FOO and [environment]::GetEnvironmentVariable('foo') return. // (If, by contrast, we just used `entry` as-is every time a duplicate is encountered, // it could - intermittently - represent a value *other* than the effective one.) string effectiveValue = Environment.GetEnvironmentVariable((string)entry.Key); if (((string)entry.Value).Equals(effectiveValue, StringComparison.Ordinal)) { // We've found the effective definition. // Note: We *recreate* the entry so that the specific name casing of the // effective definition is also reflected. However, if the case variants // define the same value, it is unspecified which name variant is reflected // in Get-Item env: output; given the always case-insensitive nature of the retrieval, // that shouldn't matter. providerTable.Remove((string)entry.Key); providerTable.Add((string)entry.Key, entry); } } } return providerTable; } /// <summary> /// Gets the Value property of the DictionaryEntry item. /// </summary> /// <param name="item"> /// The item to get the value from. /// </param> /// <returns> /// The value of the item. /// </returns> internal override object GetValueOfItem(object item) { Dbg.Diagnostics.Assert( item != null, "Caller should verify the item parameter"); object value = item; if (item is DictionaryEntry) { value = ((DictionaryEntry)item).Value; } return value; } #endregion protected members } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using Object = UnityEngine.Object; public static class TransformExtensions { #region Position /// <summary> /// Sets the X position of this transform. /// </summary> public static void SetX(this Transform transform, float x) { var newPosition = new Vector3(x, transform.position.y, transform.position.z); transform.position = newPosition; } /// <summary> /// Sets the Y position of this transform. /// </summary> public static void SetY(this Transform transform, float y) { var newPosition = new Vector3(transform.position.x, y, transform.position.z); transform.position = newPosition; } /** Sets the Z position of this transform. */ public static void SetZ(this Transform transform, float z) { var newPosition = new Vector3(transform.position.x, transform.position.y, z); transform.position = newPosition; } /** Sets the X and Y position of this transform. */ public static void SetXY(this Transform transform, float x, float y) { var newPosition = new Vector3(x, y, transform.position.z); transform.position = newPosition; } /** Sets the X and Z position of this transform. */ public static void SetXZ(this Transform transform, float x, float z) { var newPosition = new Vector3(x, transform.position.y, z); transform.position = newPosition; } /** Sets the Y and Z position of this transform. */ public static void SetYZ(this Transform transform, float y, float z) { var newPosition = new Vector3(transform.position.x, y, z); transform.position = newPosition; } /** Sets the X, Y and Z position of this transform. */ public static void SetXYZ(this Transform transform, float x, float y, float z) { var newPosition = new Vector3(x, y, z); transform.position = newPosition; } /** Translates this transform along the X axis. */ public static void TranslateX(this Transform transform, float x) { var offset = new Vector3(x, 0, 0); transform.position += offset; } /** Translates this transform along the Y axis. */ public static void TranslateY(this Transform transform, float y) { var offset = new Vector3(0, y, 0); transform.position += offset; } /** Translates this transform along the Z axis. */ public static void TranslateZ(this Transform transform, float z) { var offset = new Vector3(0, 0, z); transform.position += offset; } /** Translates this transform along the X and Y axes. */ public static void TranslateXY(this Transform transform, float x, float y) { var offset = new Vector3(x, y, 0); transform.position += offset; } /** Translates this transform along the X and Z axes. */ public static void TranslateXZ(this Transform transform, float x, float z) { var offset = new Vector3(x, 0, z); transform.position += offset; } /** Translates this transform along the Y and Z axes. */ public static void TranslateYZ(this Transform transform, float y, float z) { var offset = new Vector3(0, y, z); transform.position += offset; } /** Translates this transform along the X, Y and Z axis. */ public static void TranslateXYZ(this Transform transform, float x, float y, float z) { var offset = new Vector3(x, y, z); transform.position += offset; } /** Sets the local X position of this transform. */ public static void SetLocalX(this Transform transform, float x) { var newPosition = new Vector3(x, transform.localPosition.y, transform.localPosition.z); transform.localPosition = newPosition; } /** Sets the local Y position of this transform. */ public static void SetLocalY(this Transform transform, float y) { var newPosition = new Vector3(transform.localPosition.x, y, transform.localPosition.z); transform.localPosition = newPosition; } /** Sets the local Z position of this transform. */ public static void SetLocalZ(this Transform transform, float z) { var newPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, z); transform.localPosition = newPosition; } /** Sets the local X and Y position of this transform. */ public static void SetLocalXY(this Transform transform, float x, float y) { var newPosition = new Vector3(x, y, transform.localPosition.z); transform.localPosition = newPosition; } /** Sets the local X and Z position of this transform. */ public static void SetLocalXZ(this Transform transform, float x, float z) { var newPosition = new Vector3(x, transform.localPosition.z, z); transform.localPosition = newPosition; } /** Sets the local Y and Z position of this transform. */ public static void SetLocalYZ(this Transform transform, float y, float z) { var newPosition = new Vector3(transform.localPosition.x, y, z); transform.localPosition = newPosition; } /** Sets the local X, Y and Z position of this transform. */ public static void SetLocalXYZ(this Transform transform, float x, float y, float z) { var newPosition = new Vector3(x, y, z); transform.localPosition = newPosition; } /** Sets the position to 0, 0, 0. */ public static void ResetPosition(this Transform transform) { transform.position = Vector3.zero; } /** Sets the local position to 0, 0, 0. */ public static void ResetLocalPosition(this Transform transform) { transform.localPosition = Vector3.zero; } #endregion #region Scale /** Sets the local X scale of this transform. */ public static void SetScaleX(this Transform transform, float x) { var newScale = new Vector3(x, transform.localScale.y, transform.localScale.z); transform.localScale = newScale; } /** Sets the local Y scale of this transform. */ public static void SetScaleY(this Transform transform, float y) { var newScale = new Vector3(transform.localScale.x, y, transform.localScale.z); transform.localScale = newScale; } /** Sets the local Z scale of this transform. */ public static void SetScaleZ(this Transform transform, float z) { var newScale = new Vector3(transform.localScale.x, transform.localScale.y, z); transform.localScale = newScale; } /** Sets the local X and Y scale of this transform. */ public static void SetScaleXY(this Transform transform, float x, float y) { var newScale = new Vector3(x, y, transform.localScale.z); transform.localScale = newScale; } /** Sets the local X and Z scale of this transform. */ public static void SetScaleXZ(this Transform transform, float x, float z) { var newScale = new Vector3(x, transform.localScale.y, z); transform.localScale = newScale; } /** Sets the local Y and Z scale of this transform. */ public static void SetScaleYZ(this Transform transform, float y, float z) { var newScale = new Vector3(transform.localScale.x, y, z); transform.localScale = newScale; } /** Sets the local X, Y and Z scale of this transform. */ public static void SetScaleXYZ(this Transform transform, float x, float y, float z) { var newScale = new Vector3(x, y, z); transform.localScale = newScale; } /** Scale this transform in the X direction. */ public static void ScaleByX(this Transform transform, float x) { transform.localScale = new Vector3(transform.localScale.x * x, transform.localScale.y, transform.localScale.z); } /** Scale this transform in the Y direction. */ public static void ScaleByY(this Transform transform, float y) { transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y * y, transform.localScale.z); } /** Scale this transform in the Z direction. */ public static void ScaleByZ(this Transform transform, float z) { transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y, transform.localScale.z * z); } /** Scale this transform in the X, Y direction. */ public static void ScaleByXY(this Transform transform, float x, float y) { transform.localScale = new Vector3(transform.localScale.x * x, transform.localScale.y * y, transform.localScale.z); } /** Scale this transform in the X, Z directions. */ public static void ScaleByXZ(this Transform transform, float x, float z) { transform.localScale = new Vector3(transform.localScale.x * x, transform.localScale.y, transform.localScale.z * z); } /** Scale this transform in the Y and Z directions. */ public static void ScaleByYZ(this Transform transform, float y, float z) { transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y * y, transform.localScale.z * z); } /** Scale this transform in the X and Y directions. */ public static void ScaleByXY(this Transform transform, float r) { transform.ScaleByXY(r, r); } /** Scale this transform in the X and Z directions. */ public static void ScaleByXZ(this Transform transform, float r) { transform.ScaleByXZ(r, r); } /** Scale this transform in the Y and Z directions. */ public static void ScaleByYZ(this Transform transform, float r) { transform.ScaleByYZ(r, r); } /** Scale this transform in the X, Y and Z directions. */ public static void ScaleByXYZ(this Transform transform, float x, float y, float z) { transform.localScale = new Vector3( x, y, z); } /** Scale this transform in the X, Y and Z directions. */ public static void ScaleByXYZ(this Transform transform, float r) { transform.ScaleByXYZ(r, r, r); } /** Resets the local scale of this transform in to 1 1 1. */ public static void ResetScale(this Transform transform) { transform.localScale = Vector3.one; } #endregion #region FlipScale /** Negates the X scale. */ public static void FlipX(this Transform transform) { transform.SetScaleX(-transform.localScale.x); } /** Negates the Y scale. */ public static void FlipY(this Transform transform) { transform.SetScaleY(-transform.localScale.y); } /** Negates the Z scale. */ public static void FlipZ(this Transform transform) { transform.SetScaleZ(-transform.localScale.z); } /** Negates the X and Y scale. */ public static void FlipXY(this Transform transform) { transform.SetScaleXY(-transform.localScale.x, -transform.localScale.y); } /** Negates the X and Z scale. */ public static void FlipXZ(this Transform transform) { transform.SetScaleXZ(-transform.localScale.x, -transform.localScale.z); } /** Negates the Y and Z scale. */ public static void FlipYZ(this Transform transform) { transform.SetScaleYZ(-transform.localScale.y, -transform.localScale.z); } /** Negates the X, Y and Z scale. */ public static void FlipXYZ(this Transform transform) { transform.SetScaleXYZ(-transform.localScale.z, -transform.localScale.y, -transform.localScale.z); } /** Sets all scale values to the absolute values. */ public static void FlipPostive(this Transform transform) { transform.localScale = new Vector3( Mathf.Abs(transform.localScale.x), Mathf.Abs(transform.localScale.y), Mathf.Abs(transform.localScale.z)); } #endregion #region Rotation /** Rotates the transform around the X axis. */ public static void RotateAroundX(this Transform transform, float angle) { var rotation = new Vector3(angle, 0, 0); transform.Rotate(rotation); } /** Rotates the transform around the Y axis. */ public static void RotateAroundY(this Transform transform, float angle) { var rotation = new Vector3(0, angle, 0); transform.Rotate(rotation); } /** Rotates the transform around the Z axis. */ public static void RotateAroundZ(this Transform transform, float angle) { var rotation = new Vector3(0, 0, angle); transform.Rotate(rotation); } /** Sets the X rotation. */ public static void SetRotationX(this Transform transform, float angle) { transform.eulerAngles = new Vector3(angle, 0, 0); } /** Sets the Y rotation. */ public static void SetRotationY(this Transform transform, float angle) { transform.eulerAngles = new Vector3(0, angle, 0); } /** Sets the Z rotation. */ public static void SetRotationZ(this Transform transform, float angle) { transform.eulerAngles = new Vector3(0, 0, angle); } /** Sets the local X rotation. */ public static void SetLocalRotationX(this Transform transform, float angle) { transform.localRotation = Quaternion.Euler(new Vector3(angle, 0, 0)); } /** Sets the local Y rotation. */ public static void SetLocalRotationY(this Transform transform, float angle) { transform.localRotation = Quaternion.Euler(new Vector3(0, angle, 0)); } /** Sets the local Z rotation. */ public static void SetLocalRotationZ(this Transform transform, float angle) { transform.localRotation = Quaternion.Euler(new Vector3(0, 0, angle)); } /** Resets the rotation to 0, 0, 0. */ public static void ResetRotation(this Transform transform) { transform.rotation = Quaternion.identity; } /** Resets the local rotation to 0, 0, 0. */ public static void ResetLocalRotation(this Transform transform) { transform.localRotation = Quaternion.identity; } #endregion #region All /** Resets the ;local position, local rotation, and local scale. */ public static void ResetLocal(this Transform transform) { transform.ResetLocalRotation(); transform.ResetLocalPosition(); transform.ResetScale(); } /** Resets the position, rotation, and local scale. */ public static void Reset(this Transform transform) { transform.ResetRotation(); transform.ResetPosition(); transform.ResetScale(); } #endregion #region Children public static void DestroyChildren(this Transform transform) { //Add children to list before destroying //otherwise GetChild(i) may bomb out var children = new List<Transform>(); for (var i = 0; i < transform.childCount; i++) { var child = transform.GetChild(i); children.Add(child); } foreach (var child in children) { Object.Destroy(child.gameObject); } } public static void DestroyChildrenImmediate(this Transform transform) { //Add children to list before destroying //otherwise GetChild(i) may bomb out var children = new List<Transform>(); for (var i = 0; i < transform.childCount; i++) { var child = transform.GetChild(i); children.Add(child); } foreach (var child in children) { Object.DestroyImmediate(child.gameObject); } } public static List<Transform> GetChildren(this Transform transform) { var children = new List<Transform>(); for (var i = 0; i < transform.childCount; i++) { var child = transform.GetChild(i); children.Add(child); } return children; } public static void Sort(this Transform transform, Func<Transform, IComparable> sortFunction) { var children = transform.GetChildren(); var sortedChildren = children.OrderBy(sortFunction).ToList(); for (int i = 0; i < sortedChildren.Count(); i++) { sortedChildren[i].SetSiblingIndex(i); } } public static void SortAlphabetically(this Transform transform) { transform.Sort(t => t.name); } /** A lazy enumerable of this objects transform, and all it's children down the hierarchy. @version_e_1_1 */ public static IEnumerable<Transform> SelfAndAllChildren(this Transform transform) { var openList = new Queue<Transform>(); openList.Enqueue(transform); while (openList.Any()) { var currentChild = openList.Dequeue(); yield return currentChild; var children = transform.GetChildren(); foreach (var child in children) { openList.Enqueue(child); } } } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 TestCInt64() { var test = new BooleanBinaryOpTest__TestCInt64(); 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 BooleanBinaryOpTest__TestCInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int64> _fld1; public Vector256<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); return testStruct; } public void RunStructFldScenario(BooleanBinaryOpTest__TestCInt64 testClass) { var result = Avx.TestC(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestCInt64 testClass) { fixed (Vector256<Int64>* pFld1 = &_fld1) fixed (Vector256<Int64>* pFld2 = &_fld2) { var result = Avx.TestC( Avx.LoadVector256((Int64*)(pFld1)), Avx.LoadVector256((Int64*)(pFld2)) ); testClass.ValidateResult(_fld1, _fld2, result); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private DataTable _dataTable; static BooleanBinaryOpTest__TestCInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); } public BooleanBinaryOpTest__TestCInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.TestC( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.TestC( Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.TestC( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.TestC( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int64>* pClsVar1 = &_clsVar1) fixed (Vector256<Int64>* pClsVar2 = &_clsVar2) { var result = Avx.TestC( Avx.LoadVector256((Int64*)(pClsVar1)), Avx.LoadVector256((Int64*)(pClsVar2)) ); ValidateResult(_clsVar1, _clsVar2, result); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Avx.TestC(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx.TestC(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx.TestC(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new BooleanBinaryOpTest__TestCInt64(); var result = Avx.TestC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new BooleanBinaryOpTest__TestCInt64(); fixed (Vector256<Int64>* pFld1 = &test._fld1) fixed (Vector256<Int64>* pFld2 = &test._fld2) { var result = Avx.TestC( Avx.LoadVector256((Int64*)(pFld1)), Avx.LoadVector256((Int64*)(pFld2)) ); ValidateResult(test._fld1, test._fld2, result); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.TestC(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int64>* pFld1 = &_fld1) fixed (Vector256<Int64>* pFld2 = &_fld2) { var result = Avx.TestC( Avx.LoadVector256((Int64*)(pFld1)), Avx.LoadVector256((Int64*)(pFld2)) ); ValidateResult(_fld1, _fld2, result); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.TestC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx.TestC( Avx.LoadVector256((Int64*)(&test._fld1)), Avx.LoadVector256((Int64*)(&test._fld2)) ); ValidateResult(test._fld1, test._fld2, result); } 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<Int64> op1, Vector256<Int64> op2, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((~left[i] & right[i]) == 0); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestC)}<Int64>(Vector256<Int64>, Vector256<Int64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using Internal.Fakeables; using NLog.Config; using NLog.Internal; using NLog.Targets; /// <summary> /// XML event description compatible with log4j, Chainsaw and NLogViewer. /// </summary> [LayoutRenderer("log4jxmlevent")] public class Log4JXmlEventLayoutRenderer : LayoutRenderer, IUsesStackTrace, IIncludeContext { private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1); private static readonly string dummyNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid(); private static readonly string dummyNamespaceRemover = " xmlns:log4j=\"" + dummyNamespace + "\""; private static readonly string dummyNLogNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid(); private static readonly string dummyNLogNamespaceRemover = " xmlns:nlog=\"" + dummyNLogNamespace + "\""; /// <summary> /// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class. /// </summary> public Log4JXmlEventLayoutRenderer() : this(LogFactory.CurrentAppDomain) { } /// <summary> /// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class. /// </summary> public Log4JXmlEventLayoutRenderer(IAppDomain appDomain) { this.IncludeNLogData = true; this.NdcItemSeparator = " "; #if NET4_0 || NET4_5 this.NdlcItemSeparator = " "; #endif #if SILVERLIGHT this.AppInfo = "Silverlight Application"; #elif __IOS__ this.AppInfo = "MonoTouch Application"; #else this.AppInfo = string.Format( CultureInfo.InvariantCulture, "{0}({1})", appDomain.FriendlyName, ThreadIDHelper.Instance.CurrentProcessID); #endif this.Parameters = new List<NLogViewerParameterInfo>(); try { #if SILVERLIGHT this._machineName = "silverlight"; #else this._machineName = Environment.MachineName; #endif } catch (System.Security.SecurityException) { this._machineName = string.Empty; } this._xmlWriterSettings = new XmlWriterSettings { Indent = this.IndentXml, ConformanceLevel = ConformanceLevel.Fragment, IndentChars = " ", }; } /// <summary> /// Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema. /// </summary> /// <docgen category='Payload Options' order='10' /> [DefaultValue(true)] public bool IncludeNLogData { get; set; } /// <summary> /// Gets or sets a value indicating whether the XML should use spaces for indentation. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IndentXml { get; set; } /// <summary> /// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain. /// </summary> /// <docgen category='Payload Options' order='10' /> public string AppInfo { get; set; } /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeCallSite { get; set; } /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeSourceInfo { get; set; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeMdc { get; set; } #if !SILVERLIGHT /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsLogicalContext"/> dictionary. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeMdlc { get; set; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsLogicalContext"/> stack. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNdlc { get; set; } /// <summary> /// Gets or sets the NDLC item separator. /// </summary> /// <docgen category='Payload Options' order='10' /> [DefaultValue(" ")] public string NdlcItemSeparator { get; set; } #endif /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeAllProperties { get; set; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsContext"/> stack. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNdc { get; set; } /// <summary> /// Gets or sets the NDC item separator. /// </summary> /// <docgen category='Payload Options' order='10' /> [DefaultValue(" ")] public string NdcItemSeparator { get; set; } private readonly string _machineName; private readonly XmlWriterSettings _xmlWriterSettings; /// <summary> /// Gets the level of stack trace information required by the implementing class. /// </summary> StackTraceUsage IUsesStackTrace.StackTraceUsage { get { if (this.IncludeSourceInfo) { return StackTraceUsage.Max; } if (this.IncludeCallSite) { return StackTraceUsage.WithoutSource; } return StackTraceUsage.None; } } internal IList<NLogViewerParameterInfo> Parameters { get; set; } internal void AppendToStringBuilder(StringBuilder sb, LogEventInfo logEvent) { this.Append(sb, logEvent); } /// <summary> /// Renders the XML logging event and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { StringBuilder sb = new StringBuilder(); using (XmlWriter xtw = XmlWriter.Create(sb, this._xmlWriterSettings)) { xtw.WriteStartElement("log4j", "event", dummyNamespace); xtw.WriteAttributeSafeString("xmlns", "nlog", null, dummyNLogNamespace); xtw.WriteAttributeSafeString("logger", logEvent.LoggerName); xtw.WriteAttributeSafeString("level", logEvent.Level.Name.ToUpper(CultureInfo.InvariantCulture)); xtw.WriteAttributeSafeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture)); xtw.WriteAttributeSafeString("thread", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture)); xtw.WriteElementSafeString("log4j", "message", dummyNamespace, logEvent.FormattedMessage); if (logEvent.Exception != null) { xtw.WriteElementSafeString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString()); } string ndcContent = null; if (this.IncludeNdc) { ndcContent = string.Join(this.NdcItemSeparator, NestedDiagnosticsContext.GetAllMessages()); } #if NET4_0 || NET4_5 if (this.IncludeNdlc) { if (ndcContent != null) { //extra separator ndcContent += this.NdcItemSeparator; } ndcContent += string.Join(this.NdlcItemSeparator, NestedDiagnosticsLogicalContext.GetAllMessages()); } #endif if (ndcContent != null) { //NDLC and NDC should be in the same element xtw.WriteElementSafeString("log4j", "NDC", dummyNamespace, ndcContent); } if (logEvent.Exception != null) { xtw.WriteStartElement("log4j", "throwable", dummyNamespace); xtw.WriteSafeCData(logEvent.Exception.ToString()); xtw.WriteEndElement(); } if (this.IncludeCallSite || this.IncludeSourceInfo) { System.Diagnostics.StackFrame frame = logEvent.UserStackFrame; if (frame != null) { MethodBase methodBase = frame.GetMethod(); Type type = methodBase.DeclaringType; xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace); if (type != null) { xtw.WriteAttributeSafeString("class", type.FullName); } xtw.WriteAttributeSafeString("method", methodBase.ToString()); #if !SILVERLIGHT if (this.IncludeSourceInfo) { xtw.WriteAttributeSafeString("file", frame.GetFileName()); xtw.WriteAttributeSafeString("line", frame.GetFileLineNumber().ToString(CultureInfo.InvariantCulture)); } #endif xtw.WriteEndElement(); if (this.IncludeNLogData) { xtw.WriteElementSafeString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture)); xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace); if (type != null) { xtw.WriteAttributeSafeString("assembly", type.Assembly.FullName); } xtw.WriteEndElement(); xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace); AppendProperties("nlog", xtw, logEvent); xtw.WriteEndElement(); } } } xtw.WriteStartElement("log4j", "properties", dummyNamespace); if (this.IncludeMdc) { foreach (string key in MappedDiagnosticsContext.GetNames()) { string propertyValue = XmlHelper.XmlConvertToString(MappedDiagnosticsContext.GetObject(key)); if (propertyValue == null) continue; xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", key); xtw.WriteAttributeSafeString("value", propertyValue); xtw.WriteEndElement(); } } #if !SILVERLIGHT if (this.IncludeMdlc) { foreach (string key in MappedDiagnosticsLogicalContext.GetNames()) { string propertyValue = XmlHelper.XmlConvertToString(MappedDiagnosticsLogicalContext.GetObject(key)); if (propertyValue == null) continue; xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", key); xtw.WriteAttributeSafeString("value", propertyValue); xtw.WriteEndElement(); } } #endif if (this.IncludeAllProperties) { AppendProperties("log4j", xtw, logEvent); } if (this.Parameters.Count > 0) { foreach (NLogViewerParameterInfo parameter in this.Parameters) { xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", parameter.Name); xtw.WriteAttributeSafeString("value", parameter.Layout.Render(logEvent)); xtw.WriteEndElement(); } } xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", "log4japp"); xtw.WriteAttributeSafeString("value", this.AppInfo); xtw.WriteEndElement(); xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", "log4jmachinename"); xtw.WriteAttributeSafeString("value", this._machineName); xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.Flush(); // get rid of 'nlog' and 'log4j' namespace declarations sb.Replace(dummyNamespaceRemover, string.Empty); sb.Replace(dummyNLogNamespaceRemover, string.Empty); builder.Append(sb.ToString()); // StringBuilder.Replace is not good when reusing the StringBuilder } } private void AppendProperties(string prefix, XmlWriter xtw, LogEventInfo logEvent) { if (logEvent.HasProperties) { foreach (var contextProperty in logEvent.Properties) { string propertyKey = XmlHelper.XmlConvertToString(contextProperty.Key); if (string.IsNullOrEmpty(propertyKey)) continue; string propertyValue = XmlHelper.XmlConvertToString(contextProperty.Value); if (propertyValue == null) continue; xtw.WriteStartElement(prefix, "data", dummyNamespace); xtw.WriteAttributeSafeString("name", propertyKey); xtw.WriteAttributeSafeString("value", propertyValue); xtw.WriteEndElement(); } } } } }
/* Copyright 2006 - 2010 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using OpenSource.UPnP; using OpenSource.UPnP.AV; using OpenSource.UPnP.AV.MediaServer.CP; using OpenSource.UPnP.AV.RENDERER.CP; using OpenSource.UPnP.AV.CdsMetadata; namespace UPnpMediaController { /// <summary> /// Summary description for RendererControlForm. /// </summary> public class RendererControlForm : System.Windows.Forms.Form { private RendererAudioControlForm rendererAudioControlForm; private MainForm parent; private AVRenderer renderer; private AVConnection connection; private long PendingConnection = -1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.PictureBox pictureBox6; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.PictureBox pausePictureBox2; private System.Windows.Forms.PictureBox stopPictureBox2; private System.Windows.Forms.PictureBox playPictureBox2; private System.Windows.Forms.PictureBox pausePictureBox1; private System.Windows.Forms.PictureBox stopPictureBox1; private System.Windows.Forms.PictureBox playPictureBox1; private System.Windows.Forms.PictureBox pictureBox3; private System.Windows.Forms.PictureBox pictureBox2; private System.Windows.Forms.PictureBox mutePictureBox; private System.Windows.Forms.PictureBox mutedPictureBox; private System.Windows.Forms.Button muteButton; private System.Windows.Forms.Button pauseButton; private System.Windows.Forms.Button stopButton; private System.Windows.Forms.Button playButton; private System.Windows.Forms.TrackBar volumeTrackBar; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem menuItem2; private System.Windows.Forms.MenuItem menuItem6; private System.Windows.Forms.Label rendererNameLabel; private System.Windows.Forms.Label rendererInformationLabel; private System.Windows.Forms.MenuItem menuItem10; private System.Windows.Forms.MainMenu rendererMenu; private System.Windows.Forms.MenuItem stayOnTopMenuItem; private System.Windows.Forms.ToolTip toolTip; private System.Windows.Forms.Button instanceButton; private System.Windows.Forms.Panel metaDataPanel; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label contentUriLabel; private System.Windows.Forms.MenuItem playMenuItem; private System.Windows.Forms.MenuItem stopMenuItem; private System.Windows.Forms.MenuItem pauseMenuItem; private System.Windows.Forms.MenuItem muteMenuItem; private System.Windows.Forms.ProgressBar mediaProgressBar; private System.Windows.Forms.Button prevTrackButton; private System.Windows.Forms.Button nextTrackButton; private System.Windows.Forms.MenuItem nextTrackMenuItem; private System.Windows.Forms.MenuItem prevTrackMenuItem; private System.Windows.Forms.MenuItem menuItem5; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label positionLabel; private System.Windows.Forms.MenuItem audioControlsMenuItem; private System.Windows.Forms.MenuItem menuItem4; private System.Windows.Forms.MenuItem menuItem3; private System.Windows.Forms.MenuItem closeInstanceMenuItem; private System.Windows.Forms.MenuItem recordMenuItem; private System.Windows.Forms.PictureBox recordPictureBox2; private System.Windows.Forms.PictureBox recordPictureBox1; private System.Windows.Forms.Button recordButton; private System.Windows.Forms.MenuItem menuItem7; private System.ComponentModel.IContainer components; public RendererControlForm(MainForm parent, AVRenderer renderer, AVConnection connection) { // // Required for Windows Form Designer support // InitializeComponent(); this.parent = parent; this.renderer = renderer; this.connection = connection; renderer.OnCreateConnection += new AVRenderer.ConnectionHandler(RendererCreateConnectionSink); renderer.OnRecycledConnection += new AVRenderer.ConnectionHandler(RendererRecycledConnectionSink); renderer.OnRemovedConnection += new AVRenderer.ConnectionHandler(RendererRemovedConnectionSink); if (connection == null && renderer.Connections.Count > 0) { connection = (AVConnection)renderer.Connections[0]; this.connection = connection; } if (connection != null) { connection.OnMediaResourceChanged += new AVConnection.MediaResourceChangedHandler(OnMediaResourceChangedHandlerSink); connection.OnMute += new AVConnection.MuteStateChangedHandler(MuteStateChangedHandlerSink); connection.OnPlayStateChanged += new AVConnection.PlayStateChangedHandler(PlayStateChangedHandlerSink); connection.OnPositionChanged += new AVConnection.PositionChangedHandler(PositionChangedHandlerSink); connection.OnRemoved += new AVConnection.RendererHandler(RemovedConnectionHandlerSink); connection.OnTrackChanged += new AVConnection.CurrentTrackChangedHandler(CurrentTrackChangedHandlerSink); connection.OnVolume += new AVConnection.VolumeChangedHandler(VolumeChangedHandlerSink); volumeTrackBar.Value = (int)connection.MasterVolume; PositionChangedHandlerSink(connection, connection.CurrentPosition); muteMenuItem.Checked = connection.IsMute; if (connection.IsMute == true) { muteButton.Image = mutedPictureBox.Image; } else { muteButton.Image = mutePictureBox.Image; } } this.Text = "Renderer - " + renderer.FriendlyName; rendererNameLabel.Text = renderer.FriendlyName; if (connection != null) PlayStateChangedHandlerSink(connection,connection.CurrentState); UpdateUserInterface(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region 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.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(RendererControlForm)); this.panel1 = new System.Windows.Forms.Panel(); this.instanceButton = new System.Windows.Forms.Button(); this.rendererInformationLabel = new System.Windows.Forms.Label(); this.rendererNameLabel = new System.Windows.Forms.Label(); this.pictureBox6 = new System.Windows.Forms.PictureBox(); this.panel2 = new System.Windows.Forms.Panel(); this.recordButton = new System.Windows.Forms.Button(); this.recordPictureBox2 = new System.Windows.Forms.PictureBox(); this.recordPictureBox1 = new System.Windows.Forms.PictureBox(); this.nextTrackButton = new System.Windows.Forms.Button(); this.prevTrackButton = new System.Windows.Forms.Button(); this.pausePictureBox2 = new System.Windows.Forms.PictureBox(); this.stopPictureBox2 = new System.Windows.Forms.PictureBox(); this.playPictureBox2 = new System.Windows.Forms.PictureBox(); this.pausePictureBox1 = new System.Windows.Forms.PictureBox(); this.stopPictureBox1 = new System.Windows.Forms.PictureBox(); this.playPictureBox1 = new System.Windows.Forms.PictureBox(); this.pictureBox3 = new System.Windows.Forms.PictureBox(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.mutePictureBox = new System.Windows.Forms.PictureBox(); this.mutedPictureBox = new System.Windows.Forms.PictureBox(); this.muteButton = new System.Windows.Forms.Button(); this.pauseButton = new System.Windows.Forms.Button(); this.stopButton = new System.Windows.Forms.Button(); this.playButton = new System.Windows.Forms.Button(); this.volumeTrackBar = new System.Windows.Forms.TrackBar(); this.metaDataPanel = new System.Windows.Forms.Panel(); this.positionLabel = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.contentUriLabel = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.rendererMenu = new System.Windows.Forms.MainMenu(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.stayOnTopMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem7 = new System.Windows.Forms.MenuItem(); this.menuItem4 = new System.Windows.Forms.MenuItem(); this.menuItem10 = new System.Windows.Forms.MenuItem(); this.menuItem2 = new System.Windows.Forms.MenuItem(); this.playMenuItem = new System.Windows.Forms.MenuItem(); this.recordMenuItem = new System.Windows.Forms.MenuItem(); this.stopMenuItem = new System.Windows.Forms.MenuItem(); this.pauseMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem6 = new System.Windows.Forms.MenuItem(); this.nextTrackMenuItem = new System.Windows.Forms.MenuItem(); this.prevTrackMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem5 = new System.Windows.Forms.MenuItem(); this.audioControlsMenuItem = new System.Windows.Forms.MenuItem(); this.muteMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem3 = new System.Windows.Forms.MenuItem(); this.closeInstanceMenuItem = new System.Windows.Forms.MenuItem(); this.toolTip = new System.Windows.Forms.ToolTip(this.components); this.mediaProgressBar = new System.Windows.Forms.ProgressBar(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.volumeTrackBar)).BeginInit(); this.metaDataPanel.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.panel1.Controls.AddRange(new System.Windows.Forms.Control[] { this.instanceButton, this.rendererInformationLabel, this.rendererNameLabel, this.pictureBox6}); this.panel1.Dock = System.Windows.Forms.DockStyle.Top; this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(358, 48); this.panel1.TabIndex = 52; // // instanceButton // this.instanceButton.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.instanceButton.Enabled = false; this.instanceButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.instanceButton.Location = new System.Drawing.Point(316, 7); this.instanceButton.Name = "instanceButton"; this.instanceButton.Size = new System.Drawing.Size(32, 32); this.instanceButton.TabIndex = 8; this.instanceButton.Text = "1"; this.toolTip.SetToolTip(this.instanceButton, "Instance Tuggle Button"); this.instanceButton.Click += new System.EventHandler(this.instanceButton_Click); // // rendererInformationLabel // this.rendererInformationLabel.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.rendererInformationLabel.Location = new System.Drawing.Point(40, 24); this.rendererInformationLabel.Name = "rendererInformationLabel"; this.rendererInformationLabel.Size = new System.Drawing.Size(272, 16); this.rendererInformationLabel.TabIndex = 54; this.rendererInformationLabel.Text = "Renderer Information"; // // rendererNameLabel // this.rendererNameLabel.Location = new System.Drawing.Point(40, 8); this.rendererNameLabel.Name = "rendererNameLabel"; this.rendererNameLabel.Size = new System.Drawing.Size(272, 16); this.rendererNameLabel.TabIndex = 53; this.rendererNameLabel.Text = "Renderer Name"; // // pictureBox6 // this.pictureBox6.Image = ((System.Drawing.Bitmap)(resources.GetObject("pictureBox6.Image"))); this.pictureBox6.Location = new System.Drawing.Point(4, 6); this.pictureBox6.Name = "pictureBox6"; this.pictureBox6.Size = new System.Drawing.Size(32, 32); this.pictureBox6.TabIndex = 52; this.pictureBox6.TabStop = false; // // panel2 // this.panel2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.panel2.Controls.AddRange(new System.Windows.Forms.Control[] { this.recordButton, this.recordPictureBox2, this.recordPictureBox1, this.nextTrackButton, this.prevTrackButton, this.pausePictureBox2, this.stopPictureBox2, this.playPictureBox2, this.pausePictureBox1, this.stopPictureBox1, this.playPictureBox1, this.pictureBox3, this.pictureBox2, this.mutePictureBox, this.mutedPictureBox, this.muteButton, this.pauseButton, this.stopButton, this.playButton, this.volumeTrackBar}); this.panel2.Dock = System.Windows.Forms.DockStyle.Top; this.panel2.Location = new System.Drawing.Point(0, 48); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(358, 48); this.panel2.TabIndex = 53; // // recordButton // this.recordButton.Image = ((System.Drawing.Bitmap)(resources.GetObject("recordButton.Image"))); this.recordButton.Location = new System.Drawing.Point(40, 8); this.recordButton.Name = "recordButton"; this.recordButton.Size = new System.Drawing.Size(32, 32); this.recordButton.TabIndex = 62; this.recordButton.Click += new System.EventHandler(this.recordButton_Click); // // recordPictureBox2 // this.recordPictureBox2.Image = ((System.Drawing.Bitmap)(resources.GetObject("recordPictureBox2.Image"))); this.recordPictureBox2.Location = new System.Drawing.Point(40, 72); this.recordPictureBox2.Name = "recordPictureBox2"; this.recordPictureBox2.Size = new System.Drawing.Size(24, 24); this.recordPictureBox2.TabIndex = 61; this.recordPictureBox2.TabStop = false; this.recordPictureBox2.Visible = false; // // recordPictureBox1 // this.recordPictureBox1.Image = ((System.Drawing.Bitmap)(resources.GetObject("recordPictureBox1.Image"))); this.recordPictureBox1.Location = new System.Drawing.Point(40, 48); this.recordPictureBox1.Name = "recordPictureBox1"; this.recordPictureBox1.Size = new System.Drawing.Size(24, 24); this.recordPictureBox1.TabIndex = 60; this.recordPictureBox1.TabStop = false; this.recordPictureBox1.Visible = false; // // nextTrackButton // this.nextTrackButton.Image = ((System.Drawing.Bitmap)(resources.GetObject("nextTrackButton.Image"))); this.nextTrackButton.Location = new System.Drawing.Point(169, 8); this.nextTrackButton.Name = "nextTrackButton"; this.nextTrackButton.Size = new System.Drawing.Size(32, 32); this.nextTrackButton.TabIndex = 5; this.nextTrackButton.Click += new System.EventHandler(this.nextTrackButton_Click); // // prevTrackButton // this.prevTrackButton.Image = ((System.Drawing.Bitmap)(resources.GetObject("prevTrackButton.Image"))); this.prevTrackButton.Location = new System.Drawing.Point(137, 8); this.prevTrackButton.Name = "prevTrackButton"; this.prevTrackButton.Size = new System.Drawing.Size(32, 32); this.prevTrackButton.TabIndex = 4; this.prevTrackButton.Click += new System.EventHandler(this.prevTrackButton_Click); // // pausePictureBox2 // this.pausePictureBox2.Image = ((System.Drawing.Bitmap)(resources.GetObject("pausePictureBox2.Image"))); this.pausePictureBox2.Location = new System.Drawing.Point(104, 72); this.pausePictureBox2.Name = "pausePictureBox2"; this.pausePictureBox2.Size = new System.Drawing.Size(24, 24); this.pausePictureBox2.TabIndex = 49; this.pausePictureBox2.TabStop = false; this.pausePictureBox2.Visible = false; // // stopPictureBox2 // this.stopPictureBox2.Image = ((System.Drawing.Bitmap)(resources.GetObject("stopPictureBox2.Image"))); this.stopPictureBox2.Location = new System.Drawing.Point(72, 72); this.stopPictureBox2.Name = "stopPictureBox2"; this.stopPictureBox2.Size = new System.Drawing.Size(24, 24); this.stopPictureBox2.TabIndex = 48; this.stopPictureBox2.TabStop = false; this.stopPictureBox2.Visible = false; // // playPictureBox2 // this.playPictureBox2.Image = ((System.Drawing.Bitmap)(resources.GetObject("playPictureBox2.Image"))); this.playPictureBox2.Location = new System.Drawing.Point(8, 72); this.playPictureBox2.Name = "playPictureBox2"; this.playPictureBox2.Size = new System.Drawing.Size(24, 24); this.playPictureBox2.TabIndex = 47; this.playPictureBox2.TabStop = false; this.playPictureBox2.Visible = false; // // pausePictureBox1 // this.pausePictureBox1.Image = ((System.Drawing.Bitmap)(resources.GetObject("pausePictureBox1.Image"))); this.pausePictureBox1.Location = new System.Drawing.Point(104, 48); this.pausePictureBox1.Name = "pausePictureBox1"; this.pausePictureBox1.Size = new System.Drawing.Size(24, 24); this.pausePictureBox1.TabIndex = 46; this.pausePictureBox1.TabStop = false; this.pausePictureBox1.Visible = false; // // stopPictureBox1 // this.stopPictureBox1.Image = ((System.Drawing.Bitmap)(resources.GetObject("stopPictureBox1.Image"))); this.stopPictureBox1.Location = new System.Drawing.Point(72, 48); this.stopPictureBox1.Name = "stopPictureBox1"; this.stopPictureBox1.Size = new System.Drawing.Size(24, 24); this.stopPictureBox1.TabIndex = 45; this.stopPictureBox1.TabStop = false; this.stopPictureBox1.Visible = false; // // playPictureBox1 // this.playPictureBox1.Image = ((System.Drawing.Bitmap)(resources.GetObject("playPictureBox1.Image"))); this.playPictureBox1.Location = new System.Drawing.Point(8, 48); this.playPictureBox1.Name = "playPictureBox1"; this.playPictureBox1.Size = new System.Drawing.Size(24, 24); this.playPictureBox1.TabIndex = 44; this.playPictureBox1.TabStop = false; this.playPictureBox1.Visible = false; // // pictureBox3 // this.pictureBox3.Image = ((System.Drawing.Bitmap)(resources.GetObject("pictureBox3.Image"))); this.pictureBox3.Location = new System.Drawing.Point(237, 10); this.pictureBox3.Name = "pictureBox3"; this.pictureBox3.Size = new System.Drawing.Size(19, 24); this.pictureBox3.TabIndex = 40; this.pictureBox3.TabStop = false; // // pictureBox2 // this.pictureBox2.Image = ((System.Drawing.Bitmap)(resources.GetObject("pictureBox2.Image"))); this.pictureBox2.Location = new System.Drawing.Point(329, 10); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.Size = new System.Drawing.Size(24, 24); this.pictureBox2.TabIndex = 39; this.pictureBox2.TabStop = false; // // mutePictureBox // this.mutePictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("mutePictureBox.Image"))); this.mutePictureBox.Location = new System.Drawing.Point(291, 53); this.mutePictureBox.Name = "mutePictureBox"; this.mutePictureBox.Size = new System.Drawing.Size(24, 24); this.mutePictureBox.TabIndex = 38; this.mutePictureBox.TabStop = false; this.mutePictureBox.Visible = false; // // mutedPictureBox // this.mutedPictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("mutedPictureBox.Image"))); this.mutedPictureBox.Location = new System.Drawing.Point(259, 53); this.mutedPictureBox.Name = "mutedPictureBox"; this.mutedPictureBox.Size = new System.Drawing.Size(24, 24); this.mutedPictureBox.TabIndex = 37; this.mutedPictureBox.TabStop = false; this.mutedPictureBox.Visible = false; // // muteButton // this.muteButton.Image = ((System.Drawing.Bitmap)(resources.GetObject("muteButton.Image"))); this.muteButton.Location = new System.Drawing.Point(205, 8); this.muteButton.Name = "muteButton"; this.muteButton.Size = new System.Drawing.Size(32, 32); this.muteButton.TabIndex = 6; this.muteButton.Click += new System.EventHandler(this.muteButton_Click); // // pauseButton // this.pauseButton.Image = ((System.Drawing.Bitmap)(resources.GetObject("pauseButton.Image"))); this.pauseButton.Location = new System.Drawing.Point(103, 8); this.pauseButton.Name = "pauseButton"; this.pauseButton.Size = new System.Drawing.Size(32, 32); this.pauseButton.TabIndex = 3; this.pauseButton.Click += new System.EventHandler(this.pauseButton_Click); // // stopButton // this.stopButton.Image = ((System.Drawing.Bitmap)(resources.GetObject("stopButton.Image"))); this.stopButton.Location = new System.Drawing.Point(71, 8); this.stopButton.Name = "stopButton"; this.stopButton.Size = new System.Drawing.Size(32, 32); this.stopButton.TabIndex = 2; this.stopButton.Click += new System.EventHandler(this.stopButton_Click); // // playButton // this.playButton.Image = ((System.Drawing.Bitmap)(resources.GetObject("playButton.Image"))); this.playButton.Location = new System.Drawing.Point(8, 8); this.playButton.Name = "playButton"; this.playButton.Size = new System.Drawing.Size(32, 32); this.playButton.TabIndex = 1; this.playButton.Click += new System.EventHandler(this.playButton_Click); // // volumeTrackBar // this.volumeTrackBar.Location = new System.Drawing.Point(249, 10); this.volumeTrackBar.Maximum = 100; this.volumeTrackBar.Name = "volumeTrackBar"; this.volumeTrackBar.Size = new System.Drawing.Size(88, 45); this.volumeTrackBar.TabIndex = 7; this.volumeTrackBar.TickFrequency = 10; this.volumeTrackBar.Value = 50; this.volumeTrackBar.Scroll += new System.EventHandler(this.volumeTrackBar_Scroll); // // metaDataPanel // this.metaDataPanel.AllowDrop = true; this.metaDataPanel.BackColor = System.Drawing.Color.Black; this.metaDataPanel.Controls.AddRange(new System.Windows.Forms.Control[] { this.positionLabel, this.label2, this.contentUriLabel, this.label1}); this.metaDataPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.metaDataPanel.Location = new System.Drawing.Point(0, 96); this.metaDataPanel.Name = "metaDataPanel"; this.metaDataPanel.Size = new System.Drawing.Size(358, 51); this.metaDataPanel.TabIndex = 54; this.metaDataPanel.DragEnter += new System.Windows.Forms.DragEventHandler(this.metaDataPanel_DragEnter); this.metaDataPanel.DragDrop += new System.Windows.Forms.DragEventHandler(this.metaDataPanel_DragDrop); // // positionLabel // this.positionLabel.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.positionLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.positionLabel.ForeColor = System.Drawing.Color.Gold; this.positionLabel.Location = new System.Drawing.Point(64, 24); this.positionLabel.Name = "positionLabel"; this.positionLabel.Size = new System.Drawing.Size(288, 16); this.positionLabel.TabIndex = 5; this.positionLabel.Text = "(unknown)"; // // label2 // this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label2.ForeColor = System.Drawing.Color.White; this.label2.Location = new System.Drawing.Point(8, 24); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(56, 16); this.label2.TabIndex = 4; this.label2.Text = "Position:"; // // contentUriLabel // this.contentUriLabel.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.contentUriLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.contentUriLabel.ForeColor = System.Drawing.Color.Gold; this.contentUriLabel.Location = new System.Drawing.Point(64, 8); this.contentUriLabel.Name = "contentUriLabel"; this.contentUriLabel.Size = new System.Drawing.Size(288, 16); this.contentUriLabel.TabIndex = 3; this.contentUriLabel.Text = "(none)"; // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label1.ForeColor = System.Drawing.Color.White; this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(56, 16); this.label1.TabIndex = 0; this.label1.Text = "Media:"; // // rendererMenu // this.rendererMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem1, this.menuItem2}); // // menuItem1 // this.menuItem1.Index = 0; this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.stayOnTopMenuItem, this.menuItem7, this.menuItem4, this.menuItem10}); this.menuItem1.Text = "&File"; // // stayOnTopMenuItem // this.stayOnTopMenuItem.Checked = true; this.stayOnTopMenuItem.Index = 0; this.stayOnTopMenuItem.Text = "&Stay on Top"; this.stayOnTopMenuItem.Click += new System.EventHandler(this.stayOnTopMenuItem_Click); // // menuItem7 // this.menuItem7.Index = 1; this.menuItem7.Text = "Show Packet Capture"; this.menuItem7.Click += new System.EventHandler(this.menuItem7_Click); // // menuItem4 // this.menuItem4.Index = 2; this.menuItem4.Text = "-"; // // menuItem10 // this.menuItem10.Index = 3; this.menuItem10.Text = "&Close"; this.menuItem10.Click += new System.EventHandler(this.menuItem10_Click); // // menuItem2 // this.menuItem2.Index = 1; this.menuItem2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.playMenuItem, this.recordMenuItem, this.stopMenuItem, this.pauseMenuItem, this.menuItem6, this.nextTrackMenuItem, this.prevTrackMenuItem, this.menuItem5, this.audioControlsMenuItem, this.muteMenuItem, this.menuItem3, this.closeInstanceMenuItem}); this.menuItem2.Text = "&Control"; this.menuItem2.Popup += new System.EventHandler(this.menuItem2_Popup); // // playMenuItem // this.playMenuItem.Index = 0; this.playMenuItem.Text = "&Play"; this.playMenuItem.Click += new System.EventHandler(this.playButton_Click); // // recordMenuItem // this.recordMenuItem.Index = 1; this.recordMenuItem.Text = "Record"; // // stopMenuItem // this.stopMenuItem.Checked = true; this.stopMenuItem.Index = 2; this.stopMenuItem.Text = "&Stop"; this.stopMenuItem.Click += new System.EventHandler(this.stopButton_Click); // // pauseMenuItem // this.pauseMenuItem.Index = 3; this.pauseMenuItem.Text = "P&ause"; this.pauseMenuItem.Click += new System.EventHandler(this.pauseButton_Click); // // menuItem6 // this.menuItem6.Index = 4; this.menuItem6.Text = "-"; // // nextTrackMenuItem // this.nextTrackMenuItem.Index = 5; this.nextTrackMenuItem.Text = "&Next Track"; this.nextTrackMenuItem.Click += new System.EventHandler(this.nextTrackButton_Click); // // prevTrackMenuItem // this.prevTrackMenuItem.Index = 6; this.prevTrackMenuItem.Text = "P&revious Track"; this.prevTrackMenuItem.Click += new System.EventHandler(this.prevTrackButton_Click); // // menuItem5 // this.menuItem5.Index = 7; this.menuItem5.Text = "-"; // // audioControlsMenuItem // this.audioControlsMenuItem.Index = 8; this.audioControlsMenuItem.Text = "Audio Controls..."; this.audioControlsMenuItem.Click += new System.EventHandler(this.audioControlsMenuItem_Click); // // muteMenuItem // this.muteMenuItem.Index = 9; this.muteMenuItem.Text = "&Mute"; this.muteMenuItem.Click += new System.EventHandler(this.muteButton_Click); // // menuItem3 // this.menuItem3.Index = 10; this.menuItem3.Text = "-"; // // closeInstanceMenuItem // this.closeInstanceMenuItem.Index = 11; this.closeInstanceMenuItem.Text = "&Close Instance"; this.closeInstanceMenuItem.Click += new System.EventHandler(this.closeInstanceMenuItem_Click); // // mediaProgressBar // this.mediaProgressBar.Cursor = System.Windows.Forms.Cursors.Hand; this.mediaProgressBar.Dock = System.Windows.Forms.DockStyle.Bottom; this.mediaProgressBar.Location = new System.Drawing.Point(0, 147); this.mediaProgressBar.Name = "mediaProgressBar"; this.mediaProgressBar.Size = new System.Drawing.Size(358, 12); this.mediaProgressBar.TabIndex = 56; this.mediaProgressBar.MouseUp += new System.Windows.Forms.MouseEventHandler(this.mediaProgressBar_MouseUp); this.mediaProgressBar.MouseMove += new System.Windows.Forms.MouseEventHandler(this.mediaProgressBar_MouseMove); this.mediaProgressBar.MouseDown += new System.Windows.Forms.MouseEventHandler(this.mediaProgressBar_MouseDown); // // RendererControlForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(358, 159); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.metaDataPanel, this.mediaProgressBar, this.panel2, this.panel1}); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Menu = this.rendererMenu; this.Name = "RendererControlForm"; this.Text = "Renderer"; this.TopMost = true; this.DragDrop += new System.Windows.Forms.DragEventHandler(this.metaDataPanel_DragDrop); this.Closed += new System.EventHandler(this.RendererControlForm_Closed); this.DragEnter += new System.Windows.Forms.DragEventHandler(this.metaDataPanel_DragEnter); this.panel1.ResumeLayout(false); this.panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.volumeTrackBar)).EndInit(); this.metaDataPanel.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void stayOnTopMenuItem_Click(object sender, System.EventArgs e) { stayOnTopMenuItem.Checked = !stayOnTopMenuItem.Checked; this.TopMost = stayOnTopMenuItem.Checked; } protected void RendererRecycledConnectionSink(AVRenderer sender, AVConnection r, object Handle) { if (renderer != sender) MessageBox.Show(this,"Incorrect renderer event"); if (r != connection && (connection == null || (long)Handle == PendingConnection)) { if (connection != null) { connection.OnMediaResourceChanged -= new AVConnection.MediaResourceChangedHandler(OnMediaResourceChangedHandlerSink); connection.OnMute -= new AVConnection.MuteStateChangedHandler(MuteStateChangedHandlerSink); connection.OnPlayStateChanged -= new AVConnection.PlayStateChangedHandler(PlayStateChangedHandlerSink); connection.OnPositionChanged -= new AVConnection.PositionChangedHandler(PositionChangedHandlerSink); connection.OnRemoved -= new AVConnection.RendererHandler(RemovedConnectionHandlerSink); connection.OnVolume -= new AVConnection.VolumeChangedHandler(VolumeChangedHandlerSink); } connection = r; connection.OnMediaResourceChanged += new AVConnection.MediaResourceChangedHandler(OnMediaResourceChangedHandlerSink); connection.OnMute += new AVConnection.MuteStateChangedHandler(MuteStateChangedHandlerSink); connection.OnPlayStateChanged += new AVConnection.PlayStateChangedHandler(PlayStateChangedHandlerSink); connection.OnPositionChanged += new AVConnection.PositionChangedHandler(PositionChangedHandlerSink); connection.OnRemoved += new AVConnection.RendererHandler(RemovedConnectionHandlerSink); connection.OnVolume += new AVConnection.VolumeChangedHandler(VolumeChangedHandlerSink); } UpdateUserInterface(); } protected void RendererRemovedConnectionSink(AVRenderer sender, AVConnection r, object Handle) { UpdateUserInterface(); } protected void RendererCreateConnectionSink(AVRenderer sender, AVConnection r, object Handle) { if (renderer != sender) MessageBox.Show(this,"Incorrect renderer event"); if (connection == null || (long)Handle == PendingConnection) { if (connection != null) { connection.OnMediaResourceChanged -= new AVConnection.MediaResourceChangedHandler(OnMediaResourceChangedHandlerSink); connection.OnMute -= new AVConnection.MuteStateChangedHandler(MuteStateChangedHandlerSink); connection.OnPlayStateChanged -= new AVConnection.PlayStateChangedHandler(PlayStateChangedHandlerSink); connection.OnPositionChanged -= new AVConnection.PositionChangedHandler(PositionChangedHandlerSink); connection.OnRemoved -= new AVConnection.RendererHandler(RemovedConnectionHandlerSink); connection.OnVolume -= new AVConnection.VolumeChangedHandler(VolumeChangedHandlerSink); } connection = r; connection.OnMediaResourceChanged += new AVConnection.MediaResourceChangedHandler(OnMediaResourceChangedHandlerSink); connection.OnMute += new AVConnection.MuteStateChangedHandler(MuteStateChangedHandlerSink); connection.OnPlayStateChanged += new AVConnection.PlayStateChangedHandler(PlayStateChangedHandlerSink); connection.OnPositionChanged += new AVConnection.PositionChangedHandler(PositionChangedHandlerSink); connection.OnRemoved += new AVConnection.RendererHandler(RemovedConnectionHandlerSink); connection.OnVolume += new AVConnection.VolumeChangedHandler(VolumeChangedHandlerSink); UpdateUserInterface(); } } private void OnMediaResourceChangedHandlerSink(AVConnection sender, IMediaResource target) { UpdateUserInterface(); } private void PlayStateChangedHandlerSink(AVConnection sender, AVConnection.PlayState NewState) { if (sender != connection) return; playButton.Image = playPictureBox2.Image; recordButton.Image = recordPictureBox2.Image; stopButton.Image = stopPictureBox2.Image; pauseButton.Image = pausePictureBox2.Image; switch (NewState) { case AVConnection.PlayState.PLAYING: playButton.Image = playPictureBox1.Image; playMenuItem.Checked = true; recordMenuItem.Checked = false; stopMenuItem.Checked = false; pauseMenuItem.Checked = false; break; case AVConnection.PlayState.RECORDING: recordButton.Image = recordPictureBox1.Image; playMenuItem.Checked = false; recordMenuItem.Checked = true; stopMenuItem.Checked = false; pauseMenuItem.Checked = false; break; case AVConnection.PlayState.SEEKING: stopButton.Image = stopPictureBox1.Image; playMenuItem.Checked = false; recordMenuItem.Checked = false; stopMenuItem.Checked = true; pauseMenuItem.Checked = false; break; case AVConnection.PlayState.STOPPED: stopButton.Image = stopPictureBox1.Image; playMenuItem.Checked = false; recordMenuItem.Checked = false; stopMenuItem.Checked = true; pauseMenuItem.Checked = false; break; case AVConnection.PlayState.PAUSED: pauseButton.Image = pausePictureBox1.Image; playMenuItem.Checked = false; recordMenuItem.Checked = false; stopMenuItem.Checked = false; pauseMenuItem.Checked = true; break; } } private void MuteStateChangedHandlerSink(AVConnection sender, bool NewMuteStatus) { if (sender != connection) return; muteMenuItem.Checked = connection.IsMute; if (connection.IsMute == true) { muteButton.Image = mutedPictureBox.Image; } else { muteButton.Image = mutePictureBox.Image; } } private delegate void VolumeChangedHandlerSinkHandler(AVConnection sender, UInt16 Volume); private void VolumeChangedHandlerSink(AVConnection sender, UInt16 Volume) { if (connection != sender) return; if (InvokeRequired) { Invoke(new VolumeChangedHandlerSinkHandler(VolumeChangedHandlerSink), sender, Volume); return; } volumeTrackBar.Value = (int)connection.MasterVolume; } private delegate void CurrentTrackChangedHandler(AVConnection sender, uint track); private void CurrentTrackChangedHandlerSink(AVConnection sender, uint track) { if (sender != connection) return; if (mediaProgressBar.Tag != null) return; if (InvokeRequired) { Invoke(new CurrentTrackChangedHandler(CurrentTrackChangedHandlerSink), sender, track); return; } UpdateUserInterface(); } private delegate void PositionChangedHandler(AVConnection sender, TimeSpan position); private void PositionChangedHandlerSink(AVConnection sender, TimeSpan position) { if (sender != connection) return; if (mediaProgressBar.Tag != null) return; if (InvokeRequired) { Invoke(new PositionChangedHandler(PositionChangedHandlerSink), sender, position); return; } UpdateUserInterface(); } private void RemovedConnectionHandlerSink(AVConnection sender) { if (connection == sender) { // Unplug the connection connection.OnMediaResourceChanged -= new AVConnection.MediaResourceChangedHandler(OnMediaResourceChangedHandlerSink); connection.OnMute -= new AVConnection.MuteStateChangedHandler(MuteStateChangedHandlerSink); connection.OnPlayStateChanged -= new AVConnection.PlayStateChangedHandler(PlayStateChangedHandlerSink); connection.OnPositionChanged -= new AVConnection.PositionChangedHandler(PositionChangedHandlerSink); connection.OnRemoved -= new AVConnection.RendererHandler(RemovedConnectionHandlerSink); connection.OnVolume -= new AVConnection.VolumeChangedHandler(VolumeChangedHandlerSink); connection = null; if (renderer.Connections.Count > 0) { connection = (AVConnection)renderer.Connections[0]; connection.OnMediaResourceChanged += new AVConnection.MediaResourceChangedHandler(OnMediaResourceChangedHandlerSink); connection.OnMute += new AVConnection.MuteStateChangedHandler(MuteStateChangedHandlerSink); connection.OnPlayStateChanged += new AVConnection.PlayStateChangedHandler(PlayStateChangedHandlerSink); connection.OnPositionChanged += new AVConnection.PositionChangedHandler(PositionChangedHandlerSink); connection.OnRemoved += new AVConnection.RendererHandler(RemovedConnectionHandlerSink); connection.OnVolume += new AVConnection.VolumeChangedHandler(VolumeChangedHandlerSink); } } UpdateUserInterface(); } private void UpdateUserInterface() { if (InvokeRequired) { Invoke(new System.Threading.ThreadStart(UpdateUserInterface)); return; } if (renderer.Connections.Count == 0) { rendererInformationLabel.Text = "No connections"; } else if (renderer.Connections.Count == 1) { rendererInformationLabel.Text = "1 connection"; } else { if (connection == null) { rendererInformationLabel.Text = renderer.Connections.Count.ToString() + " connections, none selected"; } else { rendererInformationLabel.Text = renderer.Connections.Count.ToString() + " connections, instance #" + connection.ConnectionID + " selected"; } } instanceButton.Enabled = (renderer.Connections.Count > 1); if (connection != null) { instanceButton.Text = (renderer.Connections.IndexOf(connection)+1).ToString(); if (connection.MediaResource != null) { contentUriLabel.Text = connection.MediaResource.ContentUri; } else { contentUriLabel.Text = "(none)"; } if (mediaProgressBar.Tag == null) { if (connection.SupportsCurrentPosition == true) { mediaProgressBar.Maximum = (int)connection.Duration.TotalSeconds; if((int)connection.CurrentPosition.TotalSeconds <= mediaProgressBar.Maximum) { if (mediaProgressBar.Maximum != 0) mediaProgressBar.Value = (int)connection.CurrentPosition.TotalSeconds; string tf = string.Format("{0:00}",connection.CurrentPosition.Hours) + ":" + string.Format("{0:00}",connection.CurrentPosition.Minutes) + ":" + string.Format("{0:00}",connection.CurrentPosition.Seconds); string d = string.Format("{0:00}",connection.Duration.Hours) + ":" + string.Format("{0:00}",connection.Duration.Minutes) + ":" + string.Format("{0:00}",connection.Duration.Seconds); positionLabel.Text = "Track " + connection.CurrentTrack.ToString() + " of " + connection.NumberOfTracks.ToString() + ", " + tf + " / " + d; } } else { string d = string.Format("{0:00}",connection.Duration.Hours) + ":" + string.Format("{0:00}",connection.Duration.Minutes) + ":" + string.Format("{0:00}",connection.Duration.Seconds); positionLabel.Text = "Track " + connection.CurrentTrack.ToString() + " of " + connection.NumberOfTracks.ToString() + ", Duration " + d; } } muteMenuItem.Checked = connection.IsMute; if (connection.IsMute == true) { muteButton.Image = mutedPictureBox.Image; } else { muteButton.Image = mutePictureBox.Image; } } else { instanceButton.Text = "-"; contentUriLabel.Text = "(none)"; positionLabel.Text = "00:00:00"; } if(connection!=null) { if(connection.SupportsRecord) { recordButton.Enabled = true; } else { recordButton.Enabled = false; } if(connection.SupportsPause) { pauseButton.Enabled = true; } else { pauseButton.Enabled = false; } // Reset Event Values this.PlayStateChangedHandlerSink(connection,connection.CurrentState); foreach(string channel in connection.SupportedChannels) { if(channel=="Master") volumeTrackBar.Value = (int) connection.MasterVolume; } } } private void metaDataPanel_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) { if (e.Data.GetDataPresent(typeof(MediaItem[])) == true) { MediaItem[] items = (MediaItem[])e.Data.GetData(typeof(MediaItem[])); if (items.Length > 0) SetupConnection(items); } if (e.Data.GetDataPresent(typeof(string)) == true) { string stritems = (string)e.Data.GetData(typeof(string)); ArrayList items = MediaBuilder.BuildMediaBranches(stritems,typeof(MediaItem),typeof(MediaContainer)); if (items.Count > 0) SetupConnection((MediaItem[])items.ToArray(typeof(MediaItem))); } } public void SetupConnection(MediaItem[] items) { if (items == null || items.Length == 0) return; PendingConnection = DateTime.Now.Ticks; renderer.CreateConnection(items, PendingConnection); } public void SetupConnection(ICpContainer container) { if (container == null) return; PendingConnection = DateTime.Now.Ticks; renderer.CreateConnection(container, PendingConnection); } private void metaDataPanel_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) { if(e.Data.GetDataPresent(typeof(CpMediaItem[]))) { CpMediaItem[] items = (CpMediaItem[])e.Data.GetData(typeof(CpMediaItem[])); if (items != null && items.Length > 0) { // TODO: Check to see if one of the resources is compatible with the renderer e.Effect = DragDropEffects.Copy; } } if (e.Data.GetDataPresent(typeof(string)) == true) { string items = (string)e.Data.GetData(typeof(string)); if (items != null && items.StartsWith("<DIDL-Lite ")) { e.Effect = DragDropEffects.Copy; } } } private void playButton_Click(object sender, System.EventArgs e) { if (connection != null) {connection.Play();} } private void recordButton_Click(object sender, System.EventArgs e) { if (connection != null) {connection.Record();} } private void stopButton_Click(object sender, System.EventArgs e) { if (connection != null) {connection.Stop();} } private void pauseButton_Click(object sender, System.EventArgs e) { if (connection != null) {connection.Pause();} } private void muteButton_Click(object sender, System.EventArgs e) { if (connection == null) return; if (muteButton.Image == mutedPictureBox.Image) { connection.Mute(false); } else { connection.Mute(true); } } private void volumeTrackBar_Scroll(object sender, System.EventArgs e) { if (connection == null) return; connection.MasterVolume = (ushort)volumeTrackBar.Value; } private void RendererControlForm_Closed(object sender, System.EventArgs e) { if (connection != null) { connection.OnMediaResourceChanged -= new AVConnection.MediaResourceChangedHandler(OnMediaResourceChangedHandlerSink); connection.OnMute -= new AVConnection.MuteStateChangedHandler(MuteStateChangedHandlerSink); connection.OnPlayStateChanged -= new AVConnection.PlayStateChangedHandler(PlayStateChangedHandlerSink); connection.OnPositionChanged -= new AVConnection.PositionChangedHandler(PositionChangedHandlerSink); connection.OnRemoved -= new AVConnection.RendererHandler(RemovedConnectionHandlerSink); connection.OnVolume -= new AVConnection.VolumeChangedHandler(VolumeChangedHandlerSink); connection = null; } parent.RendererControlFormClose(this,renderer); } private void menuItem10_Click(object sender, System.EventArgs e) { Close(); } private void prevTrackButton_Click(object sender, System.EventArgs e) { connection.PreviousTrack(); } private void nextTrackButton_Click(object sender, System.EventArgs e) { connection.NextTrack(); } private void audioControlsMenuItem_Click(object sender, System.EventArgs e) { rendererAudioControlForm = new RendererAudioControlForm(); rendererAudioControlForm.Connection = connection; rendererAudioControlForm.ShowDialog(this); rendererAudioControlForm.Dispose(); rendererAudioControlForm = null; } private void instanceButton_Click(object sender, System.EventArgs e) { int i = renderer.Connections.IndexOf(connection)+1; if (i >= renderer.Connections.Count) i = 0; AVConnection nextconnection = (AVConnection)renderer.Connections[i]; if (nextconnection == null || nextconnection == connection) return; // Unplug the connection connection.OnMediaResourceChanged -= new AVConnection.MediaResourceChangedHandler(OnMediaResourceChangedHandlerSink); connection.OnMute -= new AVConnection.MuteStateChangedHandler(MuteStateChangedHandlerSink); connection.OnPlayStateChanged -= new AVConnection.PlayStateChangedHandler(PlayStateChangedHandlerSink); connection.OnPositionChanged -= new AVConnection.PositionChangedHandler(PositionChangedHandlerSink); connection.OnRemoved -= new AVConnection.RendererHandler(RemovedConnectionHandlerSink); connection.OnVolume -= new AVConnection.VolumeChangedHandler(VolumeChangedHandlerSink); // Setup the new one connection = nextconnection; connection.OnMediaResourceChanged += new AVConnection.MediaResourceChangedHandler(OnMediaResourceChangedHandlerSink); connection.OnMute += new AVConnection.MuteStateChangedHandler(MuteStateChangedHandlerSink); connection.OnPlayStateChanged += new AVConnection.PlayStateChangedHandler(PlayStateChangedHandlerSink); connection.OnPositionChanged += new AVConnection.PositionChangedHandler(PositionChangedHandlerSink); connection.OnRemoved += new AVConnection.RendererHandler(RemovedConnectionHandlerSink); connection.OnVolume += new AVConnection.VolumeChangedHandler(VolumeChangedHandlerSink); UpdateUserInterface(); } private void mediaProgressBar_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { mediaProgressBar.Tag = "Seek Lock"; double seekTargetRatio = ((double)e.X) / ((double)mediaProgressBar.Width); if (seekTargetRatio > 1) seekTargetRatio = 1; if (seekTargetRatio < 0) seekTargetRatio = 0; mediaProgressBar.Value = (int)(((double)mediaProgressBar.Maximum) * seekTargetRatio); } private void mediaProgressBar_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { double seekTargetRatio = (double)e.X / (double)mediaProgressBar.Width; if (seekTargetRatio > 1) seekTargetRatio = 1; if (seekTargetRatio < 0) seekTargetRatio = 0; if (connection.Duration.Ticks != 0) { TimeSpan target = new TimeSpan((long)((double)connection.Duration.Ticks * seekTargetRatio)); connection.SeekPosition(target); mediaProgressBar.Maximum = (int)connection.Duration.TotalSeconds; if (mediaProgressBar.Maximum != 0) mediaProgressBar.Value = (int)connection.CurrentPosition.TotalSeconds; } mediaProgressBar.Tag = null; UpdateUserInterface(); } private void mediaProgressBar_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Right) { double seekTargetRatio = (double)e.X / (double)mediaProgressBar.Width; if (seekTargetRatio > 1) seekTargetRatio = 1; if (seekTargetRatio < 0) seekTargetRatio = 0; mediaProgressBar.Value = (int)((double)mediaProgressBar.Maximum * seekTargetRatio); TimeSpan target = new TimeSpan((long)((double)connection.Duration.Ticks * seekTargetRatio)); string tf = string.Format("{0:00}",target.Hours) + ":" + string.Format("{0:00}",target.Minutes) + ":" + string.Format("{0:00}",target.Seconds); string d = string.Format("{0:00}",connection.Duration.Hours) + ":" + string.Format("{0:00}",connection.Duration.Minutes) + ":" + string.Format("{0:00}",connection.Duration.Seconds); positionLabel.Text = "Track " + connection.CurrentTrack.ToString() + " of " + connection.NumberOfTracks.ToString() + ", " + tf + " / " + d; } } private void closeInstanceMenuItem_Click(object sender, System.EventArgs e) { if (connection != null) { connection.Close(); } } private void menuItem2_Popup(object sender, System.EventArgs e) { closeInstanceMenuItem.Enabled = (connection != null && connection.IsCloseSupported == true); } private void menuItem7_Click(object sender, System.EventArgs e) { /* if (rendererDebugForm == null) rendererDebugForm = new RendererDebugForm(renderer); rendererDebugForm.Show(); rendererDebugForm.Activate(); */ } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNet.SignalR.Client.Http; using Microsoft.AspNet.SignalR.Client.Infrastructure; using Microsoft.AspNet.SignalR.Client.Transports; using Microsoft.AspNet.SignalR.Infrastructure; using Newtonsoft.Json; using Newtonsoft.Json.Linq; #if (NET4 || NET45) using System.Security.Cryptography.X509Certificates; #endif namespace Microsoft.AspNet.SignalR.Client { /// <summary> /// Provides client connections for SignalR services. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "_disconnectCts is disposed on disconnect.")] public class Connection : IConnection, IDisposable { internal static readonly TimeSpan DefaultAbortTimeout = TimeSpan.FromSeconds(30); private static Version _assemblyVersion; private IClientTransport _transport; // Propagates notification that connection should be stopped. private CancellationTokenSource _disconnectCts; // The amount of time the client should attempt to reconnect before stopping. private TimeSpan _disconnectTimeout; // The amount of time a transport will wait (while connecting) before failing. private TimeSpan _totalTransportConnectTimeout; // Provides a way to cancel the the timeout that stops a reconnect cycle private IDisposable _disconnectTimeoutOperation; // The default connection state is disconnected private ConnectionState _state; private KeepAliveData _keepAliveData; private TimeSpan _reconnectWindow; private Task _connectTask; private TextWriter _traceWriter; private string _connectionData; private TaskQueue _receiveQueue; private Task _lastQueuedReceiveTask; private TaskCompletionSource<object> _startTcs; // Used to synchronize state changes private readonly object _stateLock = new object(); // Used to synchronize starting and stopping specifically private readonly object _startLock = new object(); // Used to ensure we don't write to the Trace TextWriter from multiple threads simultaneously private readonly object _traceLock = new object(); private DateTime _lastMessageAt; // Indicates the last time we marked the C# code as running. private DateTime _lastActiveAt; // Keeps track of when the last keep alive from the server was received private HeartbeatMonitor _monitor; //The json serializer for the connections private JsonSerializer _jsonSerializer = new JsonSerializer(); #if (NET4 || NET45) private readonly X509CertificateCollection _certCollection = new X509CertificateCollection(); #endif /// <summary> /// Occurs when the <see cref="Connection"/> has received data from the server. /// </summary> public event Action<string> Received; /// <summary> /// Occurs when the <see cref="Connection"/> has encountered an error. /// </summary> public event Action<Exception> Error; /// <summary> /// Occurs when the <see cref="Connection"/> is stopped. /// </summary> public event Action Closed; /// <summary> /// Occurs when the <see cref="Connection"/> starts reconnecting after an error. /// </summary> public event Action Reconnecting; /// <summary> /// Occurs when the <see cref="Connection"/> successfully reconnects after a timeout. /// </summary> public event Action Reconnected; /// <summary> /// Occurs when the <see cref="Connection"/> state changes. /// </summary> public event Action<StateChange> StateChanged; /// <summary> /// Occurs when the <see cref="Connection"/> is about to timeout /// </summary> public event Action ConnectionSlow; /// <summary> /// Initializes a new instance of the <see cref="Connection"/> class. /// </summary> /// <param name="url">The url to connect to.</param> public Connection(string url) : this(url, (string)null) { } /// <summary> /// Initializes a new instance of the <see cref="Connection"/> class. /// </summary> /// <param name="url">The url to connect to.</param> /// <param name="queryString">The query string data to pass to the server.</param> public Connection(string url, IDictionary<string, string> queryString) : this(url, CreateQueryString(queryString)) { } /// <summary> /// Initializes a new instance of the <see cref="Connection"/> class. /// </summary> /// <param name="url">The url to connect to.</param> /// <param name="queryString">The query string data to pass to the server.</param> public Connection(string url, string queryString) { if (url == null) { throw new ArgumentNullException("url"); } if (url.Contains("?")) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.Error_UrlCantContainQueryStringDirectly), "url"); } if (!url.EndsWith("/", StringComparison.Ordinal)) { url += "/"; } Url = url; QueryString = queryString; _disconnectTimeoutOperation = DisposableAction.Empty; _lastMessageAt = DateTime.UtcNow; _lastActiveAt = DateTime.UtcNow; _reconnectWindow = TimeSpan.Zero; Items = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); State = ConnectionState.Disconnected; TraceLevel = TraceLevels.All; TraceWriter = new DebugTextWriter(); Headers = new HeaderDictionary(this); TransportConnectTimeout = TimeSpan.Zero; _totalTransportConnectTimeout = TimeSpan.Zero; // Current client protocol Protocol = new Version(1, 4); } /// <summary> /// The amount of time a transport will wait (while connecting) before failing. /// This value is modified by adding the server's TransportConnectTimeout configuration value. /// </summary> public TimeSpan TransportConnectTimeout { get; set; } /// <summary> /// The amount of time a transport will wait (while connecting) before failing. /// This is the total vaue obtained by adding the server's configuration value and the timeout specified by the user /// </summary> TimeSpan IConnection.TotalTransportConnectTimeout { get { return _totalTransportConnectTimeout; } } public Version Protocol { get; set; } /// <summary> /// Gets the last error encountered by the <see cref="Connection"/>. /// </summary> public Exception LastError { get; private set; } /// <summary> /// The maximum amount of time a connection will allow to try and reconnect. /// This value is equivalent to the summation of the servers disconnect and keep alive timeout values. /// </summary> TimeSpan IConnection.ReconnectWindow { get { return _reconnectWindow; } set { _reconnectWindow = value; } } /// <summary> /// Object to store the various keep alive timeout values /// </summary> KeepAliveData IConnection.KeepAliveData { get { return _keepAliveData; } set { _keepAliveData = value; } } /// <summary> /// The timestamp of the last message received by the connection. /// </summary> DateTime IConnection.LastMessageAt { get { return _lastMessageAt; } } DateTime IConnection.LastActiveAt { get { return _lastActiveAt; } } #if NET4 || NET45 X509CertificateCollection IConnection.Certificates { get { return _certCollection; } } #endif public TraceLevels TraceLevel { get; set; } public TextWriter TraceWriter { get { return _traceWriter; } set { if (value == null) { throw new ArgumentNullException("value"); } _traceWriter = value; } } /// <summary> /// Gets or sets the serializer used by the connection /// </summary> public JsonSerializer JsonSerializer { get { return _jsonSerializer; } set { if (value == null) { throw new ArgumentNullException("value"); } _jsonSerializer = value; } } /// <summary> /// Gets or sets the cookies associated with the connection. /// </summary> public CookieContainer CookieContainer { get; set; } /// <summary> /// Gets or sets authentication information for the connection. /// </summary> public ICredentials Credentials { get; set; } /// <summary> /// Gets and sets headers for the requests /// </summary> public IDictionary<string, string> Headers { get; private set; } #if !PORTABLE /// <summary> /// Gets of sets proxy information for the connection. /// </summary> public IWebProxy Proxy { get; set; } #endif /// <summary> /// Gets the url for the connection. /// </summary> public string Url { get; private set; } /// <summary> /// Gets or sets the last message id for the connection. /// </summary> public string MessageId { get; set; } /// <summary> /// Gets or sets the connection id for the connection. /// </summary> public string ConnectionId { get; set; } /// <summary> /// Gets or sets the connection token for the connection. /// </summary> public string ConnectionToken { get; set; } /// <summary> /// Gets or sets the groups token for the connection. /// </summary> public string GroupsToken { get; set; } /// <summary> /// Gets a dictionary for storing state for a the connection. /// </summary> public IDictionary<string, object> Items { get; private set; } /// <summary> /// Gets the querystring specified in the ctor. /// </summary> public string QueryString { get; private set; } public IClientTransport Transport { get { return _transport; } } /// <summary> /// Gets the current <see cref="ConnectionState"/> of the connection. /// </summary> public ConnectionState State { get { return _state; } private set { lock (_stateLock) { if (_state != value) { var stateChange = new StateChange(oldState: _state, newState: value); _state = value; if (StateChanged != null) { StateChanged(stateChange); } } } } } /// <summary> /// Starts the <see cref="Connection"/>. /// </summary> /// <returns>A task that represents when the connection has started.</returns> public Task Start() { return Start(new DefaultHttpClient()); } /// <summary> /// Starts the <see cref="Connection"/>. /// </summary> /// <param name="httpClient">The http client</param> /// <returns>A task that represents when the connection has started.</returns> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This is disposed on close")] public Task Start(IHttpClient httpClient) { // Pick the best transport supported by the client return Start(new AutoTransport(httpClient)); } /// <summary> /// Starts the <see cref="Connection"/>. /// </summary> /// <param name="transport">The transport to use.</param> /// <returns>A task that represents when the connection has started.</returns> public Task Start(IClientTransport transport) { lock (_startLock) { if (!ChangeState(ConnectionState.Disconnected, ConnectionState.Connecting)) { return _connectTask ?? TaskAsyncHelper.Empty; } _disconnectCts = new CancellationTokenSource(); _startTcs = new TaskCompletionSource<object>(); _receiveQueue = new TaskQueue(_startTcs.Task); _lastQueuedReceiveTask = TaskAsyncHelper.Empty; _transport = transport; _connectTask = Negotiate(transport); } return _connectTask; } protected virtual string OnSending() { return null; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is flowed back to the caller via the tcs.")] private Task Negotiate(IClientTransport transport) { _connectionData = OnSending(); return transport.Negotiate(this, _connectionData) .Then(negotiationResponse => { VerifyProtocolVersion(negotiationResponse.ProtocolVersion); ConnectionId = negotiationResponse.ConnectionId; ConnectionToken = negotiationResponse.ConnectionToken; _disconnectTimeout = TimeSpan.FromSeconds(negotiationResponse.DisconnectTimeout); _totalTransportConnectTimeout = TransportConnectTimeout + TimeSpan.FromSeconds(negotiationResponse.TransportConnectTimeout); // Default the beat interval to be 5 seconds in case keep alive is disabled. var beatInterval = TimeSpan.FromSeconds(5); // If we have a keep alive if (negotiationResponse.KeepAliveTimeout != null) { _keepAliveData = new KeepAliveData(TimeSpan.FromSeconds(negotiationResponse.KeepAliveTimeout.Value)); _reconnectWindow = _disconnectTimeout + _keepAliveData.Timeout; beatInterval = _keepAliveData.CheckInterval; } else { _reconnectWindow = _disconnectTimeout; } _monitor = new HeartbeatMonitor(this, _stateLock, beatInterval); return StartTransport(); }) .ContinueWithNotComplete(() => Disconnect()); } private Task StartTransport() { return _transport.Start(this, _connectionData, _disconnectCts.Token) .RunSynchronously(() => { // NOTE: We have tests that rely on this state change occuring *BEFORE* the start task is complete ChangeState(ConnectionState.Connecting, ConnectionState.Connected); // Now that we're connected complete the start task that the // receive queue is waiting on _startTcs.SetResult(null); // Start the monitor to check for server activity _lastMessageAt = DateTime.UtcNow; _lastActiveAt = DateTime.UtcNow; _monitor.Start(); }) // Don't return until the last receive has been processed to ensure messages/state sent in OnConnected // are processed prior to the Start() method task finishing .Then(() => _lastQueuedReceiveTask); } private bool ChangeState(ConnectionState oldState, ConnectionState newState) { return ((IConnection)this).ChangeState(oldState, newState); } bool IConnection.ChangeState(ConnectionState oldState, ConnectionState newState) { lock (_stateLock) { // If we're in the expected old state then change state and return true if (_state == oldState) { Trace(TraceLevels.StateChanges, "ChangeState({0}, {1})", oldState, newState); State = newState; return true; } } // Invalid transition return false; } private void VerifyProtocolVersion(string versionString) { Version version; if (String.IsNullOrEmpty(versionString) || !TryParseVersion(versionString, out version) || version != Protocol) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.Error_IncompatibleProtocolVersion, Protocol, versionString ?? "null")); } } /// <summary> /// Stops the <see cref="Connection"/> and sends an abort message to the server. /// </summary> public void Stop() { Stop(DefaultAbortTimeout); } /// <summary> /// Stops the <see cref="Connection"/> and sends an abort message to the server. /// <param name="error">The error due to which the connection is being stopped.</param> /// </summary> public void Stop(Exception error) { Stop(error, DefaultAbortTimeout); } /// <summary> /// Stops the <see cref="Connection"/> and sends an abort message to the server. /// <param name="error">The error due to which the connection is being stopped.</param> /// <param name="timeout">The timeout</param> /// </summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't want to raise the Start exception on Stop.")] public void Stop(Exception error, TimeSpan timeout) { OnError(error); Stop(timeout); } /// <summary> /// Stops the <see cref="Connection"/> and sends an abort message to the server. /// <param name="timeout">The timeout</param> /// </summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't want to raise the Start exception on Stop.")] public void Stop(TimeSpan timeout) { lock (_startLock) { // Wait for the connection to connect if (_connectTask != null) { try { _connectTask.Wait(timeout); } catch (Exception ex) { Trace(TraceLevels.Events, "Error: {0}", ex.GetBaseException()); } } if (_receiveQueue != null) { // Close the receive queue so currently running receive callback finishes and no more are run. // We can't wait on the result of the drain because this method may be on the stack of the task returned (aka deadlock). _receiveQueue.Drain().Catch(); } // This is racy since it's outside the _stateLock, but we are trying to avoid 30s deadlocks when calling _transport.Abort() if (State == ConnectionState.Disconnected) { return; } Trace(TraceLevels.Events, "Stop"); // Dispose the heart beat monitor so we don't fire notifications when waiting to abort _monitor.Dispose(); _transport.Abort(this, timeout, _connectionData); Disconnect(); } } /// <summary> /// Stops the <see cref="Connection"/> without sending an abort message to the server. /// This function is called after we receive a disconnect message from the server. /// </summary> void IConnection.Disconnect() { Disconnect(); } private void Disconnect() { lock (_stateLock) { // Do nothing if the connection is offline if (State != ConnectionState.Disconnected) { // Change state before doing anything else in case something later in the method throws State = ConnectionState.Disconnected; Trace(TraceLevels.StateChanges, "Disconnected"); _disconnectTimeoutOperation.Dispose(); _disconnectCts.Cancel(); _disconnectCts.Dispose(); if (_monitor != null) { _monitor.Dispose(); } if (_transport != null) { Trace(TraceLevels.Events, "Transport.Dispose({0})", ConnectionId); _transport.Dispose(); _transport = null; } Trace(TraceLevels.Events, "Closed"); // Clear the state for this connection ConnectionId = null; ConnectionToken = null; GroupsToken = null; MessageId = null; _connectionData = null; #if NETFX_CORE || PORTABLE // Clear the buffer _traceWriter.Flush(); #endif // TODO: Do we want to trigger Closed if we are connecting? OnClosed(); } } } protected virtual void OnClosed() { if (Closed != null) { Closed(); } } /// <summary> /// Sends data asynchronously over the connection. /// </summary> /// <param name="data">The data to send.</param> /// <returns>A task that represents when the data has been sent.</returns> public virtual Task Send(string data) { if (State == ConnectionState.Disconnected) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.Error_DataCannotBeSentConnectionDisconnected)); } if (State == ConnectionState.Connecting) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.Error_ConnectionHasNotBeenEstablished)); } return _transport.Send(this, data, _connectionData); } /// <summary> /// Sends an object that will be JSON serialized asynchronously over the connection. /// </summary> /// <param name="value">The value to serialize.</param> /// <returns>A task that represents when the data has been sent.</returns> public Task Send(object value) { return Send(this.JsonSerializeObject(value)); } #if (NET4 || NET45) /// <summary> /// Adds a client certificate to the request /// </summary> /// <param name="certificate">Client Certificate</param> public void AddClientCertificate(X509Certificate certificate) { lock (_stateLock) { if (State != ConnectionState.Disconnected) { throw new InvalidOperationException(Resources.Error_CertsCanOnlyBeAddedWhenDisconnected); } _certCollection.Add(certificate); } } #endif public void Trace(TraceLevels level, string format, params object[] args) { lock (_traceLock) { if (TraceLevel.HasFlag(level)) { _traceWriter.WriteLine( DateTime.UtcNow.ToString("HH:mm:ss.fffffff", CultureInfo.InvariantCulture) + " - " + (ConnectionId ?? "null") + " - " + format, args); } } } [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "This is called by the transport layer")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is raised via an event.")] void IConnection.OnReceived(JToken message) { _lastQueuedReceiveTask = _receiveQueue.Enqueue(() => Task.Factory.StartNew(() => { try { OnMessageReceived(message); } catch (Exception ex) { OnError(ex); } })); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception can be from user code, needs to be a catch all.")] [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "This is called by the transport layer")] protected virtual void OnMessageReceived(JToken message) { if (Received != null) { // #1889: We now have a try-catch in the OnMessageReceived handler. One note about this change is that // messages that are triggered via responses to server invocations will no longer be wrapped in an // aggregate exception due to this change. This makes the exception throwing behavior consistent across // all types of receive triggers. try { Received(message.ToString()); } catch (Exception ex) { OnError(ex); } } } private void OnError(Exception error) { Trace(TraceLevels.Events, "OnError({0})", error); LastError = error; if (Error != null) { Error(error); } } void IConnection.OnError(Exception error) { OnError(error); } void IConnection.OnReconnecting() { OnReconnecting(); } internal virtual void OnReconnecting() { // Only allow the client to attempt to reconnect for a _disconnectTimout TimeSpan which is set by // the server during negotiation. // If the client tries to reconnect for longer the server will likely have deleted its ConnectionId // topic along with the contained disconnect message. _disconnectTimeoutOperation = SetTimeout( _disconnectTimeout, () => { OnError(new TimeoutException(String.Format(CultureInfo.CurrentCulture, Resources.Error_ReconnectTimeout, _disconnectTimeout))); Disconnect(); }); #if NETFX_CORE || PORTABLE // Clear the buffer _traceWriter.Flush(); #endif if (Reconnecting != null) { Reconnecting(); } } void IConnection.OnReconnected() { // Prevent the timeout set OnReconnecting from firing and stopping the connection if we have successfully // reconnected before the _disconnectTimeout delay. _disconnectTimeoutOperation.Dispose(); if (Reconnected != null) { Reconnected(); } ((IConnection)this).MarkLastMessage(); } void IConnection.OnConnectionSlow() { Trace(TraceLevels.Events, "OnConnectionSlow"); if (ConnectionSlow != null) { ConnectionSlow(); } } /// <summary> /// Sets LastMessageAt to the current time /// </summary> void IConnection.MarkLastMessage() { _lastMessageAt = DateTime.UtcNow; } /// <summary> /// Sets LastActiveAt to the current time /// </summary> void IConnection.MarkActive() { // Ensure that we haven't gone to sleep since our last "active" marking. if (TransportHelper.VerifyLastActive(this)) { _lastActiveAt = DateTime.UtcNow; } } [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "This is called by the transport layer")] void IConnection.PrepareRequest(IRequest request) { #if PORTABLE // Cannot set user agent for Portable because SL does not support it. #elif NETFX_CORE request.UserAgent = CreateUserAgentString("SignalR.Client.WinRT"); #elif NET45 request.UserAgent = CreateUserAgentString("SignalR.Client.NET45"); #else request.UserAgent = CreateUserAgentString("SignalR.Client.NET4"); #endif request.SetRequestHeaders(Headers); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Can be called via other clients.")] private static string CreateUserAgentString(string client) { if (_assemblyVersion == null) { #if NETFX_CORE _assemblyVersion = new Version("2.1.1"); #else _assemblyVersion = new AssemblyName(typeof(Connection).Assembly.FullName).Version; #endif } #if NETFX_CORE || PORTABLE return String.Format(CultureInfo.InvariantCulture, "{0}/{1} ({2})", client, _assemblyVersion, "Unknown OS"); #else return String.Format(CultureInfo.InvariantCulture, "{0}/{1} ({2})", client, _assemblyVersion, Environment.OSVersion); #endif } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The Version constructor can throw exceptions of many different types. Failure is indicated by returning false.")] private static bool TryParseVersion(string versionString, out Version version) { #if PORTABLE try { version = new Version(versionString); return true; } catch { version = null; return false; } #else return Version.TryParse(versionString, out version); #endif } private static string CreateQueryString(IDictionary<string, string> queryString) { return String.Join("&", queryString.Select(kvp => kvp.Key + "=" + kvp.Value).ToArray()); } // TODO: Refactor into a helper class private static IDisposable SetTimeout(TimeSpan delay, Action operation) { var cancellableInvoker = new ThreadSafeInvoker(); TaskAsyncHelper.Delay(delay).Then(() => cancellableInvoker.Invoke(operation)); // Disposing this return value will cancel the operation if it has not already been invoked. return new DisposableAction(() => cancellableInvoker.Invoke()); } /// <summary> /// Default text writer /// </summary> private class DebugTextWriter : TextWriter { #if NETFX_CORE || PORTABLE private readonly StringBuilder _buffer; #endif public DebugTextWriter() : base(CultureInfo.InvariantCulture) { #if NETFX_CORE || PORTABLE _buffer = new StringBuilder(); #endif } public override void WriteLine(string value) { Debug.WriteLine(value); } #if NETFX_CORE || PORTABLE public override void Write(char value) { lock (_buffer) { if (value == '\n') { Flush(); } else { _buffer.Append(value); } } } #endif public override Encoding Encoding { get { return Encoding.UTF8; } } #if NETFX_CORE || PORTABLE public override void Flush() { Debug.WriteLine(_buffer.ToString()); _buffer.Clear(); } #endif } /// <summary> /// Stop the connection, equivalent to calling connection.stop /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Stop the connection, equivalent to calling connection.stop /// </summary> /// <param name="disposing">Set this to true to perform the dispose, false to do nothing</param> protected virtual void Dispose(bool disposing) { if (disposing) { Stop(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Irony.Parsing { [Flags] public enum OutlineOptions { None = 0, ProduceIndents = 0x01, CheckBraces = 0x02, CheckOperator = 0x04, //to implement, auto line joining if line ends with operator } public class CodeOutlineFilter : TokenFilter { public readonly OutlineOptions Options; public readonly KeyTerm ContinuationTerminal; //Terminal readonly GrammarData _grammarData; readonly Grammar _grammar; ParsingContext _context; readonly bool _produceIndents; readonly bool _checkBraces; readonly bool _checkOperator; public Stack<int> Indents = new Stack<int>(); public Token CurrentToken; public Token PreviousToken; public SourceLocation PreviousTokenLocation; public TokenStack OutputTokens = new TokenStack(); bool _isContinuation, _prevIsContinuation; bool _isOperator, _prevIsOperator; bool _doubleEof; #region constructor public CodeOutlineFilter(GrammarData grammarData, OutlineOptions options, KeyTerm continuationTerminal) { _grammarData = grammarData; _grammar = grammarData.Grammar; _grammar.LanguageFlags |= LanguageFlags.EmitLineStartToken; Options = options; ContinuationTerminal = continuationTerminal; if (ContinuationTerminal != null) if (!_grammar.NonGrammarTerminals.Contains(ContinuationTerminal)) _grammarData.Language.Errors.Add(GrammarErrorLevel.Warning, null, Resources.ErrOutlineFilterContSymbol, ContinuationTerminal.Name); //"CodeOutlineFilter: line continuation symbol '{0}' should be added to Grammar.NonGrammarTerminals list.", _produceIndents = OptionIsSet(OutlineOptions.ProduceIndents); _checkBraces = OptionIsSet(OutlineOptions.CheckBraces); _checkOperator = OptionIsSet(OutlineOptions.CheckOperator); Reset(); } #endregion public override void Reset() { base.Reset(); Indents.Clear(); Indents.Push(0); OutputTokens.Clear(); PreviousToken = null; CurrentToken = null; PreviousTokenLocation = new SourceLocation(); } public bool OptionIsSet(OutlineOptions option) { return (Options & option) != 0; } public override IEnumerable<Token> BeginFiltering(ParsingContext context, IEnumerable<Token> tokens) { _context = context; foreach (Token token in tokens) { ProcessToken(token); while (OutputTokens.Count > 0) yield return OutputTokens.Pop(); }//foreach }//method public void ProcessToken(Token token) { SetCurrentToken(token); //Quick checks if (_isContinuation) return; var tokenTerm = token.Terminal; //check EOF if (tokenTerm == _grammar.Eof) { ProcessEofToken(); return; } if (tokenTerm != _grammar.LineStartTerminal) return; //if we are here, we have LineStart token on new line; first remove it from stream, it should not go to parser OutputTokens.Pop(); if (PreviousToken == null) return; // first check if there was continuation symbol before // or - if checkBraces flag is set - check if there were open braces if (_prevIsContinuation || _checkBraces && _context.OpenBraces.Count > 0) return; //no Eos token in this case if (_prevIsOperator && _checkOperator) return; //no Eos token in this case //We need to produce Eos token and indents (if _produceIndents is set). // First check indents - they go first into OutputTokens stack, so they will be popped out last if (_produceIndents) { var currIndent = token.Location.Column; var prevIndent = Indents.Peek(); if (currIndent > prevIndent) { Indents.Push(currIndent); PushOutlineToken(_grammar.Indent, token.Location); } else if (currIndent < prevIndent) { PushDedents(currIndent); //check that current indent exactly matches the previous indent if (Indents.Peek() != currIndent) { //fire error OutputTokens.Push(new Token(_grammar.SyntaxError, token.Location, string.Empty, Resources.ErrInvDedent)); // "Invalid dedent level, no previous matching indent found." } } }//if _produceIndents //Finally produce Eos token, but not in command line mode. In command line mode the Eos was already produced // when we encountered Eof on previous line if (_context.Mode != ParseMode.CommandLine) { var eosLocation = ComputeEosLocation(); PushOutlineToken(_grammar.Eos, eosLocation); } }//method private void SetCurrentToken(Token token) { _doubleEof = CurrentToken != null && CurrentToken.Terminal == _grammar.Eof && token.Terminal == _grammar.Eof; //Copy CurrentToken to PreviousToken if (CurrentToken != null && CurrentToken.Category == TokenCategory.Content) { //remember only content tokens PreviousToken = CurrentToken; _prevIsContinuation = _isContinuation; _prevIsOperator = _isOperator; if (PreviousToken != null) PreviousTokenLocation = PreviousToken.Location; } CurrentToken = token; _isContinuation = (token.Terminal == ContinuationTerminal && ContinuationTerminal != null); _isOperator = token.Terminal.Flags.IsSet(TermFlags.IsOperator); if (!_isContinuation) OutputTokens.Push(token); //by default input token goes to output, except continuation symbol } //Processes Eof token. We should take into account the special case of processing command line input. // In this case we should not automatically dedent all stacked indents if we get EOF. // Note that tokens will be popped from the OutputTokens stack and sent to parser in the reverse order compared to // the order we pushed them into OutputTokens stack. We have Eof already in stack; we first push dedents, then Eos // They will come out to parser in the following order: Eos, Dedents, Eof. private void ProcessEofToken() { //First decide whether we need to produce dedents and Eos symbol bool pushDedents = false; bool pushEos = true; switch (_context.Mode) { case ParseMode.File: pushDedents = _produceIndents; //Do dedents if token filter tracks indents break; case ParseMode.CommandLine: //only if user entered empty line, we dedent all pushDedents = _produceIndents && _doubleEof; pushEos = !_prevIsContinuation && !_doubleEof; //if previous symbol is continuation symbol then don't push Eos break; case ParseMode.VsLineScan: pushDedents = false; //Do not dedent at all on every line end break; } //unindent all buffered indents; if (pushDedents) PushDedents(0); //now push Eos token - it will be popped first, then dedents, then EOF token if (pushEos) { var eosLocation = ComputeEosLocation(); PushOutlineToken(_grammar.Eos, eosLocation); } } private void PushDedents(int untilPosition) { while (Indents.Peek() > untilPosition) { Indents.Pop(); PushOutlineToken(_grammar.Dedent, CurrentToken.Location); } } private SourceLocation ComputeEosLocation() { if (PreviousToken == null) return new SourceLocation(); //Return position at the end of previous token var loc = PreviousToken.Location; var len = PreviousToken.Length; return new SourceLocation(loc.Position + len, loc.Line, loc.Column + len); } private void PushOutlineToken(Terminal term, SourceLocation location) { OutputTokens.Push(new Token(term, location, string.Empty, null)); } }//class }//namespace
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // CESchedulerPairTests.cs // Tests Ported from the TPL test bed // // Summary: // Implements the tests for the new scheduler ConcurrentExclusiveSchedulerPair // // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using System.Security; using Xunit; using System.Diagnostics; namespace System.Threading.Tasks.Tests { public class TrackingTaskScheduler : TaskScheduler { public TrackingTaskScheduler(int maxConLevel) { //We need to set the value to 1 so that each time a scheduler is created, its tasks will start with one. _counter = 1; if (maxConLevel < 1 && maxConLevel != -1/*infinite*/) throw new ArgumentException("Maximum concurrency level should between 1 and int32.Maxvalue"); _maxConcurrencyLevel = maxConLevel; } [SecurityCritical] protected override void QueueTask(Task task) { if (task == null) throw new ArgumentNullException("When reqeusting to QueueTask, the input task can not be null"); Task.Factory.StartNew(() => { lock (_lockObj) //Locking so that if mutliple threads in threadpool does not incorrectly increment the counter. { //store the current value of the counter (This becomes the unique ID for this scheduler's Task) SchedulerID.Value = _counter; _counter++; } ExecuteTask(task); //Extracted out due to security attribute reason. }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } [SecuritySafeCritical] //This has to be SecuritySafeCritical since its accesses TaskScheduler.TryExecuteTask (which is safecritical) private void ExecuteTask(Task task) { base.TryExecuteTask(task); } [SecurityCritical] protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (taskWasPreviouslyQueued) return false; return TryExecuteTask(task); } //public int SchedulerID //{ // get; // set; //} [SecurityCritical] protected override IEnumerable<Task> GetScheduledTasks() { return null; } private Object _lockObj = new Object(); private int _counter = 1; //This is used ot keep track of how many scheduler tasks were created public ThreadLocal<int> SchedulerID = new ThreadLocal<int>(); //This is the ID of the scheduler. /// <summary>The maximum concurrency level for the scheduler.</summary> private readonly int _maxConcurrencyLevel; public override int MaximumConcurrencyLevel { get { return _maxConcurrencyLevel; } } } public class CESchedulerPairTests { #region Test cases /// <summary> /// Test to ensure that ConcurrentExclusiveSchedulerPair can be created using user defined parameters /// and those parameters are respected when tasks are executed /// </summary> /// <remarks>maxItemsPerTask and which scheduler is used are verified in other testcases</remarks> [Theory] [InlineData("default")] [InlineData("scheduler")] [InlineData("maxconcurrent")] [InlineData("all")] public static void TestCreationOptions(String ctorType) { ConcurrentExclusiveSchedulerPair schedPair = null; //Need to define the default values since these values are passed to the verification methods TaskScheduler scheduler = TaskScheduler.Default; int maxConcurrentLevel = Environment.ProcessorCount; //Based on input args, use one of the ctor overloads switch (ctorType.ToLower()) { case "default": schedPair = new ConcurrentExclusiveSchedulerPair(); break; case "scheduler": schedPair = new ConcurrentExclusiveSchedulerPair(scheduler); break; case "maxconcurrent": maxConcurrentLevel = 2; schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, maxConcurrentLevel); break; case "all": maxConcurrentLevel = Int32.MaxValue; schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, -1/*MaxConcurrentLevel*/, -1/*MaxItemsPerTask*/); //-1 gets converted to Int32.MaxValue break; default: throw new NotImplementedException(String.Format("The option specified {0} to create the ConcurrentExclusiveSchedulerPair is invalid", ctorType)); } //Create the factories that use the exclusive scheduler and the concurrent scheduler. We test to ensure //that the ConcurrentExclusiveSchedulerPair created are valid by scheduling work on them. TaskFactory writers = new TaskFactory(schedPair.ExclusiveScheduler); TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler); List<Task> taskList = new List<Task>(); //Store all tasks created, to enable wait until all of them are finished // Schedule some dummy work that should be run with as much parallelism as possible for (int i = 0; i < 50; i++) { //In the current design, when there are no more tasks to execute, the Task used by concurrentexclusive scheduler dies //by sleeping we simulate some non trival work that takes time and causes the concurrentexclusive scheduler Task //to stay around for addition work. taskList.Add(readers.StartNew(() => { new ManualResetEvent(false).WaitOne(10); })); } // Schedule work where each item must be run when no other items are running for (int i = 0; i < 10; i++) taskList.Add(writers.StartNew(() => { new ManualResetEvent(false).WaitOne(5); })); //Wait on the tasks to finish to ensure that the ConcurrentExclusiveSchedulerPair created can schedule and execute tasks without issues foreach (var item in taskList) { item.Wait(); } //verify that maxconcurrency was respected. if (ctorType == "maxconcurrent") { Assert.Equal(maxConcurrentLevel, schedPair.ConcurrentScheduler.MaximumConcurrencyLevel); } Assert.Equal(1, schedPair.ExclusiveScheduler.MaximumConcurrencyLevel); //verify that the schedulers have not completed Assert.False(schedPair.Completion.IsCompleted, "The schedulers should not have completed as a completion request was not issued."); //complete the scheduler and make sure it shuts down successfully schedPair.Complete(); schedPair.Completion.Wait(); //make sure no additional work may be scheduled foreach (var schedPairScheduler in new TaskScheduler[] { schedPair.ConcurrentScheduler, schedPair.ExclusiveScheduler }) { Exception caughtException = null; try { Task.Factory.StartNew(() => { }, CancellationToken.None, TaskCreationOptions.None, schedPairScheduler); } catch (Exception exc) { caughtException = exc; } Assert.True( caughtException is TaskSchedulerException && caughtException.InnerException is InvalidOperationException, "Queueing after completion should fail"); } } /// <summary> /// Test to verify that only upto maxItemsPerTask are executed by a single ConcurrentExclusiveScheduler Task /// </summary> /// <remarks>In ConcurrentExclusiveSchedulerPair, each tasks scheduled are run under an internal Task. The basic idea for the test /// is that each time ConcurrentExclusiveScheduler is called QueueTasK a counter (which acts as scheduler's Task id) is incremented. /// When a task executes, it observes the parent Task Id and if it matches the one its local cache, it increments its local counter (which tracks /// the items executed by a ConcurrentExclusiveScheduler Task). At any given time the Task's local counter cant exceed maxItemsPerTask</remarks> [Theory] [InlineData(4, 1, true)] [InlineData(1, 4, true)] [InlineData(4, 1, false)] [InlineData(1, 4, false)] public static void TestMaxItemsPerTask(int maxConcurrency, int maxItemsPerTask, bool completeBeforeTaskWait) { //Create a custom TaskScheduler with specified max concurrency (TrackingTaskScheduler is defined in Common\tools\CommonUtils\TPLTestSchedulers.cs) TrackingTaskScheduler scheduler = new TrackingTaskScheduler(maxConcurrency); //We need to use the custom scheduler to achieve the results. As a by-product, we test to ensure custom schedulers are supported ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, maxConcurrency, maxItemsPerTask); TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler); //get reader and writer schedulers TaskFactory writers = new TaskFactory(schedPair.ExclusiveScheduler); //These are threadlocals to ensure that no concurrency side effects occur ThreadLocal<int> itemsExecutedCount = new ThreadLocal<int>(); //Track the items executed by CEScheduler Task ThreadLocal<int> schedulerIDInsideTask = new ThreadLocal<int>(); //Used to store the Scheduler ID observed by a Task Executed by CEScheduler Task //Work done by both reader and writer tasks Action work = () => { //Get the id of the parent Task (which is the task created by the scheduler). Each task run by the scheduler task should //see the same SchedulerID value since they are run on the same thread int id = ((TrackingTaskScheduler)scheduler).SchedulerID.Value; if (id == schedulerIDInsideTask.Value) { //since ids match, this is one more Task being executed by the CEScheduler Task itemsExecutedCount.Value = ++itemsExecutedCount.Value; //This does not need to be thread safe since we are looking to ensure that only n number of tasks were executed and not the order //in which they were executed. Also asserting inside the thread is fine since we just want the test to be marked as failure Assert.True(itemsExecutedCount.Value <= maxItemsPerTask, string.Format("itemsExecutedCount={0} cant be greater than maxValue={1}. Parent TaskID={2}", itemsExecutedCount, maxItemsPerTask, id)); } else { //Since ids dont match, this is the first Task being executed in the CEScheduler Task schedulerIDInsideTask.Value = id; //cache the scheduler ID seen by the thread, so other tasks running in same thread can see this itemsExecutedCount.Value = 1; } //Give enough time for a Task to stay around, so that other tasks will be executed by the same CEScheduler Task //or else the CESchedulerTask will die and each Task might get executed by a different CEScheduler Task. This does not affect the //verifications, but its increases the chance of finding a bug if the maxItemPerTask is not respected new ManualResetEvent(false).WaitOne(20); }; List<Task> taskList = new List<Task>(); int maxConcurrentTasks = maxConcurrency * maxItemsPerTask * 5; int maxExclusiveTasks = maxConcurrency * maxItemsPerTask * 2; // Schedule Tasks in both concurrent and exclusive mode for (int i = 0; i < maxConcurrentTasks; i++) taskList.Add(readers.StartNew(work)); for (int i = 0; i < maxExclusiveTasks; i++) taskList.Add(writers.StartNew(work)); if (completeBeforeTaskWait) { schedPair.Complete(); schedPair.Completion.Wait(); Assert.True(taskList.TrueForAll(t => t.IsCompleted), "All tasks should have completed for scheduler to complete"); } //finally wait for all of the tasks, to ensure they all executed properly Task.WaitAll(taskList.ToArray()); if (!completeBeforeTaskWait) { schedPair.Complete(); schedPair.Completion.Wait(); Assert.True(taskList.TrueForAll(t => t.IsCompleted), "All tasks should have completed for scheduler to complete"); } } /// <summary> /// When user specfices a concurrency level above the level allowed by the task scheduler, the concurrency level should be set /// to the concurrencylevel specified in the taskscheduler. Also tests that the maxConcurrencyLevel specified was respected /// </summary> [Fact] public static void TestLowerConcurrencyLevel() { //a custom scheduler with maxConcurrencyLevel of one int customSchedulerConcurrency = 1; TrackingTaskScheduler scheduler = new TrackingTaskScheduler(customSchedulerConcurrency); // specify a maxConcurrencyLevel > TaskScheduler's maxconcurrencyLevel to ensure the pair takes the min of the two ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, Int32.MaxValue); Assert.Equal(scheduler.MaximumConcurrencyLevel, schedPair.ConcurrentScheduler.MaximumConcurrencyLevel); //Now schedule a reader task that would block and verify that more reader tasks scheduled are not executed //(as long as the first task is blocked) TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler); ManualResetEvent blockReaderTaskEvent = new ManualResetEvent(false); ManualResetEvent blockMainThreadEvent = new ManualResetEvent(false); //Add a reader tasks that would block readers.StartNew(() => { blockMainThreadEvent.Set(); blockReaderTaskEvent.WaitOne(); }); blockMainThreadEvent.WaitOne(); // wait for the blockedTask to start execution //Now add more reader tasks int maxConcurrentTasks = Environment.ProcessorCount; List<Task> taskList = new List<Task>(); for (int i = 0; i < maxConcurrentTasks; i++) taskList.Add(readers.StartNew(() => { })); //schedule some dummy reader tasks foreach (Task task in taskList) { bool wasTaskStarted = (task.Status != TaskStatus.Running) && (task.Status != TaskStatus.RanToCompletion); Assert.True(wasTaskStarted, string.Format("Additional reader tasks should not start when scheduler concurrency is {0} and a reader task is blocked", customSchedulerConcurrency)); } //finally unblock the blocjedTask and wait for all of the tasks, to ensure they all executed properly blockReaderTaskEvent.Set(); Task.WaitAll(taskList.ToArray()); } [Theory] [InlineData(true)] [InlineData(false)] public static void TestConcurrentBlockage(bool useReader) { ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair(); TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler); TaskFactory writers = new TaskFactory(schedPair.ExclusiveScheduler); ManualResetEvent blockExclusiveTaskEvent = new ManualResetEvent(false); ManualResetEvent blockMainThreadEvent = new ManualResetEvent(false); ManualResetEvent blockMre = new ManualResetEvent(false); //Schedule a concurrent task and ensure that it is executed, just for fun Task<bool> conTask = readers.StartNew<bool>(() => { new ManualResetEvent(false).WaitOne(10); ; return true; }); conTask.Wait(); Assert.True(conTask.Result, "The concurrenttask when executed successfully should have returned true"); //Now scehdule a exclusive task that is blocked(thereby preventing other concurrent tasks to finish) Task<bool> exclusiveTask = writers.StartNew<bool>(() => { blockMainThreadEvent.Set(); blockExclusiveTaskEvent.WaitOne(); return true; }); //With exclusive task in execution mode, schedule a number of concurrent tasks and ensure they are not executed blockMainThreadEvent.WaitOne(); List<Task> taskList = new List<Task>(); for (int i = 0; i < 20; i++) taskList.Add(readers.StartNew<bool>(() => { blockMre.WaitOne(10); return true; })); foreach (Task task in taskList) { bool wasTaskStarted = (task.Status != TaskStatus.Running) && (task.Status != TaskStatus.RanToCompletion); Assert.True(wasTaskStarted, "Concurrent tasks should not be executed when a exclusive task is getting executed"); } blockExclusiveTaskEvent.Set(); Task.WaitAll(taskList.ToArray()); } [Theory] [MemberData("ApiType")] public static void TestIntegration(String apiType, bool useReader) { Debug.WriteLine(string.Format(" Running apiType:{0} useReader:{1}", apiType, useReader)); int taskCount = Environment.ProcessorCount; //To get varying number of tasks as a function of cores ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair(); CountdownEvent cde = new CountdownEvent(taskCount); //Used to track how many tasks were executed Action work = () => { cde.Signal(); }; //Work done by all APIs //Choose the right scheduler to use based on input parameter TaskScheduler scheduler = useReader ? schedPair.ConcurrentScheduler : schedPair.ExclusiveScheduler; SelectAPI2Target(apiType, taskCount, scheduler, work); cde.Wait(); //This will cause the test to block (and timeout) until all tasks are finished } /// <summary> /// Test to ensure that invalid parameters result in exceptions /// </summary> [Fact] public static void TestInvalidParameters() { Assert.Throws<ArgumentNullException>(() => new ConcurrentExclusiveSchedulerPair(null)); //TargetScheduler is null Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, 0)); //maxConcurrencyLevel is invalid Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, -2)); //maxConcurrencyLevel is invalid Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, -1, 0)); //maxItemsPerTask is invalid Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, -1, -2)); //maxItemsPerTask is invalid } /// <summary> /// Test to ensure completion task works successfully /// </summary> [Fact] public static void TestCompletionTask() { // Completion tasks is valid after initialization { var cesp = new ConcurrentExclusiveSchedulerPair(); Assert.True(cesp.Completion != null, "CompletionTask should never be null (after initialization)"); Assert.True(!cesp.Completion.IsCompleted, "CompletionTask should not have completed"); } // Completion task is valid after complete is called { var cesp = new ConcurrentExclusiveSchedulerPair(); cesp.Complete(); Assert.True(cesp.Completion != null, "CompletionTask should never be null (after complete)"); cesp.Completion.Wait(); } // Complete method may be called multiple times, and CompletionTask still completes { var cesp = new ConcurrentExclusiveSchedulerPair(); for (int i = 0; i < 20; i++) cesp.Complete(); // ensure multiple calls to Complete succeed Assert.True(cesp.Completion != null, "CompletionTask should never be null (after multiple completes)"); cesp.Completion.Wait(); } // Can create a bunch of schedulers, do work on them all, complete them all, and they all complete { var cesps = new ConcurrentExclusiveSchedulerPair[100]; for (int i = 0; i < cesps.Length; i++) { cesps[i] = new ConcurrentExclusiveSchedulerPair(); } for (int i = 0; i < cesps.Length; i++) { Action work = () => new ManualResetEvent(false).WaitOne(2); ; Task.Factory.StartNew(work, CancellationToken.None, TaskCreationOptions.None, cesps[i].ConcurrentScheduler); Task.Factory.StartNew(work, CancellationToken.None, TaskCreationOptions.None, cesps[i].ExclusiveScheduler); } for (int i = 0; i < cesps.Length; i++) { cesps[i].Complete(); cesps[i].Completion.Wait(); } } // Validate that CESP does not implement IDisposable Assert.Equal(null, new ConcurrentExclusiveSchedulerPair() as IDisposable); } /// <summary> /// Ensure that CESPs can be layered on other CESPs. /// </summary [Fact] public static void TestSchedulerNesting() { // Create a hierarchical set of scheduler pairs var cespParent = new ConcurrentExclusiveSchedulerPair(); var cespChild1 = new ConcurrentExclusiveSchedulerPair(cespParent.ConcurrentScheduler); var cespChild1Child1 = new ConcurrentExclusiveSchedulerPair(cespChild1.ConcurrentScheduler); var cespChild1Child2 = new ConcurrentExclusiveSchedulerPair(cespChild1.ExclusiveScheduler); var cespChild2 = new ConcurrentExclusiveSchedulerPair(cespParent.ExclusiveScheduler); var cespChild2Child1 = new ConcurrentExclusiveSchedulerPair(cespChild2.ConcurrentScheduler); var cespChild2Child2 = new ConcurrentExclusiveSchedulerPair(cespChild2.ExclusiveScheduler); // these are ordered such that we will complete the child schedulers before we complete their parents. That way // we don't complete a parent that's still in use. var cesps = new[] { cespChild1Child1, cespChild1Child2, cespChild1, cespChild2Child1, cespChild2Child2, cespChild2, cespParent, }; // Get the schedulers from all of the pairs List<TaskScheduler> schedulers = new List<TaskScheduler>(); foreach (var s in cesps) { schedulers.Add(s.ConcurrentScheduler); schedulers.Add(s.ExclusiveScheduler); } // Keep track of all created tasks var tasks = new List<Task>(); // Queue lots of work to each scheduler foreach (var scheduler in schedulers) { // Create a function that schedules and inlines recursively queued tasks Action<int> recursiveWork = null; recursiveWork = depth => { if (depth > 0) { Action work = () => { new ManualResetEvent(false).WaitOne(1); recursiveWork(depth - 1); }; TaskFactory factory = new TaskFactory(scheduler); Debug.WriteLine(string.Format("Start tasks in scheduler {0}", scheduler.Id)); Task t1 = factory.StartNew(work); Task t2 = factory.StartNew(work); Task t3 = factory.StartNew(work); Task.WaitAll(t1, t2, t3); } }; for (int i = 0; i < 2; i++) { tasks.Add(Task.Factory.StartNew(() => recursiveWork(2), CancellationToken.None, TaskCreationOptions.None, scheduler)); } } // Wait for all tasks to complete, then complete the schedulers Task.WaitAll(tasks.ToArray()); foreach (var cesp in cesps) { cesp.Complete(); cesp.Completion.Wait(); } } /// <summary> /// Ensure that continuations and parent/children which hop between concurrent and exclusive work correctly. /// EH /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public static void TestConcurrentExclusiveChain(bool syncContinuations) { var scheduler = new TrackingTaskScheduler(Environment.ProcessorCount); var cesp = new ConcurrentExclusiveSchedulerPair(scheduler); // continuations { var starter = new Task(() => { }); var t = starter; for (int i = 0; i < 10; i++) { t = t.ContinueWith(delegate { }, CancellationToken.None, syncContinuations ? TaskContinuationOptions.ExecuteSynchronously : TaskContinuationOptions.None, cesp.ConcurrentScheduler); t = t.ContinueWith(delegate { }, CancellationToken.None, syncContinuations ? TaskContinuationOptions.ExecuteSynchronously : TaskContinuationOptions.None, cesp.ExclusiveScheduler); } starter.Start(cesp.ExclusiveScheduler); t.Wait(); } // parent/child { var errorString = "hello faulty world"; var root = Task.Factory.StartNew(() => { Task.Factory.StartNew(() => { Task.Factory.StartNew(() => { Task.Factory.StartNew(() => { Task.Factory.StartNew(() => { Task.Factory.StartNew(() => { Task.Factory.StartNew(() => { throw new InvalidOperationException(errorString); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler).Wait(); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ConcurrentScheduler); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ConcurrentScheduler); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler); }, CancellationToken.None, TaskCreationOptions.None, cesp.ConcurrentScheduler); ((IAsyncResult)root).AsyncWaitHandle.WaitOne(); Assert.True(root.IsFaulted, "Root should have been faulted by child's error"); var ae = root.Exception.Flatten(); Assert.True(ae.InnerException is InvalidOperationException && ae.InnerException.Message == errorString, "Child's exception should have propagated to the root."); } } #endregion #region Helper Methods public static void SelectAPI2Target(string apiType, int taskCount, TaskScheduler scheduler, Action work) { switch (apiType) { case "StartNew": for (int i = 0; i < taskCount; i++) new TaskFactory(scheduler).StartNew(() => { work(); }); break; case "Start": for (int i = 0; i < taskCount; i++) new Task(() => { work(); }).Start(scheduler); break; case "ContinueWith": for (int i = 0; i < taskCount; i++) { new TaskFactory().StartNew(() => { }).ContinueWith((t) => { work(); }, scheduler); } break; case "FromAsync": for (int i = 0; i < taskCount; i++) { new TaskFactory(scheduler).FromAsync(Task.Factory.StartNew(() => { }), (iar) => { work(); }); } break; case "ContinueWhenAll": for (int i = 0; i < taskCount; i++) { new TaskFactory(scheduler).ContinueWhenAll(new Task[] { Task.Factory.StartNew(() => { }) }, (t) => { work(); }); } break; case "ContinueWhenAny": for (int i = 0; i < taskCount; i++) { new TaskFactory(scheduler).ContinueWhenAny(new Task[] { Task.Factory.StartNew(() => { }) }, (t) => { work(); }); } break; default: throw new ArgumentOutOfRangeException(String.Format("Api name specified {0} is invalid or is of incorrect case", apiType)); } } /// <summary> /// Used to provide parameters for the TestIntegration test /// </summary> public static IEnumerable<object[]> ApiType { get { List<Object[]> values = new List<object[]>(); foreach (String apiType in new String[] { "StartNew", "Start", "ContinueWith", /* FromAsync: Not supported in .NET Native */ "ContinueWhenAll", "ContinueWhenAny" }) { foreach (bool useReader in new bool[] { true, false }) { values.Add(new Object[] { apiType, useReader }); } } return values; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using GraphQL.Language.AST; using GraphQL.SystemTextJson; using GraphQL.Types; using Shouldly; using Xunit; namespace GraphQL.Tests.Types { // these tests relate to the code in custom-scalars.md public class Vector3ScalarTests : QueryTestBase<Vector3ScalarTests.Vector3ScalarSchema> { [Fact] public void test_parseliteral_string() { AssertQuerySuccess(@"{ input(arg: ""1,2,3"") }", @"{ ""input"": ""=1=2=3="" }"); } [Fact] public void test_parseliteral_structured() { AssertQuerySuccess(@"{ input(arg: {x:1,y:2,z:3}) }", @"{ ""input"": ""=1=2=3="" }"); } [Fact] public void test_parsevalue_string() { AssertQuerySuccess(@"query($arg: Vector3) { input(arg: $arg) }", @"{ ""input"": ""=1=2=3="" }", @"{ ""arg"": ""1,2,3"" }".ToInputs()); } [Fact] public void test_parsevalue_structured() { AssertQuerySuccess(@"query($arg: Vector3) { input(arg: $arg) }", @"{ ""input"": ""=1=2=3="" }", @"{ ""arg"": { ""x"": 1, ""y"": 2, ""z"": 3 } }".ToInputs()); } [Fact] public void test_default() { AssertQuerySuccess(@"{ input }", @"{ ""input"": ""=7=8=9="" }"); } [Fact] public void test_output() { AssertQuerySuccess(@"{ output }", @"{ ""output"": { ""x"": 4, ""y"": 5, ""z"": 6 } }"); } [Fact] public void test_loopback_with_value() { AssertQuerySuccess(@"{ loopback(arg: ""11,12,13"") }", @"{ ""loopback"": { ""x"": 11, ""y"": 12, ""z"": 13 } }"); } [Fact] public void test_loopback_with_null() { AssertQuerySuccess(@"{ loopback }", @"{ ""loopback"": null }"); } [Fact] public void test_parseLiteral_toAst() { var scalar = new Vector3Type(); var input = new Vector3(1, 2, 3); var ast = scalar.ToAST(input); var value = scalar.ParseLiteral(ast); var output = value.ShouldBeOfType<Vector3>(); output.X.ShouldBe(input.X); output.Y.ShouldBe(input.Y); output.Z.ShouldBe(input.Z); } public struct Vector3 { public Vector3(float x, float y, float z) { X = x; Y = y; Z = z; } public float X { get; set; } public float Y { get; set; } public float Z { get; set; } public override string ToString() { return $"={X}={Y}={Z}="; } } public class Vector3ScalarSchema : Schema { public Vector3ScalarSchema() { Query = new Vector3ScalarQuery(); } } public class Vector3ScalarQuery : ObjectGraphType { public Vector3ScalarQuery() { Field(typeof(StringGraphType), "input", arguments: new QueryArguments { new QueryArgument<Vector3Type> { Name = "arg", DefaultValue = new Vector3(7, 8, 9) } }, resolve: context => context.GetArgument<Vector3?>("arg")?.ToString()); Field(typeof(Vector3Type), "output", resolve: context => new Vector3(4, 5, 6)); Field(typeof(Vector3Type), "loopback", arguments: new QueryArguments { new QueryArgument<Vector3Type> { Name = "arg" } }, resolve: context => context.GetArgument<Vector3?>("arg")); } } public class Vector3Type : ScalarGraphType { private readonly FloatGraphType _floatScalar = new FloatGraphType(); public Vector3Type() { Name = "Vector3"; } public override object ParseValue(object value) { if (value == null) return null; if (value is string vector3InputString) { try { var vector3Parts = vector3InputString.Split(','); var x = float.Parse(vector3Parts[0]); var y = float.Parse(vector3Parts[1]); var z = float.Parse(vector3Parts[2]); return new Vector3(x, y, z); } catch { throw new FormatException($"Failed to parse {nameof(Vector3)} from input '{vector3InputString}'. Input should be a string of three comma-separated floats in X Y Z order, ex. 1.0,2.0,3.0"); } } if (value is IDictionary<string, object> dictionary) { try { var x = Convert.ToSingle(dictionary["x"]); var y = Convert.ToSingle(dictionary["y"]); var z = Convert.ToSingle(dictionary["z"]); if (dictionary.Count > 3) return ThrowValueConversionError(value); return new Vector3(x, y, z); } catch { throw new FormatException($"Failed to parse {nameof(Vector3)} from object. Input should be an object of three floats named X Y and Z"); } } return ThrowValueConversionError(value); } public override object ParseLiteral(IValue value) { if (value is NullValue) return null; if (value is StringValue stringValue) return ParseValue(stringValue.Value); if (value is ObjectValue objectValue) { var entries = objectValue.ObjectFields.ToDictionary(x => x.Name, x => _floatScalar.ParseLiteral(x.Value)); if (entries.Count != 3) return ThrowLiteralConversionError(value); var x = (double)entries["x"]; var y = (double)entries["y"]; var z = (double)entries["z"]; return new Vector3((float)x, (float)y, (float)z); } return ThrowLiteralConversionError(value); } public override object Serialize(object value) { if (value == null) return null; if (value is Vector3 vector3) { return new { x = vector3.X, y = vector3.Y, z = vector3.Z }; } return ThrowSerializationError(value); } public override IValue ToAST(object value) { if (value == null) return new NullValue(); if (value is Vector3 vector3) { return new ObjectValue(new[] { new ObjectField("x", new FloatValue(vector3.X)), new ObjectField("y", new FloatValue(vector3.Y)), new ObjectField("z", new FloatValue(vector3.Z)), }); } return ThrowASTConversionError(value); } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; #if HAVE_INOTIFY_COLLECTION_CHANGED using System.Collections.ObjectModel; using System.Collections.Specialized; #endif using System.ComponentModel; #if HAVE_DYNAMIC using System.Dynamic; using System.Linq.Expressions; #endif using System.IO; using Newtonsoft.Json.Utilities; using System.Globalization; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a JSON object. /// </summary> /// <example> /// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParse" title="Parsing a JSON Object from Text" /> /// </example> public partial class JObject : JContainer, IDictionary<string, JToken>, INotifyPropertyChanged #if HAVE_COMPONENT_MODEL , ICustomTypeDescriptor #endif #if HAVE_INOTIFY_PROPERTY_CHANGING , INotifyPropertyChanging #endif { private readonly JPropertyKeyedCollection _properties = new JPropertyKeyedCollection(); /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected override IList<JToken> ChildrenTokens { get { return _properties; } } /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #if HAVE_INOTIFY_PROPERTY_CHANGING /// <summary> /// Occurs when a property value is changing. /// </summary> public event PropertyChangingEventHandler PropertyChanging; #endif /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class. /// </summary> public JObject() { } /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class from another <see cref="JObject"/> object. /// </summary> /// <param name="other">A <see cref="JObject"/> object to copy from.</param> public JObject(JObject other) : base(other) { } /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class with the specified content. /// </summary> /// <param name="content">The contents of the object.</param> public JObject(params object[] content) : this((object)content) { } /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class with the specified content. /// </summary> /// <param name="content">The contents of the object.</param> public JObject(object content) { Add(content); } internal override bool DeepEquals(JToken node) { JObject t = node as JObject; if (t == null) { return false; } return _properties.Compare(t._properties); } internal override int IndexOfItem(JToken item) { return _properties.IndexOfReference(item); } internal override void InsertItem(int index, JToken item, bool skipParentCheck) { // don't add comments to JObject, no name to reference comment by if (item != null && item.Type == JTokenType.Comment) { return; } base.InsertItem(index, item, skipParentCheck); } internal override void ValidateToken(JToken o, JToken existing) { ValidationUtils.ArgumentNotNull(o, nameof(o)); if (o.Type != JTokenType.Property) { throw new ArgumentException("Can not add {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, o.GetType(), GetType())); } JProperty newProperty = (JProperty)o; if (existing != null) { JProperty existingProperty = (JProperty)existing; if (newProperty.Name == existingProperty.Name) { return; } } if (_properties.TryGetValue(newProperty.Name, out existing)) { throw new ArgumentException("Can not add property {0} to {1}. Property with the same name already exists on object.".FormatWith(CultureInfo.InvariantCulture, newProperty.Name, GetType())); } } internal override void MergeItem(object content, JsonMergeSettings settings) { JObject o = content as JObject; if (o == null) { return; } foreach (KeyValuePair<string, JToken> contentItem in o) { JProperty existingProperty = Property(contentItem.Key); if (existingProperty == null) { Add(contentItem.Key, contentItem.Value); } else if (contentItem.Value != null) { JContainer existingContainer = existingProperty.Value as JContainer; if (existingContainer == null || existingContainer.Type != contentItem.Value.Type) { if (contentItem.Value.Type != JTokenType.Null || settings?.MergeNullValueHandling == MergeNullValueHandling.Merge) { existingProperty.Value = contentItem.Value; } } else { existingContainer.Merge(contentItem.Value, settings); } } } } internal void InternalPropertyChanged(JProperty childProperty) { OnPropertyChanged(childProperty.Name); #if HAVE_COMPONENT_MODEL if (_listChanged != null) { OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, IndexOfItem(childProperty))); } #endif #if HAVE_INOTIFY_COLLECTION_CHANGED if (_collectionChanged != null) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, childProperty, childProperty, IndexOfItem(childProperty))); } #endif } internal void InternalPropertyChanging(JProperty childProperty) { #if HAVE_INOTIFY_PROPERTY_CHANGING OnPropertyChanging(childProperty.Name); #endif } internal override JToken CloneToken() { return new JObject(this); } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type { get { return JTokenType.Object; } } /// <summary> /// Gets an <see cref="IEnumerable{T}"/> of <see cref="JProperty"/> of this object's properties. /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JProperty"/> of this object's properties.</returns> public IEnumerable<JProperty> Properties() { return _properties.Cast<JProperty>(); } /// <summary> /// Gets a <see cref="JProperty"/> the specified name. /// </summary> /// <param name="name">The property name.</param> /// <returns>A <see cref="JProperty"/> with the specified name or <c>null</c>.</returns> public JProperty Property(string name) { if (name == null) { return null; } JToken property; _properties.TryGetValue(name, out property); return (JProperty)property; } /// <summary> /// Gets a <see cref="JEnumerable{T}"/> of <see cref="JToken"/> of this object's property values. /// </summary> /// <returns>A <see cref="JEnumerable{T}"/> of <see cref="JToken"/> of this object's property values.</returns> public JEnumerable<JToken> PropertyValues() { return new JEnumerable<JToken>(Properties().Select(p => p.Value)); } /// <summary> /// Gets the <see cref="JToken"/> with the specified key. /// </summary> /// <value>The <see cref="JToken"/> with the specified key.</value> public override JToken this[object key] { get { ValidationUtils.ArgumentNotNull(key, nameof(key)); string propertyName = key as string; if (propertyName == null) { throw new ArgumentException("Accessed JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); } return this[propertyName]; } set { ValidationUtils.ArgumentNotNull(key, nameof(key)); string propertyName = key as string; if (propertyName == null) { throw new ArgumentException("Set JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); } this[propertyName] = value; } } /// <summary> /// Gets or sets the <see cref="JToken"/> with the specified property name. /// </summary> /// <value></value> public JToken this[string propertyName] { get { ValidationUtils.ArgumentNotNull(propertyName, nameof(propertyName)); JProperty property = Property(propertyName); return property?.Value; } set { JProperty property = Property(propertyName); if (property != null) { property.Value = value; } else { #if HAVE_INOTIFY_PROPERTY_CHANGING OnPropertyChanging(propertyName); #endif Add(new JProperty(propertyName, value)); OnPropertyChanged(propertyName); } } } /// <summary> /// Loads a <see cref="JObject"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JObject"/>.</param> /// <returns>A <see cref="JObject"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> /// <exception cref="JsonReaderException"> /// <paramref name="reader"/> is not valid JSON. /// </exception> public new static JObject Load(JsonReader reader) { return Load(reader, null); } /// <summary> /// Loads a <see cref="JObject"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JObject"/>.</param> /// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the JSON. /// If this is <c>null</c>, default load settings will be used.</param> /// <returns>A <see cref="JObject"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> /// <exception cref="JsonReaderException"> /// <paramref name="reader"/> is not valid JSON. /// </exception> public new static JObject Load(JsonReader reader, JsonLoadSettings settings) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); if (reader.TokenType == JsonToken.None) { if (!reader.Read()) { throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader."); } } reader.MoveToContent(); if (reader.TokenType != JsonToken.StartObject) { throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } JObject o = new JObject(); o.SetLineInfo(reader as IJsonLineInfo, settings); o.ReadTokenFrom(reader, settings); return o; } /// <summary> /// Load a <see cref="JObject"/> from a string that contains JSON. /// </summary> /// <param name="json">A <see cref="String"/> that contains JSON.</param> /// <returns>A <see cref="JObject"/> populated from the string that contains JSON.</returns> /// <exception cref="JsonReaderException"> /// <paramref name="json"/> is not valid JSON. /// </exception> /// <example> /// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParse" title="Parsing a JSON Object from Text" /> /// </example> public new static JObject Parse(string json) { return Parse(json, null); } /// <summary> /// Load a <see cref="JObject"/> from a string that contains JSON. /// </summary> /// <param name="json">A <see cref="String"/> that contains JSON.</param> /// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the JSON. /// If this is <c>null</c>, default load settings will be used.</param> /// <returns>A <see cref="JObject"/> populated from the string that contains JSON.</returns> /// <exception cref="JsonReaderException"> /// <paramref name="json"/> is not valid JSON. /// </exception> /// <example> /// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParse" title="Parsing a JSON Object from Text" /> /// </example> public new static JObject Parse(string json, JsonLoadSettings settings) { using (JsonReader reader = new JsonTextReader(new StringReader(json))) { JObject o = Load(reader, settings); if (reader.Read() && reader.TokenType != JsonToken.Comment) { throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content."); } return o; } } /// <summary> /// Creates a <see cref="JObject"/> from an object. /// </summary> /// <param name="o">The object that will be used to create <see cref="JObject"/>.</param> /// <returns>A <see cref="JObject"/> with the values of the specified object.</returns> public new static JObject FromObject(object o) { return FromObject(o, JsonSerializer.CreateDefault()); } /// <summary> /// Creates a <see cref="JObject"/> from an object. /// </summary> /// <param name="o">The object that will be used to create <see cref="JObject"/>.</param> /// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used to read the object.</param> /// <returns>A <see cref="JObject"/> with the values of the specified object.</returns> public new static JObject FromObject(object o, JsonSerializer jsonSerializer) { JToken token = FromObjectInternal(o, jsonSerializer); if (token != null && token.Type != JTokenType.Object) { throw new ArgumentException("Object serialized to {0}. JObject instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type)); } return (JObject)token; } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WriteStartObject(); for (int i = 0; i < _properties.Count; i++) { _properties[i].WriteTo(writer, converters); } writer.WriteEndObject(); } /// <summary> /// Gets the <see cref="Newtonsoft.Json.Linq.JToken"/> with the specified property name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns>The <see cref="Newtonsoft.Json.Linq.JToken"/> with the specified property name.</returns> public JToken GetValue(string propertyName) { return GetValue(propertyName, StringComparison.Ordinal); } /// <summary> /// Gets the <see cref="Newtonsoft.Json.Linq.JToken"/> with the specified property name. /// The exact property name will be searched for first and if no matching property is found then /// the <see cref="StringComparison"/> will be used to match a property. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="comparison">One of the enumeration values that specifies how the strings will be compared.</param> /// <returns>The <see cref="Newtonsoft.Json.Linq.JToken"/> with the specified property name.</returns> public JToken GetValue(string propertyName, StringComparison comparison) { if (propertyName == null) { return null; } // attempt to get value via dictionary first for performance JProperty property = Property(propertyName); if (property != null) { return property.Value; } // test above already uses this comparison so no need to repeat if (comparison != StringComparison.Ordinal) { foreach (JProperty p in _properties) { if (string.Equals(p.Name, propertyName, comparison)) { return p.Value; } } } return null; } /// <summary> /// Tries to get the <see cref="Newtonsoft.Json.Linq.JToken"/> with the specified property name. /// The exact property name will be searched for first and if no matching property is found then /// the <see cref="StringComparison"/> will be used to match a property. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> /// <param name="comparison">One of the enumeration values that specifies how the strings will be compared.</param> /// <returns><c>true</c> if a value was successfully retrieved; otherwise, <c>false</c>.</returns> public bool TryGetValue(string propertyName, StringComparison comparison, out JToken value) { value = GetValue(propertyName, comparison); return (value != null); } #region IDictionary<string,JToken> Members /// <summary> /// Adds the specified property name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> public void Add(string propertyName, JToken value) { Add(new JProperty(propertyName, value)); } bool IDictionary<string, JToken>.ContainsKey(string key) { return _properties.Contains(key); } ICollection<string> IDictionary<string, JToken>.Keys { // todo: make order of the collection returned match JObject order get { return _properties.Keys; } } /// <summary> /// Removes the property with the specified name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns><c>true</c> if item was successfully removed; otherwise, <c>false</c>.</returns> public bool Remove(string propertyName) { JProperty property = Property(propertyName); if (property == null) { return false; } property.Remove(); return true; } /// <summary> /// Tries to get the <see cref="Newtonsoft.Json.Linq.JToken"/> with the specified property name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> /// <returns><c>true</c> if a value was successfully retrieved; otherwise, <c>false</c>.</returns> public bool TryGetValue(string propertyName, out JToken value) { JProperty property = Property(propertyName); if (property == null) { value = null; return false; } value = property.Value; return true; } ICollection<JToken> IDictionary<string, JToken>.Values { get { // todo: need to wrap _properties.Values with a collection to get the JProperty value throw new NotImplementedException(); } } #endregion #region ICollection<KeyValuePair<string,JToken>> Members void ICollection<KeyValuePair<string, JToken>>.Add(KeyValuePair<string, JToken> item) { Add(new JProperty(item.Key, item.Value)); } void ICollection<KeyValuePair<string, JToken>>.Clear() { RemoveAll(); } bool ICollection<KeyValuePair<string, JToken>>.Contains(KeyValuePair<string, JToken> item) { JProperty property = Property(item.Key); if (property == null) { return false; } return (property.Value == item.Value); } void ICollection<KeyValuePair<string, JToken>>.CopyTo(KeyValuePair<string, JToken>[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (arrayIndex < 0) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), "arrayIndex is less than 0."); } if (arrayIndex >= array.Length && arrayIndex != 0) { throw new ArgumentException("arrayIndex is equal to or greater than the length of array."); } if (Count > array.Length - arrayIndex) { throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); } int index = 0; foreach (JProperty property in _properties) { array[arrayIndex + index] = new KeyValuePair<string, JToken>(property.Name, property.Value); index++; } } bool ICollection<KeyValuePair<string, JToken>>.IsReadOnly { get { return false; } } bool ICollection<KeyValuePair<string, JToken>>.Remove(KeyValuePair<string, JToken> item) { if (!((ICollection<KeyValuePair<string, JToken>>)this).Contains(item)) { return false; } ((IDictionary<string, JToken>)this).Remove(item.Key); return true; } #endregion internal override int GetDeepHashCode() { return ContentsHashCode(); } /// <summary> /// Returns an enumerator that can be used to iterate through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<KeyValuePair<string, JToken>> GetEnumerator() { foreach (JProperty property in _properties) { yield return new KeyValuePair<string, JToken>(property.Name, property.Value); } } /// <summary> /// Raises the <see cref="PropertyChanged"/> event with the provided arguments. /// </summary> /// <param name="propertyName">Name of the property.</param> protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #if HAVE_INOTIFY_PROPERTY_CHANGING /// <summary> /// Raises the <see cref="PropertyChanging"/> event with the provided arguments. /// </summary> /// <param name="propertyName">Name of the property.</param> protected virtual void OnPropertyChanging(string propertyName) { PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(propertyName)); } #endif #if HAVE_COMPONENT_MODEL // include custom type descriptor on JObject rather than use a provider because the properties are specific to a type #region ICustomTypeDescriptor PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor)this).GetProperties(null); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { PropertyDescriptorCollection descriptors = new PropertyDescriptorCollection(null); foreach (KeyValuePair<string, JToken> propertyValue in this) { descriptors.Add(new JPropertyDescriptor(propertyValue.Key)); } return descriptors; } AttributeCollection ICustomTypeDescriptor.GetAttributes() { return AttributeCollection.Empty; } string ICustomTypeDescriptor.GetClassName() { return null; } string ICustomTypeDescriptor.GetComponentName() { return null; } TypeConverter ICustomTypeDescriptor.GetConverter() { return new TypeConverter(); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return null; } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return null; } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return null; } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return EventDescriptorCollection.Empty; } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return EventDescriptorCollection.Empty; } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return null; } #endregion #endif #if HAVE_DYNAMIC /// <summary> /// Returns the <see cref="DynamicMetaObject"/> responsible for binding operations performed on this object. /// </summary> /// <param name="parameter">The expression tree representation of the runtime value.</param> /// <returns> /// The <see cref="DynamicMetaObject"/> to bind this object. /// </returns> protected override DynamicMetaObject GetMetaObject(Expression parameter) { return new DynamicProxyMetaObject<JObject>(parameter, this, new JObjectDynamicProxy()); } private class JObjectDynamicProxy : DynamicProxy<JObject> { public override bool TryGetMember(JObject instance, GetMemberBinder binder, out object result) { // result can be null result = instance[binder.Name]; return true; } public override bool TrySetMember(JObject instance, SetMemberBinder binder, object value) { JToken v = value as JToken; // this can throw an error if value isn't a valid for a JValue if (v == null) { v = new JValue(value); } instance[binder.Name] = v; return true; } public override IEnumerable<string> GetDynamicMemberNames(JObject instance) { return instance.Properties().Select(p => p.Name); } } #endif } }
//! \file ArcLPK.cs //! \date Mon Feb 16 17:21:47 2015 //! \brief Lucifen Easy Game System archive implementation. // // Copyright (C) 2015-2016 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Text; using GameRes.Compression; using GameRes.Formats.Properties; using GameRes.Formats.Strings; using GameRes.Utility; namespace GameRes.Formats.Lucifen { internal class LuciEntry : PackedEntry { public byte Flag; } internal class LuciArchive : ArcFile { public LpkInfo Info; public EncryptionScheme Scheme; public LuciArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, EncryptionScheme scheme, LpkInfo info) : base (arc, impl, dir) { Info = info; Scheme = scheme; } } [Serializable] public class EncryptionScheme { public LpkOpener.Key BaseKey; public byte ContentXor; public uint RotatePattern; public bool ImportGameInit; } [Serializable] public class LpkScheme : ResourceScheme { public Dictionary<string, EncryptionScheme> KnownSchemes; public Dictionary<string, Dictionary<string, LpkOpener.Key>> KnownKeys; } internal class LuciOptions : ResourceOptions { public string Scheme; public LpkOpener.Key Key; } internal class LpkInfo { public bool AlignedOffset; public bool Flag1; public bool IsEncrypted; public bool PackedEntries; public bool WholeCrypt; public uint Key; public byte[] Prefix; } [Export(typeof(ArchiveFormat))] public class LpkOpener : ArchiveFormat { public override string Tag { get { return "LPK"; } } public override string Description { get { return "Lucifen system resource archive"; } } public override uint Signature { get { return 0x314b504c; } } // 'LPK1' public override bool IsHierarchic { get { return true; } } public override bool CanCreate { get { return false; } } [Serializable] public class Key { public uint Key1, Key2; public Key (uint k1, uint k2) { Key1 = k1; Key2 = k2; } } static readonly EncryptionScheme DefaultScheme = new EncryptionScheme { BaseKey = new Key (0xA5B9AC6B, 0x9A639DE5), ContentXor = 0x5d, RotatePattern = 0x31746285, ImportGameInit = true }; public static Dictionary<string, EncryptionScheme> KnownSchemes = new Dictionary<string, EncryptionScheme> { { "Default", DefaultScheme } }; static Dictionary<string, Dictionary<string, Key>> KnownKeys = new Dictionary<string, Dictionary<string, Key>>(); EncryptionScheme CurrentScheme = DefaultScheme; Dictionary<string, Key> CurrentFileMap = new Dictionary<string, Key>(); public override ArcFile TryOpen (ArcView file) { string name = Path.GetFileName (file.Name).ToUpperInvariant(); if (string.IsNullOrEmpty (name)) return null; Key file_key = null; var basename = Encodings.cp932.GetBytes (Path.GetFileNameWithoutExtension (name)); if (name != "SCRIPT.LPK") CurrentFileMap.TryGetValue (name, out file_key); try { var arc = Open (basename, file, CurrentScheme, file_key); if (null != arc) return arc; } catch { /* unknown encryption, ignore parse errors */ } var new_scheme = QueryEncryptionScheme(); if (new_scheme == CurrentScheme && !CurrentScheme.ImportGameInit) return null; CurrentScheme = new_scheme; if (name != "SCRIPT.LPK" && CurrentScheme.ImportGameInit) { if (0 == CurrentFileMap.Count) ImportKeys (file.Name); } if (CurrentFileMap.Count > 0 && !CurrentFileMap.TryGetValue (name, out file_key)) return null; return Open (basename, file, CurrentScheme, file_key); } public override Stream OpenEntry (ArcFile arc, Entry entry) { if (0 == entry.Size) return Stream.Null; var larc = arc as LuciArchive; var lent = entry as LuciEntry; Stream input = arc.File.CreateStream (entry.Offset, entry.Size); if (null == larc || null == lent) return input; byte[] data; using (input) { if (lent.IsPacked) { using (var reader = new LzssReader (input, (int)lent.Size, (int)lent.UnpackedSize)) { reader.Unpack(); data = reader.Data; } } else { data = new byte[lent.Size]; input.Read (data, 0, data.Length); } } if (larc.Info.WholeCrypt) { DecryptContent (data, larc.Scheme.ContentXor); } if (larc.Info.IsEncrypted) { int count = Math.Min (data.Length, 0x100); if (count != 0) DecryptEntry (data, count, larc.Info.Key, larc.Scheme.RotatePattern); } input = new MemoryStream (data); if (null != larc.Info.Prefix) return new PrefixStream (larc.Info.Prefix, input); else return input; } static void DecryptContent (byte[] data, byte key) { for (int i = 0; i < data.Length; ++i) { int v = data[i] ^ key; data[i] = Binary.RotByteR ((byte)v, 4); } } static unsafe void DecryptEntry (byte[] data, int length, uint key, uint pattern) { fixed (byte* buf_raw = data) { uint* encoded = (uint*)buf_raw; length /= 4; for (int i = 0; i < length; ++i) { encoded[i] ^= key; pattern = Binary.RotR (pattern, 4); key = Binary.RotL (key, (int)pattern); } } } static unsafe void DecryptIndex (byte[] data, int length, uint key, uint pattern) { fixed (byte* buf_raw = data) { uint* encoded = (uint*)buf_raw; length /= 4; for (int i = 0; i < length; ++i) { encoded[i] ^= key; pattern = Binary.RotL (pattern, 4); key = Binary.RotR (key, (int)pattern); } } } ArcFile Open (byte[] basename, ArcView file, EncryptionScheme scheme, Key key) { uint key1 = scheme.BaseKey.Key1; uint key2 = scheme.BaseKey.Key2; for (int b = 0, e = basename.Length-1; e >= 0; ++b, --e) { key1 ^= basename[e]; key2 ^= basename[b]; key1 = Binary.RotR (key1, 7); key2 = Binary.RotL (key2, 7); } if (null != key) { key1 ^= key.Key1; key2 ^= key.Key2; } uint code = file.View.ReadUInt32 (4) ^ key2; int index_size = (int)(code & 0xffffff); byte flags = (byte)(code >> 24); if (0 != (flags & 1)) index_size = (index_size << 11) - 8; if (index_size < 5 || index_size >= file.MaxOffset) return null; var index = new byte[index_size]; if (index_size != file.View.Read (8, index, 0, (uint)index_size)) return null; DecryptIndex (index, index_size, key2, scheme.RotatePattern); var lpk_info = new LpkInfo { AlignedOffset = 0 != (flags & 1), Flag1 = 0 != (flags & 2), IsEncrypted = 0 != (flags & 4), PackedEntries = 0 != (flags & 8), WholeCrypt = 0 != (flags & 0x10), Key = key1 }; var reader = new IndexReader (lpk_info); var dir = reader.Read (index); if (null == dir) return null; // this condition is fishy, probably patch files have additional bitflag set if (lpk_info.WholeCrypt && Binary.AsciiEqual (basename, "PATCH")) lpk_info.WholeCrypt = false; return new LuciArchive (file, this, dir, scheme, reader.Info); } static readonly byte[] ScriptName = Encoding.ASCII.GetBytes ("SCRIPT"); void ImportKeys (string source_name) { var script_lpk = VFS.CombinePath (Path.GetDirectoryName (source_name), "SCRIPT.LPK"); using (var script_file = VFS.OpenView (script_lpk)) using (var script_arc = Open (ScriptName, script_file, CurrentScheme, null)) { if (null == script_arc) throw new UnknownEncryptionScheme(); var entry = script_arc.Dir.FirstOrDefault (e => e.Name.Equals ("gameinit.sob", StringComparison.InvariantCultureIgnoreCase)); if (null == entry) throw new FileNotFoundException ("Missing 'gameinit.sob' entry in SCRIPT.LPK"); using (var gameinit = script_arc.OpenEntry (entry)) { var init_data = new byte[gameinit.Length]; gameinit.Read (init_data, 0, init_data.Length); if (!ParseGameInit (init_data)) throw new UnknownEncryptionScheme(); } } } bool ParseGameInit (byte[] sob) { CurrentFileMap.Clear(); if (!Binary.AsciiEqual (sob, "SOB0")) return false; int offset = LittleEndian.ToInt32 (sob, 4) + 8; if (offset <= 0 || offset >= sob.Length) return false; unsafe { fixed (byte* buf_raw = sob) { uint* p = (uint*)(buf_raw + offset); uint index_len = *p; if (offset+8+(int)index_len >= sob.Length) return false; p += 2; uint* last = p + index_len / 4 - 28; while (p < last) { if (p[0] == 0x28 && p[1] == 0 && p[2] != 0 && p[3] == 8 && p[4] == 1 && p[5] == 8 && p[6] == 1 && p[7] == 8 && p[8] != 0 && p[9] == 8 && p[10] != 0 && p[11] == 5 && p[17] == 0x28 && p[18] == 0 && p[19] != 0 && p[20] == 8 && p[21] != 0 && p[22] == 8 && p[23] == 0xffffffff && p[24] == 8 && p[25] == 1 && p[26] == 8 && p[27] == 1 && p[28] == 5) { byte* lpk = (byte*)p + p[21] - p[2] + 0x34; int name_index = (int)(lpk - buf_raw); if (name_index < 0 || name_index >= sob.Length) { ++p; continue; } string name = Binary.GetCString (sob, name_index, sob.Length-name_index); name = name.ToUpperInvariant(); CurrentFileMap[name] = new Key (p[8], p[10]); p += 0x22; } else ++p; } return true; } } } public override ResourceOptions GetDefaultOptions () { return new LuciOptions { Scheme = Settings.Default.LPKScheme }; } public override object GetAccessWidget () { return new GUI.WidgetLPK(); } EncryptionScheme QueryEncryptionScheme () { CurrentFileMap.Clear(); var options = Query<LuciOptions> (arcStrings.ArcEncryptedNotice); if (null == options) return DefaultScheme; string title = options.Scheme; if (null == options.Key) { Dictionary<string, Key> file_map = null; if (KnownKeys.TryGetValue (title, out file_map)) CurrentFileMap = new Dictionary<string, Key> (file_map); } return KnownSchemes[title]; } public override ResourceScheme Scheme { get { return new LpkScheme { KnownSchemes = KnownSchemes, KnownKeys = KnownKeys }; } set { var scheme = (LpkScheme)value; KnownSchemes = scheme.KnownSchemes; KnownKeys = scheme.KnownKeys; foreach (var key in KnownSchemes.Keys.Where (x => null == KnownSchemes[x]).ToArray()) { KnownSchemes[key] = DefaultScheme; } } } } internal class IndexReader { byte[] m_index; LpkInfo m_info; List<Entry> m_dir; byte[] m_name; int m_index_width; int m_entries_offset; public LpkInfo Info { get { return m_info; } } public int EntrySize { get; private set; } public IndexReader (LpkInfo info) { if (!info.Flag1) throw new NotSupportedException ("Not supported LPK index format"); m_info = info; EntrySize = m_info.PackedEntries ? 13 : 9; } public List<Entry> Read (byte[] index) { m_index = index; int count = LittleEndian.ToInt32 (m_index, 0); if (count <= 0 || count > 0xfffff) return null; int index_offset = 4; int prefix_length = m_index[index_offset++]; if (0 != prefix_length) { m_info.Prefix = new byte[prefix_length]; Buffer.BlockCopy (m_index, index_offset, m_info.Prefix, 0, prefix_length); index_offset += prefix_length; } m_index_width = 0 != m_index[index_offset++] ? 4 : 2; int letter_table_length = LittleEndian.ToInt32 (m_index, index_offset); index_offset += 4; m_entries_offset = index_offset + letter_table_length; if (m_entries_offset >= m_index.Length) return null; if ((m_index.Length - m_entries_offset) / EntrySize < count) EntrySize = (m_index.Length - m_entries_offset) / count; if (EntrySize < 8 || m_info.PackedEntries && EntrySize < 12) return null; m_dir = new List<Entry> (count); m_name = new byte[260]; TraverseIndex (index_offset, 0); return m_dir.Count == count ? m_dir : null; } void TraverseIndex (int index_offset, int name_length) { if (index_offset < 0 || index_offset >= m_index.Length) throw new InvalidFormatException ("Error parsing LPK index"); if (name_length >= m_name.Length) throw new InvalidFormatException ("Entry filename is too long"); int entries = m_index[index_offset++]; for (int i = 0; i < entries; ++i) { byte next_letter = m_index[index_offset++]; int next_offset = 4 == m_index_width ? LittleEndian.ToInt32 (m_index, index_offset) : (int)LittleEndian.ToUInt16 (m_index, index_offset); m_name[name_length] = next_letter; index_offset += m_index_width;; if (0 != next_letter) TraverseIndex (index_offset+next_offset, name_length+1); else AddEntry (name_length, next_offset); } } void AddEntry (int name_length, int entry_num) { if (name_length < 1) throw new InvalidFormatException ("Invalid LPK entry name"); string name = Encodings.cp932.GetString (m_name, 0, name_length); var entry = new LuciEntry { Name = name, Type = FormatCatalog.Instance.GetTypeFromName (name), IsPacked = m_info.PackedEntries, }; int entry_pos = m_entries_offset + EntrySize * entry_num; if (entry_pos+EntrySize > m_index.Length) throw new InvalidFormatException ("Invalid LPK entry index"); if (0 != (EntrySize & 1)) entry.Flag = m_index[entry_pos++]; long offset = LittleEndian.ToUInt32 (m_index, entry_pos); entry.Offset = m_info.AlignedOffset ? offset << 11 : offset; entry.Size = LittleEndian.ToUInt32 (m_index, entry_pos+4); if (entry.IsPacked) entry.UnpackedSize = LittleEndian.ToUInt32 (m_index, entry_pos+8); else entry.UnpackedSize = entry.Size; m_dir.Add (entry); } } }
using System; using System.Collections.Generic; using System.IO; using Fake; using Machine.Specifications; using Microsoft.FSharp.Core; namespace Test.FAKECore { public class when_accessing_internals { It should_have_access_to_FAKE_internals = () => AssemblyInfoFile.getDependencies(new List<AssemblyInfoFile.Attribute>()); } public class when_using_fsharp_task_with_default_config { It should_use_system_namespace_and_emit_a_version_module = () => { string infoFile = Path.GetTempFileName(); var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLib"), AssemblyInfoFile.Attribute.Version("1.0.0.0") }; AssemblyInfoFile.CreateFSharpAssemblyInfo(infoFile, attributes); const string expected = "// Auto-Generated by FAKE; do not edit\r\nnamespace System\r\nopen System.Reflection\r\n\r\n[<assembly: AssemblyProductAttribute(\"TestLib\")>]\r\n[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\ndo ()\r\n\r\nmodule internal AssemblyVersionInformation =\r\n let [<Literal>] AssemblyProduct = \"TestLib\"\r\n let [<Literal>] AssemblyVersion = \"1.0.0.0\"\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It update_attributes_should_update_attributes_in_fs_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".fs"); const string original = "namespace System\r\nopen System.Reflection\r\n\r\n" + "[<assembly: AssemblyProduct(\"TestLib\")>]\r\n" + "[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\n"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLibNew"), AssemblyInfoFile.Attribute.Version("2.0.0.0") }; AssemblyInfoFile.UpdateAttributes(infoFile, attributes); // Assert const string expected = "namespace System\r\nopen System.Reflection\r\n\r\n" + "[<assembly: AssemblyProduct(\"TestLibNew\")>]\r\n" + "[<assembly: AssemblyVersionAttribute(\"2.0.0.0\")>]\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It get_attribute_should_read_attribute_from_fs_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".fs"); const string original = "namespace System\r\nopen System.Reflection\r\n\r\n" + "[<assembly: AssemblyProduct(\"TestLib\")>]\r\n" + "[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\n"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var productAttr = AssemblyInfoFile.GetAttribute("AssemblyProduct", infoFile).Value; var versionAttr = AssemblyInfoFile.GetAttribute("AssemblyVersion", infoFile).Value; // Assert productAttr.Value.ShouldEqual("TestLib"); versionAttr.Value.ShouldEqual("1.0.0.0"); }; } public class when_using_fsharp_task_with_custom_config { It should_use_custom_namespace_and_not_emit_a_version_module = () => { var customConfig = new AssemblyInfoFile.AssemblyInfoFileConfig(false, new FSharpOption<string>("Custom")); string infoFile = Path.GetTempFileName(); var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLib"), AssemblyInfoFile.Attribute.Version("1.0.0.0") }; AssemblyInfoFile.CreateFSharpAssemblyInfoWithConfig(infoFile, attributes, customConfig); const string expected = "// Auto-Generated by FAKE; do not edit\r\nnamespace Custom\r\nopen System.Reflection\r\n\r\n[<assembly: AssemblyProductAttribute(\"TestLib\")>]\r\n[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\ndo ()\r\n\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; } public class when_using_csharp_task_with_default_config { It should_use_system_namespace_and_emit_a_version_module = () => { string infoFile = Path.GetTempFileName(); var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLib"), AssemblyInfoFile.Attribute.Version("1.0.0.0") }; AssemblyInfoFile.CreateCSharpAssemblyInfo(infoFile, attributes); const string expected = "// <auto-generated/>\r\nusing System.Reflection;\r\n\r\n[assembly: AssemblyProductAttribute(\"TestLib\")]\r\n[assembly: AssemblyVersionAttribute(\"1.0.0.0\")]\r\nnamespace System {\r\n internal static class AssemblyVersionInformation {\r\n internal const System.String AssemblyProduct = \"TestLib\";\r\n internal const System.String AssemblyVersion = \"1.0.0.0\";\r\n }\r\n}\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It update_attributes_should_update_attributes_in_cs_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".cs"); const string original = "// <auto-generated/>\r\nusing System.Reflection;\r\n\r\n" + "[assembly: AssemblyProduct(\"TestLib\")]\r\n" + "[assembly: AssemblyVersionAttribute(\"1.0.0.0\")]\r\n"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLibNew"), AssemblyInfoFile.Attribute.Version("2.0.0.0") }; AssemblyInfoFile.UpdateAttributes(infoFile, attributes); // Assert const string expected = "// <auto-generated/>\r\nusing System.Reflection;\r\n\r\n" + "[assembly: AssemblyProduct(\"TestLibNew\")]\r\n" + "[assembly: AssemblyVersionAttribute(\"2.0.0.0\")]\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It get_attribute_should_read_attribute_from_cs_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".cs"); const string original = "// <auto-generated/>\r\nusing System.Reflection;\r\n\r\n" + "[assembly: AssemblyProduct(\"TestLib\")]\r\n" + "[assembly: AssemblyVersionAttribute(\"1.0.0.0\")]\r\n"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var productAttr = AssemblyInfoFile.GetAttribute("AssemblyProduct", infoFile).Value; var versionAttr = AssemblyInfoFile.GetAttribute("AssemblyVersion", infoFile).Value; // Assert productAttr.Value.ShouldEqual("TestLib"); versionAttr.Value.ShouldEqual("1.0.0.0"); }; } public class when_using_cppcli_task_with_default_config { It should_emit_valid_syntax = () => { string infoFile = Path.GetTempFileName(); var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLib"), AssemblyInfoFile.Attribute.Version("1.0.0.0") }; AssemblyInfoFile.CreateCppCliAssemblyInfo(infoFile, attributes); const string expected = "// <auto-generated/>\r\nusing namespace System::Reflection;\r\n\r\n[assembly:AssemblyProductAttribute(\"TestLib\")];\r\n[assembly:AssemblyVersionAttribute(\"1.0.0.0\")];\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It update_attributes_should_update_attributes_in_cpp_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".cpp"); const string original = "// <auto-generated/>\r\nusing namespace System::Reflection;\r\n\r\n" + "[assembly:AssemblyProduct(\"TestLib\")];\r\n" + "[assembly:AssemblyVersionAttribute(\"1.0.0.0\")];\r\n"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLibNew"), AssemblyInfoFile.Attribute.Version("2.0.0.0") }; AssemblyInfoFile.UpdateAttributes(infoFile, attributes); // Assert const string expected = "// <auto-generated/>\r\nusing namespace System::Reflection;\r\n\r\n" + "[assembly:AssemblyProduct(\"TestLibNew\")];\r\n" + "[assembly:AssemblyVersionAttribute(\"2.0.0.0\")];\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It get_attribute_should_read_attribute_from_cpp_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".cpp"); const string original = "// <auto-generated/>\r\nusing namespace System::Reflection;\r\n\r\n" + "[assembly:AssemblyProduct(\"TestLib\")];\r\n" + "[assembly:AssemblyVersionAttribute(\"1.0.0.0\")];\r\n"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var productAttr = AssemblyInfoFile.GetAttribute("AssemblyProduct", infoFile).Value; var versionAttr = AssemblyInfoFile.GetAttribute("AssemblyVersion", infoFile).Value; // Assert productAttr.Value.ShouldEqual("TestLib"); versionAttr.Value.ShouldEqual("1.0.0.0"); }; } public class when_using_vb_task_with_default_config { It should_emit_valid_syntax = () => { string infoFile = Path.GetTempFileName(); var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLib"), AssemblyInfoFile.Attribute.Version("1.0.0.0") }; AssemblyInfoFile.CreateVisualBasicAssemblyInfo(infoFile, attributes); const string expected = "' <auto-generated/>\r\nImports System.Reflection\r\n\r\n<assembly: AssemblyProductAttribute(\"TestLib\")>\r\n<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>\r\nFriend NotInheritable Class AssemblyVersionInformation\r\n Friend Const AssemblyProduct As System.String = \"TestLib\"\r\n Friend Const AssemblyVersion As System.String = \"1.0.0.0\"\r\nEnd Class\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It update_attributes_should_update_attributes_in_vb_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".vb"); const string original = "' <auto-generated/>\r\nImports System.Reflection\r\n\r\n" + "<assembly: AssemblyProduct(\"TestLib\")>\r\n" + "<Assembly: AssemblyCompany(\"TestCompany\")>\r\n" + "<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>\r\n" + "<Assembly: ComVisibleAttribute(false)>"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLibNew"), AssemblyInfoFile.Attribute.Company("TestCompanyNew"), AssemblyInfoFile.Attribute.Version("2.0.0.0") }; AssemblyInfoFile.UpdateAttributes(infoFile, attributes); // Assert const string expected = "' <auto-generated/>\r\nImports System.Reflection\r\n\r\n" + "<assembly: AssemblyProduct(\"TestLibNew\")>\r\n" + "<Assembly: AssemblyCompany(\"TestCompanyNew\")>\r\n" + "<assembly: AssemblyVersionAttribute(\"2.0.0.0\")>\r\n" + "<Assembly: ComVisibleAttribute(false)>"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It get_attribute_should_read_attribute_from_vb_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end, and also // case-insensitive attributes string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".vb"); const string original = "' <auto-generated/>\r\nImports System.Reflection\r\n\r\n" + "<assembly: AssemblyProduct(\"TestLib\")>\r\n" + "<Assembly: AssemblyCompany(\"TestCompany\")>\r\n" + "<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>\r\n" + "<Assembly: ComVisibleAttribute(false)>"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var productAttr = AssemblyInfoFile.GetAttribute("AssemblyProduct", infoFile).Value; var companyAttr = AssemblyInfoFile.GetAttribute("AssemblyCompany", infoFile).Value; var versionAttr = AssemblyInfoFile.GetAttribute("AssemblyVersion", infoFile).Value; var comVisibleAttr = AssemblyInfoFile.GetAttribute("ComVisible", infoFile).Value; // Assert productAttr.Value.ShouldEqual("TestLib"); companyAttr.Value.ShouldEqual("TestCompany"); versionAttr.Value.ShouldEqual("1.0.0.0"); comVisibleAttr.Value.ShouldEqual("false"); }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma warning disable CS0067 // events are declared but not used using System; using System.Reflection; using System.Runtime.ExceptionServices; #if !uapaot using System.Runtime.Loader; #endif using System.IO; using System.Security.Principal; namespace System { public partial class AppDomain : MarshalByRefObject { private static readonly AppDomain s_domain = new AppDomain(); private readonly object _forLock = new object(); private IPrincipal _defaultPrincipal; private AppDomain() { } public static AppDomain CurrentDomain => s_domain; #if !uapaot public string BaseDirectory => AppContext.BaseDirectory; public string RelativeSearchPath => null; public event UnhandledExceptionEventHandler UnhandledException { add { AppContext.UnhandledException += value; } remove { AppContext.UnhandledException -= value; } } #endif public string DynamicDirectory => null; [ObsoleteAttribute("AppDomain.SetDynamicBase has been deprecated. Please investigate the use of AppDomainSetup.DynamicBase instead. http://go.microsoft.com/fwlink/?linkid=14202")] public void SetDynamicBase(string path) { } public string FriendlyName { get { Assembly assembly = Assembly.GetEntryAssembly(); return assembly != null ? assembly.GetName().Name : "DefaultDomain"; } } public int Id => 1; public bool IsFullyTrusted => true; public bool IsHomogenous => true; public event EventHandler DomainUnload; #if !uapaot public event EventHandler<FirstChanceExceptionEventArgs> FirstChanceException { add { AppContext.FirstChanceException += value; } remove { AppContext.FirstChanceException -= value; } } public event EventHandler ProcessExit { add { AppContext.ProcessExit += value; } remove { AppContext.ProcessExit -= value; } } #endif public string ApplyPolicy(string assemblyName) { if (assemblyName == null) { throw new ArgumentNullException(nameof(assemblyName)); } if (assemblyName.Length == 0 || assemblyName[0] == '\0') { throw new ArgumentException(SR.ZeroLengthString); } return assemblyName; } public static AppDomain CreateDomain(string friendlyName) { if (friendlyName == null) throw new ArgumentNullException(nameof(friendlyName)); throw new PlatformNotSupportedException(SR.PlatformNotSupported_AppDomains); } public int ExecuteAssembly(string assemblyFile) => ExecuteAssembly(assemblyFile, null); public int ExecuteAssembly(string assemblyFile, string[] args) { if (assemblyFile == null) { throw new ArgumentNullException(nameof(assemblyFile)); } string fullPath = Path.GetFullPath(assemblyFile); Assembly assembly = Assembly.LoadFile(fullPath); return ExecuteAssembly(assembly, args); } public int ExecuteAssembly(string assemblyFile, string[] args, byte[] hashValue, Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // This api is only meaningful for very specific partial trust/CAS scenarios } private int ExecuteAssembly(Assembly assembly, string[] args) { MethodInfo entry = assembly.EntryPoint; if (entry == null) { throw new MissingMethodException(SR.EntryPointNotFound + assembly.FullName); } object result = null; try { result = entry.GetParameters().Length > 0 ? entry.Invoke(null, new object[] { args }) : entry.Invoke(null, null); } catch (TargetInvocationException targetInvocationException) { if (targetInvocationException.InnerException == null) { throw; } // We are catching the TIE here and throws the inner exception only, // this is needed to have a consistent exception story with desktop clr ExceptionDispatchInfo.Capture(targetInvocationException.InnerException).Throw(); } return result != null ? (int)result : 0; } public int ExecuteAssemblyByName(AssemblyName assemblyName, params string[] args) => ExecuteAssembly(Assembly.Load(assemblyName), args); public int ExecuteAssemblyByName(string assemblyName) => ExecuteAssemblyByName(assemblyName, null); public int ExecuteAssemblyByName(string assemblyName, params string[] args) => ExecuteAssembly(Assembly.Load(assemblyName), args); #if !uapaot public object GetData(string name) => AppContext.GetData(name); public void SetData(string name, object data) => AppContext.SetData(name, data); public bool? IsCompatibilitySwitchSet(string value) { bool result; return AppContext.TryGetSwitch(value, out result) ? result : default(bool?); } #endif public bool IsDefaultAppDomain() => true; public bool IsFinalizingForUnload() => false; public override string ToString() => SR.AppDomain_Name + FriendlyName + Environment.NewLine + SR.AppDomain_NoContextPolicies; public static void Unload(AppDomain domain) { if (domain == null) { throw new ArgumentNullException(nameof(domain)); } throw new CannotUnloadAppDomainException(SR.NotSupported); } public Assembly Load(byte[] rawAssembly) => Assembly.Load(rawAssembly); public Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore) => Assembly.Load(rawAssembly, rawSymbolStore); public Assembly Load(AssemblyName assemblyRef) => Assembly.Load(assemblyRef); public Assembly Load(string assemblyString) => Assembly.Load(assemblyString); public Assembly[] ReflectionOnlyGetAssemblies() => Array.Empty<Assembly>(); public static bool MonitoringIsEnabled { get { return false; } set { if (!value) { throw new ArgumentException(SR.Arg_MustBeTrue); } throw new PlatformNotSupportedException(SR.PlatformNotSupported_AppDomain_ResMon); } } public long MonitoringSurvivedMemorySize { get { throw CreateResMonNotAvailException(); } } public static long MonitoringSurvivedProcessMemorySize { get { throw CreateResMonNotAvailException(); } } public long MonitoringTotalAllocatedMemorySize { get { throw CreateResMonNotAvailException(); } } public TimeSpan MonitoringTotalProcessorTime { get { throw CreateResMonNotAvailException(); } } private static Exception CreateResMonNotAvailException() => new InvalidOperationException(SR.PlatformNotSupported_AppDomain_ResMon); [ObsoleteAttribute("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread. http://go.microsoft.com/fwlink/?linkid=14202", false)] public static int GetCurrentThreadId() => Environment.CurrentManagedThreadId; public bool ShadowCopyFiles => false; [ObsoleteAttribute("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. http://go.microsoft.com/fwlink/?linkid=14202")] public void AppendPrivatePath(string path) { } [ObsoleteAttribute("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. http://go.microsoft.com/fwlink/?linkid=14202")] public void ClearPrivatePath() { } [ObsoleteAttribute("AppDomain.ClearShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. http://go.microsoft.com/fwlink/?linkid=14202")] public void ClearShadowCopyPath() { } [ObsoleteAttribute("AppDomain.SetCachePath has been deprecated. Please investigate the use of AppDomainSetup.CachePath instead. http://go.microsoft.com/fwlink/?linkid=14202")] public void SetCachePath(string path) { } [ObsoleteAttribute("AppDomain.SetShadowCopyFiles has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyFiles instead. http://go.microsoft.com/fwlink/?linkid=14202")] public void SetShadowCopyFiles() { } [ObsoleteAttribute("AppDomain.SetShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. http://go.microsoft.com/fwlink/?linkid=14202")] public void SetShadowCopyPath(string path) { } #if !uapaot public Assembly[] GetAssemblies() => AssemblyLoadContext.GetLoadedAssemblies(); public event AssemblyLoadEventHandler AssemblyLoad { add { AssemblyLoadContext.AssemblyLoad += value; } remove { AssemblyLoadContext.AssemblyLoad -= value; } } public event ResolveEventHandler AssemblyResolve { add { AssemblyLoadContext.AssemblyResolve += value; } remove { AssemblyLoadContext.AssemblyResolve -= value; } } public event ResolveEventHandler ReflectionOnlyAssemblyResolve; public event ResolveEventHandler TypeResolve { add { AssemblyLoadContext.TypeResolve += value; } remove { AssemblyLoadContext.TypeResolve -= value; } } public event ResolveEventHandler ResourceResolve { add { AssemblyLoadContext.ResourceResolve += value; } remove { AssemblyLoadContext.ResourceResolve -= value; } } #endif public void SetPrincipalPolicy(PrincipalPolicy policy) { } public void SetThreadPrincipal(IPrincipal principal) { if (principal == null) { throw new ArgumentNullException(nameof(principal)); } lock (_forLock) { // Check that principal has not been set previously. if (_defaultPrincipal != null) { throw new SystemException(SR.AppDomain_Policy_PrincipalTwice); } _defaultPrincipal = principal; } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// ConferenceResource /// </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; using Twilio.Types; namespace Twilio.Rest.Api.V2010.Account { public class ConferenceResource : Resource { public sealed class StatusEnum : StringEnum { private StatusEnum(string value) : base(value) {} public StatusEnum() {} public static implicit operator StatusEnum(string value) { return new StatusEnum(value); } public static readonly StatusEnum Init = new StatusEnum("init"); public static readonly StatusEnum InProgress = new StatusEnum("in-progress"); public static readonly StatusEnum Completed = new StatusEnum("completed"); } public sealed class UpdateStatusEnum : StringEnum { private UpdateStatusEnum(string value) : base(value) {} public UpdateStatusEnum() {} public static implicit operator UpdateStatusEnum(string value) { return new UpdateStatusEnum(value); } public static readonly UpdateStatusEnum Completed = new UpdateStatusEnum("completed"); } public sealed class ReasonConferenceEndedEnum : StringEnum { private ReasonConferenceEndedEnum(string value) : base(value) {} public ReasonConferenceEndedEnum() {} public static implicit operator ReasonConferenceEndedEnum(string value) { return new ReasonConferenceEndedEnum(value); } public static readonly ReasonConferenceEndedEnum ConferenceEndedViaApi = new ReasonConferenceEndedEnum("conference-ended-via-api"); public static readonly ReasonConferenceEndedEnum ParticipantWithEndConferenceOnExitLeft = new ReasonConferenceEndedEnum("participant-with-end-conference-on-exit-left"); public static readonly ReasonConferenceEndedEnum ParticipantWithEndConferenceOnExitKicked = new ReasonConferenceEndedEnum("participant-with-end-conference-on-exit-kicked"); public static readonly ReasonConferenceEndedEnum LastParticipantKicked = new ReasonConferenceEndedEnum("last-participant-kicked"); public static readonly ReasonConferenceEndedEnum LastParticipantLeft = new ReasonConferenceEndedEnum("last-participant-left"); } private static Request BuildFetchRequest(FetchConferenceOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Conferences/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch an instance of a conference /// </summary> /// <param name="options"> Fetch Conference parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Conference </returns> public static ConferenceResource Fetch(FetchConferenceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch an instance of a conference /// </summary> /// <param name="options"> Fetch Conference parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Conference </returns> public static async System.Threading.Tasks.Task<ConferenceResource> FetchAsync(FetchConferenceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch an instance of a conference /// </summary> /// <param name="pathSid"> The unique string that identifies this resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource(s) to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Conference </returns> public static ConferenceResource Fetch(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchConferenceOptions(pathSid){PathAccountSid = pathAccountSid}; return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch an instance of a conference /// </summary> /// <param name="pathSid"> The unique string that identifies this resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource(s) to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Conference </returns> public static async System.Threading.Tasks.Task<ConferenceResource> FetchAsync(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchConferenceOptions(pathSid){PathAccountSid = pathAccountSid}; return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadConferenceOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Conferences.json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of conferences belonging to the account used to make the request /// </summary> /// <param name="options"> Read Conference parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Conference </returns> public static ResourceSet<ConferenceResource> Read(ReadConferenceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<ConferenceResource>.FromJson("conferences", response.Content); return new ResourceSet<ConferenceResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of conferences belonging to the account used to make the request /// </summary> /// <param name="options"> Read Conference parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Conference </returns> public static async System.Threading.Tasks.Task<ResourceSet<ConferenceResource>> ReadAsync(ReadConferenceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<ConferenceResource>.FromJson("conferences", response.Content); return new ResourceSet<ConferenceResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of conferences belonging to the account used to make the request /// </summary> /// <param name="pathAccountSid"> The SID of the Account that created the resource(s) to read </param> /// <param name="dateCreatedBefore"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="dateCreated"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="dateCreatedAfter"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="dateUpdatedBefore"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="dateUpdated"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="dateUpdatedAfter"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="friendlyName"> The string that identifies the Conference resources to read </param> /// <param name="status"> The status of the resources 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 Conference </returns> public static ResourceSet<ConferenceResource> Read(string pathAccountSid = null, DateTime? dateCreatedBefore = null, DateTime? dateCreated = null, DateTime? dateCreatedAfter = null, DateTime? dateUpdatedBefore = null, DateTime? dateUpdated = null, DateTime? dateUpdatedAfter = null, string friendlyName = null, ConferenceResource.StatusEnum status = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadConferenceOptions(){PathAccountSid = pathAccountSid, DateCreatedBefore = dateCreatedBefore, DateCreated = dateCreated, DateCreatedAfter = dateCreatedAfter, DateUpdatedBefore = dateUpdatedBefore, DateUpdated = dateUpdated, DateUpdatedAfter = dateUpdatedAfter, FriendlyName = friendlyName, Status = status, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of conferences belonging to the account used to make the request /// </summary> /// <param name="pathAccountSid"> The SID of the Account that created the resource(s) to read </param> /// <param name="dateCreatedBefore"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="dateCreated"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="dateCreatedAfter"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="dateUpdatedBefore"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="dateUpdated"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="dateUpdatedAfter"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="friendlyName"> The string that identifies the Conference resources to read </param> /// <param name="status"> The status of the resources 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 Conference </returns> public static async System.Threading.Tasks.Task<ResourceSet<ConferenceResource>> ReadAsync(string pathAccountSid = null, DateTime? dateCreatedBefore = null, DateTime? dateCreated = null, DateTime? dateCreatedAfter = null, DateTime? dateUpdatedBefore = null, DateTime? dateUpdated = null, DateTime? dateUpdatedAfter = null, string friendlyName = null, ConferenceResource.StatusEnum status = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadConferenceOptions(){PathAccountSid = pathAccountSid, DateCreatedBefore = dateCreatedBefore, DateCreated = dateCreated, DateCreatedAfter = dateCreatedAfter, DateUpdatedBefore = dateUpdatedBefore, DateUpdated = dateUpdated, DateUpdatedAfter = dateUpdatedAfter, FriendlyName = friendlyName, Status = status, 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<ConferenceResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<ConferenceResource>.FromJson("conferences", 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<ConferenceResource> NextPage(Page<ConferenceResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<ConferenceResource>.FromJson("conferences", 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<ConferenceResource> PreviousPage(Page<ConferenceResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<ConferenceResource>.FromJson("conferences", response.Content); } private static Request BuildUpdateRequest(UpdateConferenceOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Conferences/" + options.PathSid + ".json", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// update /// </summary> /// <param name="options"> Update Conference parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Conference </returns> public static ConferenceResource Update(UpdateConferenceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update Conference parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Conference </returns> public static async System.Threading.Tasks.Task<ConferenceResource> UpdateAsync(UpdateConferenceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathSid"> The unique string that identifies this resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource(s) to update </param> /// <param name="status"> The new status of the resource </param> /// <param name="announceUrl"> The URL we should call to announce something into the conference </param> /// <param name="announceMethod"> he HTTP method used to call announce_url </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Conference </returns> public static ConferenceResource Update(string pathSid, string pathAccountSid = null, ConferenceResource.UpdateStatusEnum status = null, Uri announceUrl = null, Twilio.Http.HttpMethod announceMethod = null, ITwilioRestClient client = null) { var options = new UpdateConferenceOptions(pathSid){PathAccountSid = pathAccountSid, Status = status, AnnounceUrl = announceUrl, AnnounceMethod = announceMethod}; return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathSid"> The unique string that identifies this resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource(s) to update </param> /// <param name="status"> The new status of the resource </param> /// <param name="announceUrl"> The URL we should call to announce something into the conference </param> /// <param name="announceMethod"> he HTTP method used to call announce_url </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Conference </returns> public static async System.Threading.Tasks.Task<ConferenceResource> UpdateAsync(string pathSid, string pathAccountSid = null, ConferenceResource.UpdateStatusEnum status = null, Uri announceUrl = null, Twilio.Http.HttpMethod announceMethod = null, ITwilioRestClient client = null) { var options = new UpdateConferenceOptions(pathSid){PathAccountSid = pathAccountSid, Status = status, AnnounceUrl = announceUrl, AnnounceMethod = announceMethod}; return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a ConferenceResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> ConferenceResource object represented by the provided JSON </returns> public static ConferenceResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<ConferenceResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created this resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that this resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that this resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The API version used to create this conference /// </summary> [JsonProperty("api_version")] public string ApiVersion { get; private set; } /// <summary> /// A string that you assigned to describe this conference room /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// A string that represents the Twilio Region where the conference was mixed /// </summary> [JsonProperty("region")] public string Region { get; private set; } /// <summary> /// The unique string that identifies this resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The status of this conference /// </summary> [JsonProperty("status")] [JsonConverter(typeof(StringEnumConverter))] public ConferenceResource.StatusEnum Status { get; private set; } /// <summary> /// The URI of this resource, relative to `https://api.twilio.com` /// </summary> [JsonProperty("uri")] public string Uri { get; private set; } /// <summary> /// A list of related resources identified by their relative URIs /// </summary> [JsonProperty("subresource_uris")] public Dictionary<string, string> SubresourceUris { get; private set; } /// <summary> /// The reason why a conference ended. /// </summary> [JsonProperty("reason_conference_ended")] [JsonConverter(typeof(StringEnumConverter))] public ConferenceResource.ReasonConferenceEndedEnum ReasonConferenceEnded { get; private set; } /// <summary> /// The call SID that caused the conference to end /// </summary> [JsonProperty("call_sid_ending_conference")] public string CallSidEndingConference { get; private set; } private ConferenceResource() { } } }
/* * Location Intelligence APIs * * Incorporate our extensive geodata into everyday applications, business processes and workflows. * * OpenAPI spec version: 8.5.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using RestSharp; using NUnit.Framework; using pb.locationIntelligence.Client; using pb.locationIntelligence.Api; using pb.locationIntelligence.Model; namespace pb.locationIntelligence.Test { /// <summary> /// Class for testing LIAPIGeoRiskServiceApi /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the API endpoint. /// </remarks> [TestFixture] public class LIAPIGeoRiskServiceApiTests { private LIAPIGeoRiskServiceApi instance; /// <summary> /// Setup before each unit test /// </summary> [SetUp] public void Init() { instance = new LIAPIGeoRiskServiceApi(); } /// <summary> /// Clean up after each unit test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of LIAPIGeoRiskServiceApi /// </summary> [Test] public void InstanceTest() { // test 'IsInstanceOfType' LIAPIGeoRiskServiceApi Assert.IsInstanceOf(typeof(LIAPIGeoRiskServiceApi), instance, "instance is a LIAPIGeoRiskServiceApi"); } /// <summary> /// Test GetCrimeRiskByAddress /// </summary> [Test] public void GetCrimeRiskByAddressTest() { // TODO uncomment below to test the method and replace null with proper value //string address = null; //string type = null; //string includeGeometry = null; //var response = instance.GetCrimeRiskByAddress(address, type, includeGeometry); //Assert.IsInstanceOf<CrimeRiskResponse> (response, "response is CrimeRiskResponse"); } /// <summary> /// Test GetCrimeRiskByAddressBatch /// </summary> [Test] public void GetCrimeRiskByAddressBatchTest() { // TODO uncomment below to test the method and replace null with proper value //CrimeRiskByAddressRequest body = null; //var response = instance.GetCrimeRiskByAddressBatch(body); //Assert.IsInstanceOf<CrimeRiskResponseList> (response, "response is CrimeRiskResponseList"); } /// <summary> /// Test GetCrimeRiskByLocation /// </summary> [Test] public void GetCrimeRiskByLocationTest() { // TODO uncomment below to test the method and replace null with proper value //string longitude = null; //string latitude = null; //string type = null; //string includeGeometry = null; //var response = instance.GetCrimeRiskByLocation(longitude, latitude, type, includeGeometry); //Assert.IsInstanceOf<CrimeRiskLocationResponse> (response, "response is CrimeRiskLocationResponse"); } /// <summary> /// Test GetCrimeRiskByLocationBatch /// </summary> [Test] public void GetCrimeRiskByLocationBatchTest() { // TODO uncomment below to test the method and replace null with proper value //CrimeRiskByLocationRequest body = null; //var response = instance.GetCrimeRiskByLocationBatch(body); //Assert.IsInstanceOf<CrimeRiskLocationResponseList> (response, "response is CrimeRiskLocationResponseList"); } /// <summary> /// Test GetDistanceToFloodHazardByAddress /// </summary> [Test] public void GetDistanceToFloodHazardByAddressTest() { // TODO uncomment below to test the method and replace null with proper value //string address = null; //string maxCandidates = null; //string waterBodyType = null; //string searchDistance = null; //string searchDistanceUnit = null; //var response = instance.GetDistanceToFloodHazardByAddress(address, maxCandidates, waterBodyType, searchDistance, searchDistanceUnit); //Assert.IsInstanceOf<WaterBodyResponse> (response, "response is WaterBodyResponse"); } /// <summary> /// Test GetDistanceToFloodHazardByAddressBatch /// </summary> [Test] public void GetDistanceToFloodHazardByAddressBatchTest() { // TODO uncomment below to test the method and replace null with proper value //DistanceToFloodHazardAddressRequest body = null; //var response = instance.GetDistanceToFloodHazardByAddressBatch(body); //Assert.IsInstanceOf<DistanceToFloodHazardResponse> (response, "response is DistanceToFloodHazardResponse"); } /// <summary> /// Test GetDistanceToFloodHazardByLocation /// </summary> [Test] public void GetDistanceToFloodHazardByLocationTest() { // TODO uncomment below to test the method and replace null with proper value //string longitude = null; //string latitude = null; //string maxCandidates = null; //string waterBodyType = null; //string searchDistance = null; //string searchDistanceUnit = null; //var response = instance.GetDistanceToFloodHazardByLocation(longitude, latitude, maxCandidates, waterBodyType, searchDistance, searchDistanceUnit); //Assert.IsInstanceOf<WaterBodyLocationResponse> (response, "response is WaterBodyLocationResponse"); } /// <summary> /// Test GetDistanceToFloodHazardByLocationBatch /// </summary> [Test] public void GetDistanceToFloodHazardByLocationBatchTest() { // TODO uncomment below to test the method and replace null with proper value //DistanceToFloodHazardLocationRequest body = null; //var response = instance.GetDistanceToFloodHazardByLocationBatch(body); //Assert.IsInstanceOf<DistanceToFloodHazardLocationResponse> (response, "response is DistanceToFloodHazardLocationResponse"); } /// <summary> /// Test GetEarthquakeHistory /// </summary> [Test] public void GetEarthquakeHistoryTest() { // TODO uncomment below to test the method and replace null with proper value //string postCode = null; //string startDate = null; //string endDate = null; //string minMagnitude = null; //string maxMagnitude = null; //string maxCandidates = null; //var response = instance.GetEarthquakeHistory(postCode, startDate, endDate, minMagnitude, maxMagnitude, maxCandidates); //Assert.IsInstanceOf<EarthquakeHistory> (response, "response is EarthquakeHistory"); } /// <summary> /// Test GetEarthquakeRiskByAddress /// </summary> [Test] public void GetEarthquakeRiskByAddressTest() { // TODO uncomment below to test the method and replace null with proper value //string address = null; //string richterValue = null; //string includeGeometry = null; //var response = instance.GetEarthquakeRiskByAddress(address, richterValue, includeGeometry); //Assert.IsInstanceOf<EarthquakeRiskResponse> (response, "response is EarthquakeRiskResponse"); } /// <summary> /// Test GetEarthquakeRiskByAddressBatch /// </summary> [Test] public void GetEarthquakeRiskByAddressBatchTest() { // TODO uncomment below to test the method and replace null with proper value //EarthquakeRiskByAddressRequest body = null; //var response = instance.GetEarthquakeRiskByAddressBatch(body); //Assert.IsInstanceOf<EarthquakeRiskResponseList> (response, "response is EarthquakeRiskResponseList"); } /// <summary> /// Test GetEarthquakeRiskByLocation /// </summary> [Test] public void GetEarthquakeRiskByLocationTest() { // TODO uncomment below to test the method and replace null with proper value //string longitude = null; //string latitude = null; //string richterValue = null; //string includeGeometry = null; //var response = instance.GetEarthquakeRiskByLocation(longitude, latitude, richterValue, includeGeometry); //Assert.IsInstanceOf<EarthquakeRiskLocationResponse> (response, "response is EarthquakeRiskLocationResponse"); } /// <summary> /// Test GetEarthquakeRiskByLocationBatch /// </summary> [Test] public void GetEarthquakeRiskByLocationBatchTest() { // TODO uncomment below to test the method and replace null with proper value //EarthquakeRiskByLocationRequest body = null; //var response = instance.GetEarthquakeRiskByLocationBatch(body); //Assert.IsInstanceOf<EarthquakeRiskLocationResponseList> (response, "response is EarthquakeRiskLocationResponseList"); } /// <summary> /// Test GetFireHistory /// </summary> [Test] public void GetFireHistoryTest() { // TODO uncomment below to test the method and replace null with proper value //string postCode = null; //string startDate = null; //string endDate = null; //string maxCandidates = null; //var response = instance.GetFireHistory(postCode, startDate, endDate, maxCandidates); //Assert.IsInstanceOf<FireHistory> (response, "response is FireHistory"); } /// <summary> /// Test GetFireRiskByAddress /// </summary> [Test] public void GetFireRiskByAddressTest() { // TODO uncomment below to test the method and replace null with proper value //string address = null; //var response = instance.GetFireRiskByAddress(address); //Assert.IsInstanceOf<FireRiskResponse> (response, "response is FireRiskResponse"); } /// <summary> /// Test GetFireRiskByAddressBatch /// </summary> [Test] public void GetFireRiskByAddressBatchTest() { // TODO uncomment below to test the method and replace null with proper value //FireRiskByAddressRequest body = null; //var response = instance.GetFireRiskByAddressBatch(body); //Assert.IsInstanceOf<FireRiskResponseList> (response, "response is FireRiskResponseList"); } /// <summary> /// Test GetFireRiskByLocation /// </summary> [Test] public void GetFireRiskByLocationTest() { // TODO uncomment below to test the method and replace null with proper value //string longitude = null; //string latitude = null; //var response = instance.GetFireRiskByLocation(longitude, latitude); //Assert.IsInstanceOf<FireRiskLocationResponse> (response, "response is FireRiskLocationResponse"); } /// <summary> /// Test GetFireRiskByLocationBatch /// </summary> [Test] public void GetFireRiskByLocationBatchTest() { // TODO uncomment below to test the method and replace null with proper value //FireRiskByLocationRequest body = null; //var response = instance.GetFireRiskByLocationBatch(body); //Assert.IsInstanceOf<FireRiskLocationResponseList> (response, "response is FireRiskLocationResponseList"); } /// <summary> /// Test GetFireStationByAddress /// </summary> [Test] public void GetFireStationByAddressTest() { // TODO uncomment below to test the method and replace null with proper value //string address = null; //string maxCandidates = null; //string travelTime = null; //string travelTimeUnit = null; //string travelDistance = null; //string travelDistanceUnit = null; //string sortBy = null; //string historicTrafficTimeBucket = null; //var response = instance.GetFireStationByAddress(address, maxCandidates, travelTime, travelTimeUnit, travelDistance, travelDistanceUnit, sortBy, historicTrafficTimeBucket); //Assert.IsInstanceOf<FireStations> (response, "response is FireStations"); } /// <summary> /// Test GetFireStationByLocation /// </summary> [Test] public void GetFireStationByLocationTest() { // TODO uncomment below to test the method and replace null with proper value //string longitude = null; //string latitude = null; //string maxCandidates = null; //string travelTime = null; //string travelTimeUnit = null; //string travelDistance = null; //string travelDistanceUnit = null; //string sortBy = null; //string historicTrafficTimeBucket = null; //var response = instance.GetFireStationByLocation(longitude, latitude, maxCandidates, travelTime, travelTimeUnit, travelDistance, travelDistanceUnit, sortBy, historicTrafficTimeBucket); //Assert.IsInstanceOf<FireStationsLocation> (response, "response is FireStationsLocation"); } /// <summary> /// Test GetFloodRiskByAddress /// </summary> [Test] public void GetFloodRiskByAddressTest() { // TODO uncomment below to test the method and replace null with proper value //string address = null; //string includeZoneDesc = null; //string includeGeometry = null; //var response = instance.GetFloodRiskByAddress(address, includeZoneDesc, includeGeometry); //Assert.IsInstanceOf<FloodRiskResponse> (response, "response is FloodRiskResponse"); } /// <summary> /// Test GetFloodRiskByAddressBatch /// </summary> [Test] public void GetFloodRiskByAddressBatchTest() { // TODO uncomment below to test the method and replace null with proper value //FloodRiskByAddressRequest body = null; //var response = instance.GetFloodRiskByAddressBatch(body); //Assert.IsInstanceOf<FloodRiskResponseList> (response, "response is FloodRiskResponseList"); } /// <summary> /// Test GetFloodRiskByLocation /// </summary> [Test] public void GetFloodRiskByLocationTest() { // TODO uncomment below to test the method and replace null with proper value //string longitude = null; //string latitude = null; //string includeZoneDesc = null; //string includeGeometry = null; //var response = instance.GetFloodRiskByLocation(longitude, latitude, includeZoneDesc, includeGeometry); //Assert.IsInstanceOf<FloodRiskLocationResponse> (response, "response is FloodRiskLocationResponse"); } /// <summary> /// Test GetFloodRiskByLocationBatch /// </summary> [Test] public void GetFloodRiskByLocationBatchTest() { // TODO uncomment below to test the method and replace null with proper value //FloodRiskByLocationRequest body = null; //var response = instance.GetFloodRiskByLocationBatch(body); //Assert.IsInstanceOf<FloodRiskLocationResponseList> (response, "response is FloodRiskLocationResponseList"); } } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; //Helper data classes for ParserDataBuilder // Note about using LRItemSet vs LRItemList. // It appears that in many places the LRItemList would be a better (and faster) choice than LRItemSet. // Many of the sets are actually lists and don't require hashset's functionality. // But surprisingly, using LRItemSet proved to have much better performance (twice faster for lookbacks/lookaheads computation), so LRItemSet // is used everywhere. namespace Irony.Parsing.Construction { internal class ParserStateData { public readonly ParserState State; public readonly LRItemSet AllItems = new LRItemSet(); public readonly LRItemSet ShiftItems = new LRItemSet(); public readonly LRItemSet ReduceItems = new LRItemSet(); public readonly LRItemSet InitialItems = new LRItemSet(); public readonly BnfTermSet ShiftTerms = new BnfTermSet(); public readonly TerminalSet ShiftTerminals = new TerminalSet(); public readonly TerminalSet Conflicts = new TerminalSet(); public readonly TerminalSet ResolvedConflicts = new TerminalSet(); public readonly bool IsInadequate; public LR0ItemSet AllCores = new LR0ItemSet(); //used for creating canonical states from core set public ParserStateData(ParserState state, LR0ItemSet kernelCores) { State = state; foreach (var core in kernelCores) AddItem(core); IsInadequate = ReduceItems.Count > 1 || ReduceItems.Count == 1 && ShiftItems.Count > 0; } public void AddItem(LR0Item core) { //Check if a core had been already added. If yes, simply return if(!AllCores.Add(core))return ; //Create new item, add it to AllItems, InitialItems, ReduceItems or ShiftItems var item = new LRItem(State, core); AllItems.Add(item); if (item.Core.IsFinal) ReduceItems.Add(item); else ShiftItems.Add(item); if (item.Core.IsInitial) InitialItems.Add(item); if (core.IsFinal) return; //Add current term to ShiftTerms if (!ShiftTerms.Add(core.Current)) return; if (core.Current is Terminal) ShiftTerminals.Add(core.Current as Terminal); //If current term (core.Current) is a new non-terminal, expand it var currNt = core.Current as NonTerminal; if (currNt == null) return; foreach(var prod in currNt.Productions) AddItem(prod.LR0Items[0]); }//method public TransitionTable Transitions { get { if(_transitions == null) _transitions = new TransitionTable(); return _transitions; } } TransitionTable _transitions; //A set of states reachable through shifts over nullable non-terminals. Computed on demand public ParserStateSet ReadStateSet { get { if(_readStateSet == null) { _readStateSet = new ParserStateSet(); foreach(var shiftTerm in State.BuilderData.ShiftTerms) if (shiftTerm.Flags.IsSet(TermFlags.IsNullable)) { var targetState = State.Actions[shiftTerm].NewState; _readStateSet.Add(targetState); _readStateSet.UnionWith(targetState.BuilderData.ReadStateSet); //we shouldn't get into loop here, the chain of reads is finite } }//if return _readStateSet; } } ParserStateSet _readStateSet; public TerminalSet GetShiftReduceConflicts() { var result = new TerminalSet(); result.UnionWith(Conflicts); result.IntersectWith(ShiftTerminals); return result; } public TerminalSet GetReduceReduceConflicts() { var result = new TerminalSet(); result.UnionWith(Conflicts); result.ExceptWith(ShiftTerminals); return result; } }//class //An object representing inter-state transitions. Defines Includes, IncludedBy that are used for efficient lookahead computation internal class Transition { public readonly ParserState FromState; public readonly ParserState ToState; public readonly NonTerminal OverNonTerminal; public readonly LRItemSet Items; public readonly TransitionSet Includes = new TransitionSet(); public readonly TransitionSet IncludedBy = new TransitionSet(); int _hashCode; public Transition(ParserState fromState, NonTerminal overNonTerminal) { FromState = fromState; OverNonTerminal = overNonTerminal; ToState = FromState.Actions[overNonTerminal].NewState; _hashCode = unchecked(FromState.GetHashCode() - overNonTerminal.GetHashCode()); FromState.BuilderData.Transitions.Add(overNonTerminal, this); Items = FromState.BuilderData.ShiftItems.SelectByCurrent(overNonTerminal); foreach(var item in Items) { item.Transition = this; } }//constructor public void Include(Transition other) { if (other == this) return; if (!IncludeTransition(other)) return; //include children foreach(var child in other.Includes) { IncludeTransition(child); } } private bool IncludeTransition(Transition other) { if (!Includes.Add(other)) return false; other.IncludedBy.Add(this); //propagate "up" foreach(var incBy in IncludedBy) incBy.IncludeTransition(other); return true; } public override string ToString() { return FromState.Name + " -> (over " + OverNonTerminal.Name + ") -> " + ToState.Name; } public override int GetHashCode() { return _hashCode; } }//class internal class TransitionSet : HashSet<Transition> { } internal class TransitionList : List<Transition> { } internal class TransitionTable : Dictionary<NonTerminal, Transition> { } internal class LRItem { public readonly ParserState State; public readonly LR0Item Core; //these properties are used in lookahead computations public LRItem ShiftedItem; public Transition Transition; int _hashCode; //Lookahead info for reduce items public TransitionSet Lookbacks = new TransitionSet(); public TerminalSet Lookaheads = new TerminalSet(); public LRItem(ParserState state, LR0Item core) { State = state; Core = core; _hashCode = unchecked(state.GetHashCode() + core.GetHashCode()); } public override string ToString() { return Core.ToString(); } public override int GetHashCode() { return _hashCode; } }//LRItem class internal class LRItemList : List<LRItem> {} internal class LRItemSet : HashSet<LRItem> { public LRItem FindByCore(LR0Item core) { foreach (LRItem item in this) if (item.Core == core) return item; return null; } public LRItemSet SelectByCurrent(BnfTerm current) { var result = new LRItemSet(); foreach (var item in this) if (item.Core.Current == current) result.Add(item); return result; } public LR0ItemSet GetShiftedCores() { var result = new LR0ItemSet(); foreach (var item in this) if (item.Core.ShiftedItem != null) result.Add(item.Core.ShiftedItem); return result; } public LRItemSet SelectByLookahead(Terminal lookahead) { var result = new LRItemSet(); foreach (var item in this) if (item.Lookaheads.Contains(lookahead)) result.Add(item); return result; } }//class public partial class LR0Item { public readonly Production Production; public readonly int Position; public readonly BnfTerm Current; public bool TailIsNullable; public GrammarHintList Hints = new GrammarHintList(); //automatically generated IDs - used for building keys for lists of kernel LR0Items // which in turn are used to quickly lookup parser states in hash internal readonly int ID; public LR0Item(int id, Production production, int position, GrammarHintList hints) { ID = id; Production = production; Position = position; Current = (Position < Production.RValues.Count) ? Production.RValues[Position] : null; if (hints != null) Hints.AddRange(hints); _hashCode = ID.ToString().GetHashCode(); }//method public LR0Item ShiftedItem { get { if (Position >= Production.LR0Items.Count - 1) return null; else return Production.LR0Items[Position + 1]; } } public bool IsKernel { get { return Position > 0; } } public bool IsInitial { get { return Position == 0; } } public bool IsFinal { get { return Position == Production.RValues.Count; } } public override string ToString() { return Production.ProductionToString(Production, Position); } public override int GetHashCode() { return _hashCode; } int _hashCode; }//LR0Item internal class LR0ItemList : List<LR0Item> { } internal class LR0ItemSet : HashSet<LR0Item> { } }//namespace
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Globalization; namespace System.Net { // More sophisticated password cache that stores multiple // name-password pairs and associates these with host/realm. public class CredentialCache : ICredentials, ICredentialsByHost, IEnumerable { private readonly Dictionary<CredentialKey, NetworkCredential> _cache = new Dictionary<CredentialKey, NetworkCredential>(); private readonly Dictionary<CredentialHostKey, NetworkCredential> _cacheForHosts = new Dictionary<CredentialHostKey, NetworkCredential>(); internal int _version; private int _numbDefaultCredInCache = 0; // [thread token optimization] The resulting counter of default credential resided in the cache. internal bool IsDefaultInCache { get { return _numbDefaultCredInCache != 0; } } /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Net.CredentialCache'/> class. /// </para> /// </devdoc> public CredentialCache() { } /// <devdoc> /// <para> /// Adds a <see cref='System.Net.NetworkCredential'/> instance to the credential cache. /// </para> /// </devdoc> public void Add(Uri uriPrefix, string authenticationType, NetworkCredential credential) { // Parameter validation if (uriPrefix == null) { throw new ArgumentNullException("uriPrefix"); } if (authenticationType == null) { throw new ArgumentNullException("authenticationType"); } ++_version; CredentialKey key = new CredentialKey(uriPrefix, authenticationType); if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + credential.Domain + "],[" + credential.UserName + "]"); } _cache.Add(key, credential); if (credential is SystemNetworkCredential) { ++_numbDefaultCredInCache; } } public void Add(string host, int port, string authenticationType, NetworkCredential credential) { // Parameter validation if (host == null) { throw new ArgumentNullException("host"); } if (authenticationType == null) { throw new ArgumentNullException("authenticationType"); } if (host.Length == 0) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, "host")); } if (port < 0) { throw new ArgumentOutOfRangeException("port"); } ++_version; CredentialHostKey key = new CredentialHostKey(host, port, authenticationType); if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + credential.Domain + "],[" + credential.UserName + "]"); } _cacheForHosts.Add(key, credential); if (credential is SystemNetworkCredential) { ++_numbDefaultCredInCache; } } /// <devdoc> /// <para> /// Removes a <see cref='System.Net.NetworkCredential'/> instance from the credential cache. /// </para> /// </devdoc> public void Remove(Uri uriPrefix, string authenticationType) { if (uriPrefix == null || authenticationType == null) { // These couldn't possibly have been inserted into // the cache because of the test in Add(). return; } ++_version; CredentialKey key = new CredentialKey(uriPrefix, authenticationType); if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]"); } if (_cache[key] is SystemNetworkCredential) { --_numbDefaultCredInCache; } _cache.Remove(key); } public void Remove(string host, int port, string authenticationType) { if (host == null || authenticationType == null) { // These couldn't possibly have been inserted into // the cache because of the test in Add(). return; } if (port < 0) { return; } ++_version; CredentialHostKey key = new CredentialHostKey(host, port, authenticationType); if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]"); } if (_cacheForHosts[key] is SystemNetworkCredential) { --_numbDefaultCredInCache; } _cacheForHosts.Remove(key); } /// <devdoc> /// <para> /// Returns the <see cref='System.Net.NetworkCredential'/> /// instance associated with the supplied Uri and /// authentication type. /// </para> /// </devdoc> public NetworkCredential GetCredential(Uri uriPrefix, string authenticationType) { if (uriPrefix == null) { throw new ArgumentNullException("uriPrefix"); } if (authenticationType == null) { throw new ArgumentNullException("authenticationType"); } if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::GetCredential(uriPrefix=\"" + uriPrefix + "\", authType=\"" + authenticationType + "\")"); } int longestMatchPrefix = -1; NetworkCredential mostSpecificMatch = null; IDictionaryEnumerator credEnum = _cache.GetEnumerator(); // Enumerate through every credential in the cache while (credEnum.MoveNext()) { CredentialKey key = (CredentialKey)credEnum.Key; // Determine if this credential is applicable to the current Uri/AuthType if (key.Match(uriPrefix, authenticationType)) { int prefixLen = key.UriPrefixLength; // Check if the match is better than the current-most-specific match if (prefixLen > longestMatchPrefix) { // Yes: update the information about currently preferred match longestMatchPrefix = prefixLen; mostSpecificMatch = (NetworkCredential)credEnum.Value; } } } if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::GetCredential returning " + ((mostSpecificMatch == null) ? "null" : "(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")")); } return mostSpecificMatch; } public NetworkCredential GetCredential(string host, int port, string authenticationType) { if (host == null) { throw new ArgumentNullException("host"); } if (authenticationType == null) { throw new ArgumentNullException("authenticationType"); } if (host.Length == 0) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, "host")); } if (port < 0) { throw new ArgumentOutOfRangeException("port"); } if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::GetCredential(host=\"" + host + ":" + port.ToString() + "\", authenticationType=\"" + authenticationType + "\")"); } NetworkCredential match = null; IDictionaryEnumerator credEnum = _cacheForHosts.GetEnumerator(); // Enumerate through every credential in the cache while (credEnum.MoveNext()) { CredentialHostKey key = (CredentialHostKey)credEnum.Key; // Determine if this credential is applicable to the current Uri/AuthType if (key.Match(host, port, authenticationType)) { match = (NetworkCredential)credEnum.Value; } } if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::GetCredential returning " + ((match == null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")")); } return match; } public IEnumerator GetEnumerator() { return new CredentialEnumerator(this, _cache, _cacheForHosts, _version); } /// <devdoc> /// <para> /// Gets the default system credentials from the <see cref='System.Net.CredentialCache'/>. /// </para> /// </devdoc> public static ICredentials DefaultCredentials { get { return SystemNetworkCredential.s_defaultCredential; } } public static NetworkCredential DefaultNetworkCredentials { get { return SystemNetworkCredential.s_defaultCredential; } } private class CredentialEnumerator : IEnumerator { private CredentialCache _cache; private ICredentials[] _array; private int _index = -1; private int _version; internal CredentialEnumerator(CredentialCache cache, Dictionary<CredentialKey, NetworkCredential> table, Dictionary<CredentialHostKey, NetworkCredential> hostTable, int version) { _cache = cache; _array = new ICredentials[table.Count + hostTable.Count]; ((ICollection)table.Values).CopyTo(_array, 0); ((ICollection)hostTable.Values).CopyTo(_array, table.Count); _version = version; } object IEnumerator.Current { get { if (_index < 0 || _index >= _array.Length) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } if (_version != _cache._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } return _array[_index]; } } bool IEnumerator.MoveNext() { if (_version != _cache._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if (++_index < _array.Length) { return true; } _index = _array.Length; return false; } void IEnumerator.Reset() { _index = -1; } } } // Abstraction for credentials in password-based // authentication schemes (basic, digest, NTLM, Kerberos). // // Note that this is not applicable to public-key based // systems such as SSL client authentication. // // "Password" here may be the clear text password or it // could be a one-way hash that is sufficient to // authenticate, as in HTTP/1.1 digest. internal class SystemNetworkCredential : NetworkCredential { internal static readonly SystemNetworkCredential s_defaultCredential = new SystemNetworkCredential(); // We want reference equality to work. Making this private is a good way to guarantee that. private SystemNetworkCredential() : base(string.Empty, string.Empty, string.Empty) { } } internal class CredentialHostKey : IEquatable<CredentialHostKey> { public readonly string Host; public readonly string AuthenticationType; public readonly int Port; internal CredentialHostKey(string host, int port, string authenticationType) { Host = host; Port = port; AuthenticationType = authenticationType; } internal bool Match(string host, int port, string authenticationType) { if (host == null || authenticationType == null) { return false; } // If the protocols don't match, this credential is not applicable for the given Uri. if (!string.Equals(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase) || !string.Equals(Host, host, StringComparison.OrdinalIgnoreCase) || port != Port) { return false; } if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialKey::Match(" + Host.ToString() + ":" + Port.ToString() + " & " + host.ToString() + ":" + port.ToString() + ")"); } return true; } private int _hashCode = 0; private bool _computedHashCode = false; public override int GetHashCode() { if (!_computedHashCode) { // Compute HashCode on demand _hashCode = AuthenticationType.ToUpperInvariant().GetHashCode() + Host.ToUpperInvariant().GetHashCode() + Port.GetHashCode(); _computedHashCode = true; } return _hashCode; } public bool Equals(CredentialHostKey other) { if (other == null) { return false; } bool equals = string.Equals(AuthenticationType, other.AuthenticationType, StringComparison.OrdinalIgnoreCase) && string.Equals(Host, other.Host, StringComparison.OrdinalIgnoreCase) && Port == other.Port; if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + other.ToString() + ") returns " + equals.ToString()); } return equals; } public override bool Equals(object comparand) { return Equals(comparand as CredentialHostKey); } public override string ToString() { return "[" + Host.Length.ToString(NumberFormatInfo.InvariantInfo) + "]:" + Host + ":" + Port.ToString(NumberFormatInfo.InvariantInfo) + ":" + LoggingHash.ObjectToString(AuthenticationType); } } internal class CredentialKey : IEquatable<CredentialKey> { public readonly Uri UriPrefix; public readonly int UriPrefixLength = -1; public readonly string AuthenticationType; private int _hashCode = 0; private bool _computedHashCode = false; internal CredentialKey(Uri uriPrefix, string authenticationType) { UriPrefix = uriPrefix; UriPrefixLength = UriPrefix.ToString().Length; AuthenticationType = authenticationType; } internal bool Match(Uri uri, string authenticationType) { if (uri == null || authenticationType == null) { return false; } // If the protocols don't match, this credential is not applicable for the given Uri. if (!string.Equals(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase)) { return false; } if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialKey::Match(" + UriPrefix.ToString() + " & " + uri.ToString() + ")"); } return IsPrefix(uri, UriPrefix); } // IsPrefix (Uri) // // Determines whether <prefixUri> is a prefix of this URI. A prefix // match is defined as: // // scheme match // + host match // + port match, if any // + <prefix> path is a prefix of <URI> path, if any // // Returns: // True if <prefixUri> is a prefix of this URI internal bool IsPrefix(Uri uri, Uri prefixUri) { if (prefixUri.Scheme != uri.Scheme || prefixUri.Host != uri.Host || prefixUri.Port != uri.Port) { return false; } int prefixLen = prefixUri.AbsolutePath.LastIndexOf('/'); if (prefixLen > uri.AbsolutePath.LastIndexOf('/')) { return false; } return String.Compare(uri.AbsolutePath, 0, prefixUri.AbsolutePath, 0, prefixLen, StringComparison.OrdinalIgnoreCase) == 0; } public override int GetHashCode() { if (!_computedHashCode) { // Compute HashCode on demand _hashCode = AuthenticationType.ToUpperInvariant().GetHashCode() + UriPrefixLength + UriPrefix.GetHashCode(); _computedHashCode = true; } return _hashCode; } public bool Equals(CredentialKey other) { if (other == null) { return false; } bool equals = string.Equals(AuthenticationType, other.AuthenticationType, StringComparison.OrdinalIgnoreCase) && UriPrefix.Equals(other.UriPrefix); if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + other.ToString() + ") returns " + equals.ToString()); } return equals; } public override bool Equals(object comparand) { return Equals(comparand as CredentialKey); } public override string ToString() { return "[" + UriPrefixLength.ToString(NumberFormatInfo.InvariantInfo) + "]:" + LoggingHash.ObjectToString(UriPrefix) + ":" + LoggingHash.ObjectToString(AuthenticationType); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Provides methods to directly work against the Git object database /// without involving the index nor the working directory. /// </summary> public class ObjectDatabase : IEnumerable<GitObject> { private readonly Repository repo; private readonly ObjectDatabaseSafeHandle handle; /// <summary> /// Needed for mocking purposes. /// </summary> protected ObjectDatabase() { } internal ObjectDatabase(Repository repo) { this.repo = repo; handle = Proxy.git_repository_odb(repo.Handle); repo.RegisterForCleanup(handle); } #region Implementation of IEnumerable /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the collection.</returns> public virtual IEnumerator<GitObject> GetEnumerator() { ICollection<GitOid> oids = Proxy.git_odb_foreach(handle, ptr => ptr.MarshalAs<GitOid>()); return oids .Select(gitOid => repo.Lookup<GitObject>(new ObjectId(gitOid))) .GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion /// <summary> /// Determines if the given object can be found in the object database. /// </summary> /// <param name="objectId">Identifier of the object being searched for.</param> /// <returns>True if the object has been found; false otherwise.</returns> public virtual bool Contains(ObjectId objectId) { Ensure.ArgumentNotNull(objectId, "objectId"); return Proxy.git_odb_exists(handle, objectId); } /// <summary> /// Retrieves the header of a GitObject from the object database. The header contains the Size /// and Type of the object. Note that most backends do not support reading only the header /// of an object, so the whole object will be read and then size would be returned. /// </summary> /// <param name="objectId">Object Id of the queried object</param> /// <returns>GitObjectMetadata object instance containg object header information</returns> public virtual GitObjectMetadata RetrieveObjectMetadata(ObjectId objectId) { Ensure.ArgumentNotNull(objectId, "objectId"); return Proxy.git_odb_read_header(handle, objectId); } /// <summary> /// Inserts a <see cref="Blob"/> into the object database, created from the content of a file. /// </summary> /// <param name="path">Path to the file to create the blob from. A relative path is allowed to /// be passed if the <see cref="Repository"/> is a standard, non-bare, repository. The path /// will then be considered as a path relative to the root of the working directory.</param> /// <returns>The created <see cref="Blob"/>.</returns> public virtual Blob CreateBlob(string path) { Ensure.ArgumentNotNullOrEmptyString(path, "path"); if (repo.Info.IsBare && !Path.IsPathRooted(path)) { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "Cannot create a blob in a bare repository from a relative path ('{0}').", path)); } ObjectId id = Path.IsPathRooted(path) ? Proxy.git_blob_create_fromdisk(repo.Handle, path) : Proxy.git_blob_create_fromfile(repo.Handle, path); return repo.Lookup<Blob>(id); } /// <summary> /// Adds the provided backend to the object database with the specified priority. /// <para> /// If the provided backend implements <see cref="IDisposable"/>, the <see cref="IDisposable.Dispose"/> /// method will be honored and invoked upon the disposal of the repository. /// </para> /// </summary> /// <param name="backend">The backend to add</param> /// <param name="priority">The priority at which libgit2 should consult this backend (higher values are consulted first)</param> public virtual void AddBackend(OdbBackend backend, int priority) { Ensure.ArgumentNotNull(backend, "backend"); Ensure.ArgumentConformsTo(priority, s => s > 0, "priority"); Proxy.git_odb_add_backend(handle, backend.GitOdbBackendPointer, priority); } private class Processor { private readonly Stream stream; private readonly long? numberOfBytesToConsume; private int totalNumberOfReadBytes; public Processor(Stream stream, long? numberOfBytesToConsume) { this.stream = stream; this.numberOfBytesToConsume = numberOfBytesToConsume; } public int Provider(IntPtr content, int max_length, IntPtr data) { var local = new byte[max_length]; int bytesToRead = max_length; if (numberOfBytesToConsume.HasValue) { long totalRemainingBytesToRead = numberOfBytesToConsume.Value - totalNumberOfReadBytes; if (totalRemainingBytesToRead < max_length) { bytesToRead = totalRemainingBytesToRead > int.MaxValue ? int.MaxValue : (int)totalRemainingBytesToRead; } } if (bytesToRead == 0) { return 0; } int numberOfReadBytes = stream.Read(local, 0, bytesToRead); if (numberOfBytesToConsume.HasValue && numberOfReadBytes == 0) { return (int)GitErrorCode.User; } totalNumberOfReadBytes += numberOfReadBytes; Marshal.Copy(local, 0, content, numberOfReadBytes); return numberOfReadBytes; } } /// <summary> /// Inserts a <see cref="Blob"/> into the object database, created from the content of a stream. /// <para>Optionally, git filters will be applied to the content before storing it.</para> /// </summary> /// <param name="stream">The stream from which will be read the content of the blob to be created.</param> /// <returns>The created <see cref="Blob"/>.</returns> public virtual Blob CreateBlob(Stream stream) { return CreateBlob(stream, null, null); } /// <summary> /// Inserts a <see cref="Blob"/> into the object database, created from the content of a stream. /// <para>Optionally, git filters will be applied to the content before storing it.</para> /// </summary> /// <param name="stream">The stream from which will be read the content of the blob to be created.</param> /// <param name="hintpath">The hintpath is used to determine what git filters should be applied to the object before it can be placed to the object database.</param> /// <returns>The created <see cref="Blob"/>.</returns> public virtual Blob CreateBlob(Stream stream, string hintpath) { return CreateBlob(stream, hintpath, null); } /// <summary> /// Inserts a <see cref="Blob"/> into the object database, created from the content of a stream. /// <para>Optionally, git filters will be applied to the content before storing it.</para> /// </summary> /// <param name="stream">The stream from which will be read the content of the blob to be created.</param> /// <param name="hintpath">The hintpath is used to determine what git filters should be applied to the object before it can be placed to the object database.</param> /// <param name="numberOfBytesToConsume">The number of bytes to consume from the stream.</param> /// <returns>The created <see cref="Blob"/>.</returns> public virtual Blob CreateBlob(Stream stream, string hintpath, long numberOfBytesToConsume) { return CreateBlob(stream, hintpath, (long?)numberOfBytesToConsume); } private Blob CreateBlob(Stream stream, string hintpath, long? numberOfBytesToConsume) { Ensure.ArgumentNotNull(stream, "stream"); // there's no need to buffer the file for filtering, so simply use a stream if (hintpath == null && numberOfBytesToConsume.HasValue) { return CreateBlob(stream, numberOfBytesToConsume.Value); } if (!stream.CanRead) { throw new ArgumentException("The stream cannot be read from.", "stream"); } var proc = new Processor(stream, numberOfBytesToConsume); ObjectId id = Proxy.git_blob_create_fromchunks(repo.Handle, hintpath, proc.Provider); return repo.Lookup<Blob>(id); } /// <summary> /// Inserts a <see cref="Blob"/> into the object database created from the content of the stream. /// </summary> /// <param name="stream">The stream from which will be read the content of the blob to be created.</param> /// <param name="numberOfBytesToConsume">Number of bytes to consume from the stream.</param> /// <returns>The created <see cref="Blob"/>.</returns> public virtual Blob CreateBlob(Stream stream, long numberOfBytesToConsume) { Ensure.ArgumentNotNull(stream, "stream"); if (!stream.CanRead) { throw new ArgumentException("The stream cannot be read from.", "stream"); } using (var odbStream = Proxy.git_odb_open_wstream(handle, numberOfBytesToConsume, GitObjectType.Blob)) { var buffer = new byte[4*1024]; long totalRead = 0; while (totalRead < numberOfBytesToConsume) { long left = numberOfBytesToConsume - totalRead; int toRead = left < buffer.Length ? (int)left : buffer.Length; var read = stream.Read(buffer, 0, toRead); if (read == 0) { throw new EndOfStreamException("The stream ended unexpectedly"); } Proxy.git_odb_stream_write(odbStream, buffer, read); totalRead += read; } var id = Proxy.git_odb_stream_finalize_write(odbStream); return repo.Lookup<Blob>(id); } } /// <summary> /// Inserts a <see cref="Tree"/> into the object database, created from a <see cref="TreeDefinition"/>. /// </summary> /// <param name="treeDefinition">The <see cref="TreeDefinition"/>.</param> /// <returns>The created <see cref="Tree"/>.</returns> public virtual Tree CreateTree(TreeDefinition treeDefinition) { Ensure.ArgumentNotNull(treeDefinition, "treeDefinition"); return treeDefinition.Build(repo); } /// <summary> /// Inserts a <see cref="Tree"/> into the object database, created from the <see cref="Index"/>. /// <para> /// It recursively creates tree objects for each of the subtrees stored in the index, but only returns the root tree. /// </para> /// <para> /// The index must be fully merged. /// </para> /// </summary> /// <param name="index">The <see cref="Index"/>.</param> /// <returns>The created <see cref="Tree"/>. This can be used e.g. to create a <see cref="Commit"/>.</returns> public virtual Tree CreateTree(Index index) { Ensure.ArgumentNotNull(index, "index"); var treeId = Proxy.git_index_write_tree(index.Handle); return this.repo.Lookup<Tree>(treeId); } /// <summary> /// Inserts a <see cref="Commit"/> into the object database, referencing an existing <see cref="Tree"/>. /// <para> /// Prettifing the message includes: /// * Removing empty lines from the beginning and end. /// * Removing trailing spaces from every line. /// * Turning multiple consecutive empty lines between paragraphs into just one empty line. /// * Ensuring the commit message ends with a newline. /// * Removing every line starting with "#". /// </para> /// </summary> /// <param name="author">The <see cref="Signature"/> of who made the change.</param> /// <param name="committer">The <see cref="Signature"/> of who added the change to the repository.</param> /// <param name="message">The description of why a change was made to the repository.</param> /// <param name="tree">The <see cref="Tree"/> of the <see cref="Commit"/> to be created.</param> /// <param name="parents">The parents of the <see cref="Commit"/> to be created.</param> /// <param name="prettifyMessage">True to prettify the message, or false to leave it as is.</param> /// <returns>The created <see cref="Commit"/>.</returns> public virtual Commit CreateCommit(Signature author, Signature committer, string message, Tree tree, IEnumerable<Commit> parents, bool prettifyMessage) { return CreateCommit(author, committer, message, tree, parents, prettifyMessage, null); } /// <summary> /// Inserts a <see cref="Commit"/> into the object database, referencing an existing <see cref="Tree"/>. /// <para> /// Prettifing the message includes: /// * Removing empty lines from the beginning and end. /// * Removing trailing spaces from every line. /// * Turning multiple consecutive empty lines between paragraphs into just one empty line. /// * Ensuring the commit message ends with a newline. /// * Removing every line starting with the <paramref name="commentChar"/>. /// </para> /// </summary> /// <param name="author">The <see cref="Signature"/> of who made the change.</param> /// <param name="committer">The <see cref="Signature"/> of who added the change to the repository.</param> /// <param name="message">The description of why a change was made to the repository.</param> /// <param name="tree">The <see cref="Tree"/> of the <see cref="Commit"/> to be created.</param> /// <param name="parents">The parents of the <see cref="Commit"/> to be created.</param> /// <param name="prettifyMessage">True to prettify the message, or false to leave it as is.</param> /// <param name="commentChar">When non null, lines starting with this character will be stripped if prettifyMessage is true.</param> /// <returns>The created <see cref="Commit"/>.</returns> public virtual Commit CreateCommit(Signature author, Signature committer, string message, Tree tree, IEnumerable<Commit> parents, bool prettifyMessage, char? commentChar) { Ensure.ArgumentNotNull(message, "message"); Ensure.ArgumentDoesNotContainZeroByte(message, "message"); Ensure.ArgumentNotNull(author, "author"); Ensure.ArgumentNotNull(committer, "committer"); Ensure.ArgumentNotNull(tree, "tree"); Ensure.ArgumentNotNull(parents, "parents"); if (prettifyMessage) { message = Proxy.git_message_prettify(message, commentChar); } GitOid[] parentIds = parents.Select(p => p.Id.Oid).ToArray(); ObjectId commitId = Proxy.git_commit_create(repo.Handle, null, author, committer, message, tree, parentIds); return repo.Lookup<Commit>(commitId); } /// <summary> /// Inserts a <see cref="TagAnnotation"/> into the object database, pointing to a specific <see cref="GitObject"/>. /// </summary> /// <param name="name">The name.</param> /// <param name="target">The <see cref="GitObject"/> being pointed at.</param> /// <param name="tagger">The tagger.</param> /// <param name="message">The message.</param> /// <returns>The created <see cref="TagAnnotation"/>.</returns> public virtual TagAnnotation CreateTagAnnotation(string name, GitObject target, Signature tagger, string message) { Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(message, "message"); Ensure.ArgumentNotNull(target, "target"); Ensure.ArgumentNotNull(tagger, "tagger"); Ensure.ArgumentDoesNotContainZeroByte(name, "name"); Ensure.ArgumentDoesNotContainZeroByte(message, "message"); string prettifiedMessage = Proxy.git_message_prettify(message, null); ObjectId tagId = Proxy.git_tag_annotation_create(repo.Handle, name, target, tagger, prettifiedMessage); return repo.Lookup<TagAnnotation>(tagId); } /// <summary> /// Archive the given commit. /// </summary> /// <param name="commit">The commit.</param> /// <param name="archiver">The archiver to use.</param> public virtual void Archive(Commit commit, ArchiverBase archiver) { Ensure.ArgumentNotNull(commit, "commit"); Ensure.ArgumentNotNull(archiver, "archiver"); archiver.OrchestrateArchiving(commit.Tree, commit.Id, commit.Committer.When); } /// <summary> /// Archive the given tree. /// </summary> /// <param name="tree">The tree.</param> /// <param name="archiver">The archiver to use.</param> public virtual void Archive(Tree tree, ArchiverBase archiver) { Ensure.ArgumentNotNull(tree, "tree"); Ensure.ArgumentNotNull(archiver, "archiver"); archiver.OrchestrateArchiving(tree, null, DateTimeOffset.UtcNow); } /// <summary> /// Returns the merge base (best common ancestor) of the given commits /// and the distance between each of these commits and this base. /// </summary> /// <param name="one">The <see cref="Commit"/> being used as a reference.</param> /// <param name="another">The <see cref="Commit"/> being compared against <paramref name="one"/>.</param> /// <returns>A instance of <see cref="HistoryDivergence"/>.</returns> public virtual HistoryDivergence CalculateHistoryDivergence(Commit one, Commit another) { Ensure.ArgumentNotNull(one, "one"); Ensure.ArgumentNotNull(another, "another"); return new HistoryDivergence(repo, one, another); } /// <summary> /// Calculates the current shortest abbreviated <see cref="ObjectId"/> /// string representation for a <see cref="GitObject"/>. /// </summary> /// <param name="gitObject">The <see cref="GitObject"/> which identifier should be shortened.</param> /// <returns>A short string representation of the <see cref="ObjectId"/>.</returns> public virtual string ShortenObjectId(GitObject gitObject) { var shortSha = Proxy.git_object_short_id(repo.Handle, gitObject.Id); return shortSha; } /// <summary> /// Calculates the current shortest abbreviated <see cref="ObjectId"/> /// string representation for a <see cref="GitObject"/>. /// </summary> /// <param name="gitObject">The <see cref="GitObject"/> which identifier should be shortened.</param> /// <param name="minLength">Minimum length of the shortened representation.</param> /// <returns>A short string representation of the <see cref="ObjectId"/>.</returns> public virtual string ShortenObjectId(GitObject gitObject, int minLength) { if (minLength <= 0 || minLength > ObjectId.HexSize) { throw new ArgumentOutOfRangeException("minLength", minLength, string.Format("Expected value should be greater than zero and less than or equal to {0}.", ObjectId.HexSize)); } string shortSha = Proxy.git_object_short_id(repo.Handle, gitObject.Id); if (minLength <= shortSha.Length) { return shortSha; } return gitObject.Sha.Substring(0, minLength); } /// <summary> /// Returns whether merging <paramref name="one"/> into <paramref name="another"/> /// would result in merge conflicts. /// </summary> /// <param name="one">The commit wrapping the base tree to merge into.</param> /// <param name="another">The commit wrapping the tree to merge into <paramref name="one"/>.</param> /// <returns>True if the merge does not result in a conflict, false otherwise.</returns> public virtual bool CanMergeWithoutConflict(Commit one, Commit another) { Ensure.ArgumentNotNull(one, "one"); Ensure.ArgumentNotNull(another, "another"); var result = repo.ObjectDatabase.MergeCommits(one, another, null); return (result.Status == MergeTreeStatus.Succeeded); } /// <summary> /// Find the best possible merge base given two <see cref="Commit"/>s. /// </summary> /// <param name="first">The first <see cref="Commit"/>.</param> /// <param name="second">The second <see cref="Commit"/>.</param> /// <returns>The merge base or null if none found.</returns> public virtual Commit FindMergeBase(Commit first, Commit second) { Ensure.ArgumentNotNull(first, "first"); Ensure.ArgumentNotNull(second, "second"); return FindMergeBase(new[] { first, second }, MergeBaseFindingStrategy.Standard); } /// <summary> /// Find the best possible merge base given two or more <see cref="Commit"/> according to the <see cref="MergeBaseFindingStrategy"/>. /// </summary> /// <param name="commits">The <see cref="Commit"/>s for which to find the merge base.</param> /// <param name="strategy">The strategy to leverage in order to find the merge base.</param> /// <returns>The merge base or null if none found.</returns> public virtual Commit FindMergeBase(IEnumerable<Commit> commits, MergeBaseFindingStrategy strategy) { Ensure.ArgumentNotNull(commits, "commits"); ObjectId id; List<GitOid> ids = new List<GitOid>(8); int count = 0; foreach (var commit in commits) { if (commit == null) { throw new ArgumentException("Enumerable contains null at position: " + count.ToString(CultureInfo.InvariantCulture), "commits"); } ids.Add(commit.Id.Oid); count++; } if (count < 2) { throw new ArgumentException("The enumerable must contains at least two commits.", "commits"); } switch (strategy) { case MergeBaseFindingStrategy.Standard: id = Proxy.git_merge_base_many(repo.Handle, ids.ToArray()); break; case MergeBaseFindingStrategy.Octopus: id = Proxy.git_merge_base_octopus(repo.Handle, ids.ToArray()); break; default: throw new ArgumentException("", "strategy"); } return id == null ? null : repo.Lookup<Commit>(id); } /// <summary> /// Perform a three-way merge of two commits, looking up their /// commit ancestor. The returned index will contain the results /// of the merge and can be examined for conflicts. The returned /// index must be disposed. /// </summary> /// <param name="ours">The first tree</param> /// <param name="theirs">The second tree</param> /// <param name="options">The <see cref="MergeTreeOptions"/> controlling the merge</param> /// <returns>The <see cref="Index"/> containing the merged trees and any conflicts</returns> public virtual MergeTreeResult MergeCommits(Commit ours, Commit theirs, MergeTreeOptions options) { Ensure.ArgumentNotNull(ours, "ours"); Ensure.ArgumentNotNull(theirs, "theirs"); options = options ?? new MergeTreeOptions(); var mergeOptions = new GitMergeOpts { Version = 1, MergeFileFavorFlags = options.MergeFileFavor, MergeTreeFlags = options.FindRenames ? GitMergeTreeFlags.GIT_MERGE_TREE_FIND_RENAMES : GitMergeTreeFlags.GIT_MERGE_TREE_NORMAL, RenameThreshold = (uint)options.RenameThreshold, TargetLimit = (uint)options.TargetLimit, }; using (var oneHandle = Proxy.git_object_lookup(repo.Handle, ours.Id, GitObjectType.Commit)) using (var twoHandle = Proxy.git_object_lookup(repo.Handle, theirs.Id, GitObjectType.Commit)) using (var indexHandle = Proxy.git_merge_commits(repo.Handle, oneHandle, twoHandle, mergeOptions)) { MergeTreeResult mergeResult; if (Proxy.git_index_has_conflicts(indexHandle)) { List<Conflict> conflicts = new List<Conflict>(); Conflict conflict; using (ConflictIteratorSafeHandle iterator = Proxy.git_index_conflict_iterator_new(indexHandle)) { while ((conflict = Proxy.git_index_conflict_next(iterator)) != null) { conflicts.Add(conflict); } } mergeResult = new MergeTreeResult(conflicts); } else { var treeId = Proxy.git_index_write_tree_to(indexHandle, repo.Handle); mergeResult = new MergeTreeResult(this.repo.Lookup<Tree>(treeId)); } return mergeResult; } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using System.Drawing; using mshtml; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.BlogClient; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Extensibility.ImageEditing; using OpenLiveWriter.Mshtml; using OpenLiveWriter.Api; namespace OpenLiveWriter.PostEditor.PostHtmlEditing.ImageEditing.Decorators { /// <summary> /// Summary description for Decorator. /// </summary> public class HtmlImageTargetDecorator : IImageDecorator, IImageDecoratorDefaultSettingsCustomizer { public const string Id = "ImageTarget"; public HtmlImageTargetDecorator() { } public void Decorate(ImageDecoratorContext context) { HtmlImageTargetDecoratorSettings settings = new HtmlImageTargetDecoratorSettings(context.Settings, context.ImgElement); if(context.InvocationSource == ImageDecoratorInvocationSource.InitialInsert || context.InvocationSource == ImageDecoratorInvocationSource.Reset) { //set the default link target type. //settings.LinkTarget = settings.DefaultLinkTarget; //the default size is a scaled version of the image based on the default inline size constraints. Size defaultSizeBounds = settings.DefaultTargetBoundsSize; settings.BaseSize = context.Image.Size; //calculate the base image size to scale from. If the image is rotated 90 degrees, then switch the height/width Size baseImageSize = context.Image.Size; if(ImageUtils.IsRotated90(context.ImageRotation)) baseImageSize = new Size(baseImageSize.Height, baseImageSize.Width); //calculate and set the scaled default size using the defaultSizeBounds //Note: if the image dimensions are smaller than the default, don't scale that dimension (bug 419446) Size defaultSize = ImageUtils.GetScaledImageSize(Math.Min(baseImageSize.Width, defaultSizeBounds.Width), Math.Min(baseImageSize.Height, defaultSizeBounds.Height), baseImageSize); settings.ImageSize = defaultSize; settings.ImageSizeName = settings.DefaultTargetBoundsSizeName; } else if (settings.BaseSizeChanged(context.Image) && context.ImageEmbedType == ImageEmbedType.Linked) { Size newBaseSize = context.Image.Size; settings.ImageSize = HtmlImageResizeDecorator.AdjustImageSizeForNewBaseSize(false, settings, newBaseSize, context.ImageRotation, context); settings.BaseSize = newBaseSize; } if (context.InvocationSource == ImageDecoratorInvocationSource.Reset) { //set the initial link options settings.LinkOptions = settings.DefaultLinkOptions; } //this decorator only applies to linked images. if(context.ImageEmbedType == ImageEmbedType.Linked) { Size imageSize = settings.ImageSize; //resize the image and update the image used by the context. Bitmap bitmap = HtmlImageResizeDecorator.ResizeImage(context.Image, imageSize, context.ImageRotation); context.Image = bitmap; if(settings.ImageSize != bitmap.Size) settings.ImageSize = bitmap.Size; } } public ImageDecoratorEditor CreateEditor(CommandManager commandManager) { return new HtmlImageTargetEditor(); } #region IImageDecoratorDefaultSettingsCustomizer Members void IImageDecoratorDefaultSettingsCustomizer.CustomizeDefaultSettingsBeforeSave(ImageDecoratorEditorContext context, IProperties defaultSettings) { HtmlImageTargetDecoratorSettings defaultTargetSettings = new HtmlImageTargetDecoratorSettings(defaultSettings, context.ImgElement); HtmlImageTargetDecoratorSettings targetSettings = new HtmlImageTargetDecoratorSettings(context.Settings, context.ImgElement); //save a reasonable value for the default link target. //If the link target is a URL, default to NONE since the user clearly doesn't want to preserve //the URL currently associated with the image for all future images if(defaultTargetSettings.LinkTarget != LinkTargetType.URL) defaultTargetSettings.DefaultLinkTarget = defaultTargetSettings.LinkTarget; else defaultTargetSettings.DefaultLinkTarget = LinkTargetType.NONE; defaultTargetSettings.DefaultLinkOptions = targetSettings.LinkOptions; defaultTargetSettings.DefaultTargetBoundsSizeName = targetSettings.ImageSizeName; defaultTargetSettings.DefaultTargetBoundsSize = targetSettings.ImageSize; } #endregion } internal class HtmlImageTargetDecoratorSettings : IResizeDecoratorSettings { private const string WIDTH = "ImageWidth"; private const string HEIGHT = "ImageHeight"; private const string BOUNDS = "ImageBoundsSize"; private const string BASE_WIDTH = "BaseWidth"; private const string BASE_HEIGHT = "BaseHeight"; private const string TARGET_TYPE = "TargetType"; private const string DEFAULT_TARGET_TYPE = "DefaultTargetType"; private const string DEFAULT_OPEN_NEW_WINDOW = "DefaultOpenNewWindow"; private const string DEFAULT_TARGET_WIDTH = "DefaultTargetWidth"; private const string DEFAULT_TARGET_HEIGHT = "DefaultTargetHeight"; private const string DEFAULT_TARGET_SIZE_NAME = "DefaultTargetSizeName"; private const string DHTML_IMAGE_VIEWER = "DhtmlImageViewer"; private const string DEFAULT_USE_IMAGE_VIEWER = "DefaultUseImageViewer"; private const string DEFAULT_IMAGE_VIEWER_GROUP = "DefaultImageViewerGroup"; // Anything in this list will be removed from the properties when the image reference is fixed // because ti is being synced with a posted edited outside of writer. public static readonly string[] ImageReferenceFixedStaleProperties = new string[1] { TARGET_TYPE }; private readonly IProperties Settings; private readonly IHTMLElement ImgElement; public HtmlImageTargetDecoratorSettings(IProperties settings, IHTMLElement imgElement) { Settings = settings; ImgElement = imgElement; } public Size ImageSize { get { IHTMLImgElement imgElement = (IHTMLImgElement)ImgElement; int width = Settings.GetInt(WIDTH, imgElement.width); int height = Settings.GetInt(HEIGHT, imgElement.height); return new Size(width, height); } set { Settings.SetInt(WIDTH, value.Width); Settings.SetInt(HEIGHT, value.Height); } } /// <summary> /// The maximum bounds that were allowed when determining the current image size. /// This value is used to decide what the best initial size should be for the image if the current /// size is saved as the default size. Rather than forcing all future images to be exactly the current /// size, the named size associated with the bounds can be used for more flexibility. /// </summary> public ImageSizeName ImageSizeName { get { ImageSizeName bounds = (ImageSizeName)ImageSizeName.Parse( typeof(ImageSizeName), Settings.GetString(BOUNDS, ImageSizeName.Full.ToString())); return bounds; } set { Settings.SetString(BOUNDS, value.ToString()); } } /// <summary> /// Defines the type of target for the image. /// </summary> public LinkTargetType LinkTarget { get { LinkTargetType linkTargetType = uninitializedDefaultLinkTarget; string linkTarget = Settings.GetString(TARGET_TYPE, null); if(linkTarget != null) { linkTargetType = (LinkTargetType)LinkTargetType.Parse(typeof(LinkTargetType), linkTarget); } else { //The link target type is completely uninitialized (no one has set it, and no image decorator defaults have been saved). //Examine the link values from the DOM to figure out the correct value for this property. //If the image is surrounded by an anchor to a remote image, then set the target type to link. //If the image is not surrounded by an anchor then set the target type to None. //Else leave as the default (which is a local image). string linkTargetUrl = LinkTargetUrl; if(linkTargetUrl == null) linkTargetType = LinkTargetType.NONE; else if(!UrlHelper.IsFileUrl(linkTargetUrl)) { linkTargetType = LinkTargetType.URL; } } return linkTargetType; } set { Settings.SetString(TARGET_TYPE, value.ToString()); } } public LinkTargetType DefaultLinkTarget { get { string linkTarget = Settings.GetString(DEFAULT_TARGET_TYPE, uninitializedDefaultLinkTarget.ToString()); LinkTargetType linkTargetType = (LinkTargetType)LinkTargetType.Parse(typeof(LinkTargetType), linkTarget); return linkTargetType; } set { Settings.SetString(DEFAULT_TARGET_TYPE, value.ToString()); } } private readonly LinkTargetType uninitializedDefaultLinkTarget = LinkTargetType.IMAGE; internal Size DefaultTargetBoundsSize { get { ImageSizeName boundsSize = DefaultTargetBoundsSizeName; Size defaultBoundsSize; if(boundsSize != ImageSizeName.Custom) defaultBoundsSize = ImageSizeHelper.GetSizeConstraints(boundsSize); else { int defaultWidth = Settings.GetInt(DEFAULT_TARGET_WIDTH, 300); int defaultHeight = Settings.GetInt(DEFAULT_TARGET_HEIGHT, 300); defaultBoundsSize = new Size(defaultWidth, defaultHeight); } return defaultBoundsSize; } set { Settings.SetInt(DEFAULT_TARGET_WIDTH, value.Width); Settings.SetInt(DEFAULT_TARGET_HEIGHT, value.Height); } } internal ImageSizeName DefaultTargetBoundsSizeName { get { ImageSizeName bounds = (ImageSizeName)ImageSizeName.Parse( typeof(ImageSizeName), Settings.GetString(DEFAULT_TARGET_SIZE_NAME, ImageSizeName.Large.ToString())); return bounds; } set { Settings.SetString(DEFAULT_TARGET_SIZE_NAME, value.ToString()); } } Size IResizeDecoratorSettings.DefaultBoundsSize { get { return DefaultTargetBoundsSize; } } ImageSizeName IResizeDecoratorSettings.DefaultBoundsSizeName { get { return DefaultTargetBoundsSizeName; } } /// <summary> /// Get/Set the url for URL-based link targets. /// </summary> public string LinkTargetUrl { get { IHTMLElement anchorElement = GetAnchorElement(); if(anchorElement != null) return (string)anchorElement.getAttribute("href", 2); return null; } set { UpdateImageLink(value, ImgElement, DefaultLinkOptions); } } public void UpdateImageLinkOptions(string title, string rel, bool newWindow) { IHTMLElement anchorElement = GetAnchorElement(); IHTMLAnchorElement htmlAnchorElement = (anchorElement as IHTMLAnchorElement); if (htmlAnchorElement != null) { //set the default target attribute for the new element string target = newWindow ? "_blank" : null; if(htmlAnchorElement.target != target) //don't set the target to null if its already null (avoids adding empty target attr) htmlAnchorElement.target = target ; if (title != String.Empty) { anchorElement.setAttribute("title", title, 0); } else { anchorElement.removeAttribute("title", 0); } if (rel != String.Empty) { anchorElement.setAttribute("rel", rel, 0); } else { anchorElement.removeAttribute("rel", 0); } } } public string LinkTitle { get { IHTMLElement anchorElement = GetAnchorElement(); if (anchorElement != null) { if ( anchorElement.title != null ) return anchorElement.title ; else return String.Empty ; } else { return String.Empty ; } } } public string LinkRel { get { IHTMLElement anchorElement = GetAnchorElement(); IHTMLAnchorElement htmlAnchorElement = (anchorElement as IHTMLAnchorElement); if (htmlAnchorElement != null) { if ( htmlAnchorElement.rel != null ) return htmlAnchorElement.rel ; else return String.Empty ; } else { return String.Empty ; } } } public ILinkOptions LinkOptions { get { bool openInNewWindow = false; bool useImageViewer = false; string imageViewerGroupName = null; IHTMLElement anchorElement = GetAnchorElement(); if(anchorElement != null) { IHTMLAnchorElement htmlAnchorElement = (IHTMLAnchorElement)anchorElement; openInNewWindow = htmlAnchorElement.target != null; ImageViewer viewer = DhtmlImageViewers.GetImageViewer(DhtmlImageViewer); if (viewer != null) viewer.Detect(htmlAnchorElement, ref useImageViewer, ref imageViewerGroupName); } return new LinkOptions(openInNewWindow, useImageViewer, imageViewerGroupName); } set { IHTMLElement anchorElement = GetAnchorElement(); if(anchorElement != null) { string target = value.ShowInNewWindow ? "_blank" : null; IHTMLAnchorElement htmlAnchorElement = (anchorElement as IHTMLAnchorElement); if (htmlAnchorElement != null) { if (target == null) ((IHTMLElement) htmlAnchorElement).removeAttribute("target", 0); else htmlAnchorElement.target = target; } ImageViewer viewer = DhtmlImageViewers.GetImageViewer(DhtmlImageViewer); if (viewer != null) { if (value.UseImageViewer) viewer.Apply(htmlAnchorElement, value.ImageViewerGroupName); else viewer.Remove(htmlAnchorElement); } //save the value as the default for this image so that we can properly restore the options //if the user toggles the target and causes the anchor to be removed-then-added DefaultLinkOptions = value; } } } public ILinkOptions DefaultLinkOptions { get { bool openInNewWindow = Settings.GetBoolean(DEFAULT_OPEN_NEW_WINDOW, false); bool useImageViewer = Settings.GetBoolean(DEFAULT_USE_IMAGE_VIEWER, true); string groupName = Settings.GetString(DEFAULT_IMAGE_VIEWER_GROUP, null); return new LinkOptions(openInNewWindow, useImageViewer, groupName); } set { Settings.SetBoolean(DEFAULT_OPEN_NEW_WINDOW, value.ShowInNewWindow); Settings.SetBoolean(DEFAULT_USE_IMAGE_VIEWER, value.UseImageViewer); Settings.SetString(DEFAULT_IMAGE_VIEWER_GROUP, value.ImageViewerGroupName); } } // The base size is used to quickly determine whether the image has // been cropped since the last time the default bounds were calculated. public Size? BaseSize { get { if (!Settings.Contains(BASE_WIDTH) || !Settings.Contains(BASE_HEIGHT)) return null; try { return new Size(Settings.GetInt(BASE_WIDTH, -1), Settings.GetInt(BASE_HEIGHT, -1)); } catch { return null; } } set { if (value == null) { Settings.Remove(BASE_WIDTH); Settings.Remove(BASE_HEIGHT); } else { Settings.SetInt(BASE_WIDTH, value.Value.Width); Settings.SetInt(BASE_HEIGHT, value.Value.Height); } } } public string DhtmlImageViewer { get { return Settings.GetString(DHTML_IMAGE_VIEWER, null); } set { if (value != DhtmlImageViewer) { // Unload the existing viewer, if any exists ImageViewer viewer = DhtmlImageViewers.GetImageViewer(DhtmlImageViewer); if (viewer != null) { IHTMLAnchorElement anchor = GetAnchorElement() as IHTMLAnchorElement; if (anchor != null) viewer.Remove(anchor); } Settings.SetString(DHTML_IMAGE_VIEWER, value); } } } public bool BaseSizeChanged(Bitmap image) { Size? baseSize = BaseSize; if (baseSize == null) return true; return !baseSize.Equals(image.Size); } internal IHTMLElement GetAnchorElement() { IHTMLElement parentElement = ImgElement.parentElement; while(parentElement != null) { if(parentElement is IHTMLAnchorElement) return parentElement; parentElement = parentElement.parentElement; } return null; } private void UpdateImageLink(string href, IHTMLElement ImgElement, ILinkOptions defaultOptions) { MshtmlMarkupServices markupServices = new MshtmlMarkupServices((IMarkupServicesRaw)ImgElement.document); IHTMLElement parentElement = ImgElement.parentElement; if(!(parentElement is IHTMLAnchorElement)) { parentElement = markupServices.CreateElement(_ELEMENT_TAG_ID.TAGID_A, null); MarkupRange range = markupServices.CreateMarkupRange(); range.MoveToElement(ImgElement, true); markupServices.InsertElement(parentElement, range.Start, range.End); //set the default target attribute for the new element string target = defaultOptions.ShowInNewWindow ? "_blank" : null; IHTMLAnchorElement htmlAnchorElement = (parentElement as IHTMLAnchorElement); if(htmlAnchorElement.target != target) //don't set the target to null if its already null (avoids adding empty target attr) htmlAnchorElement.target = target ; ImageViewer viewer = DhtmlImageViewers.GetImageViewer(DhtmlImageViewer); if (viewer != null) { if (defaultOptions.UseImageViewer) viewer.Apply(htmlAnchorElement, defaultOptions.ImageViewerGroupName); } } parentElement.setAttribute("href", href, 0); } public void RemoveImageLink() { IHTMLElement parentElement = ImgElement.parentElement; if(parentElement is IHTMLAnchorElement) { ((IHTMLDOMNode)parentElement).removeNode(false); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; public class VHTimeDemo : MonoBehaviour { #region Constants const string TimeDemoCommand = "time_demo"; const string TimeDemoUrl = "http://uperf/AddTimeDemo.php"; const int NumAvgFpsEntries = 50; struct TimeData { public float time; public float curfps; public float avgfps; public TimeData(float _time, float _curfps, float _avgfps) { time = _time; curfps = _curfps; avgfps = _avgfps; } } #endregion #region Variables public FpsCounter m_FpsCounter; public string m_TimeDemoName = "timeDemo01"; public string m_ProjectName = "Unnamed Project"; public float m_FpsSamplingRate = 0.2f; public float m_DelayWhenStarted = 0; public GameObject m_CallbackFunctionContainer; public string m_OnStartFuncCallbackName = ""; public string m_OnFinishFuncCallbackName = ""; Vector2 m_TimeDemoStartEndFrames = new Vector2(); float m_StartTime = 0; float m_TimeDemoLength = 0; // in seconds List<TimeData> m_TimeData = new List<TimeData>(); LinkedList<float> m_AvgFpsTracker = new LinkedList<float>(); string m_sceneName; string m_computerName; System.DateTime m_dateOfDemo; #endregion #region Properties public float TimeDemoLength { get { return m_TimeDemoLength; } set { m_TimeDemoLength = value; } } #endregion #region Functions // Use this for initialization void Start() { if (m_FpsCounter == null) { Debug.LogError("VHTimeDemo needs FpsCounter"); } m_sceneName = VHUtils.SceneManagerActiveSceneName(); if (string.IsNullOrEmpty(m_sceneName)) { m_sceneName = "Unnamed Scene"; } m_computerName = System.Environment.MachineName; } public void StartTimeDemo(bool exitAfterFinished) { StartTimeDemo(m_ProjectName, m_TimeDemoName, exitAfterFinished); } public void StartTimeDemo(string projectName, string timeDemoName, bool exitAfterFinished) { m_TimeDemoLength = 0; m_ProjectName = projectName; m_TimeDemoName = timeDemoName; if (!string.IsNullOrEmpty(m_OnStartFuncCallbackName)) { m_CallbackFunctionContainer.SendMessage(m_OnStartFuncCallbackName, SendMessageOptions.RequireReceiver); } m_TimeDemoStartEndFrames.x = Time.frameCount; m_StartTime = Time.timeSinceLevelLoad; // record fps StartCoroutine(RecordFPS()); } public void StopTimeDemo() { m_TimeDemoStartEndFrames.y = Time.frameCount; m_dateOfDemo = System.DateTime.Now; m_TimeDemoLength = Time.timeSinceLevelLoad - m_StartTime; Debug.Log("m_TimeDemoLength: " + m_TimeDemoLength); StopAllCoroutines(); StopCoroutine("RecordFPS"); if (!string.IsNullOrEmpty(m_OnFinishFuncCallbackName)) { m_CallbackFunctionContainer.SendMessage(m_OnFinishFuncCallbackName, SendMessageOptions.RequireReceiver); } StartCoroutine(UploadTimeDemoData(TimeDemoUrl, false)); } IEnumerator RecordFPS() { yield return new WaitForSeconds(m_DelayWhenStarted); m_TimeData.Clear(); float startTime = Time.timeSinceLevelLoad; while (true) { if (m_FpsCounter.Fps == 0) { yield return new WaitForSeconds(m_FpsSamplingRate); continue; } if (m_AvgFpsTracker.Count >= NumAvgFpsEntries) { m_AvgFpsTracker.RemoveFirst(); } m_AvgFpsTracker.AddLast(m_FpsCounter.Fps); m_TimeData.Add(new TimeData(Time.timeSinceLevelLoad - startTime, m_FpsCounter.Fps, GetSamplingAverageFps())); yield return new WaitForSeconds(m_FpsSamplingRate); } } float GetSamplingAverageFps() { float average = 0; foreach (float data in m_AvgFpsTracker) { average += data; } if (average == 0) { average = m_FpsCounter.Fps; } return average / Mathf.Max(m_AvgFpsTracker.Count, 1); } float GetTimeDemoAverageFps() { float average = 0; for (int i = 0; i < m_TimeData.Count; i++) { average += m_TimeData[i].avgfps; } if (average == 0) { average = m_FpsCounter.Fps; } return average / Mathf.Max((float)m_TimeData.Count, 1); } float GetMaxFps() { if (m_TimeData.Count == 0) { return 0; } float retVal = m_TimeData[0].curfps; for (int i = 1; i < m_TimeData.Count; i++) { if (retVal < m_TimeData[i].curfps) retVal = m_TimeData[i].curfps; } return retVal; } float GetMinFps() { if (m_TimeData.Count == 0) { return 0; } float retVal = m_TimeData[0].curfps; for (int i = 1; i < m_TimeData.Count; i++) { if (retVal > m_TimeData[i].curfps) retVal = m_TimeData[i].curfps; } return retVal; } string TimeDataAsString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < m_TimeData.Count; i++) { builder.Append(string.Format("{0},{1},{2}|", m_TimeData[i].time, m_TimeData[i].curfps, m_TimeData[i].avgfps)); } builder.Remove(builder.Length - 1, 1); return builder.ToString(); } IEnumerator UploadTimeDemoData(string dbUrl, bool exitApplication) { WWWForm form = new WWWForm(); form.AddField("project_name", m_ProjectName); form.AddField("scene_name", m_sceneName); form.AddField("computer_name", m_computerName); form.AddField("timedemo_name", m_TimeDemoName); form.AddField("timedemo_length", m_TimeDemoLength.ToString("F2")); form.AddField("max_fps", GetMaxFps().ToString("F2")); form.AddField("min_fps", GetMinFps().ToString("F2")); form.AddField("avg_fps", GetTimeDemoAverageFps().ToString("F2")); form.AddField("timedata", TimeDataAsString()); form.AddField("date", m_dateOfDemo.ToString("yyyy-MM-dd HH:mm:ss")); // i.e. 2012-07-06 11:45:26 form.AddField("screen_width", Screen.width.ToString()); form.AddField("screen_height", Screen.height.ToString()); form.AddField("fullscreen", Screen.fullScreen.ToString()); form.AddField("quality_level", QualitySettings.names[QualitySettings.GetQualityLevel()]); Debug.Log(string.Format("m_ProjectName {0} m_sceneName {1} m_computerName {2} m_TimeDemoName {3} m_TimeDemoLength {4} max_fps {5} min_fps {6} avg_fps {7} date {8}", m_ProjectName, m_sceneName, m_computerName, m_TimeDemoName, m_TimeDemoLength.ToString("F2"), GetMaxFps().ToString("F2"), GetMinFps().ToString("F2"), GetTimeDemoAverageFps().ToString("F2"), m_dateOfDemo.ToString("yyyy-MM-dd HH:mm:ss"))); WWW www = new WWW(dbUrl, form); if (VHUtils.IsEditor() || !VHUtils.IsWebGL()) { // when uploading large data chunks at the same time, uncomment this to prevent overloading the db while (!www.isDone) {} } else { yield return www; } if (www.error != null) { Debug.Log(www.error); } else { Debug.Log("Successfully uploaded timedemo data: " + www.text); } if (exitApplication) { VHUtils.ApplicationQuit(); } yield break; } public void UploadTestData() { // modify these values to customize the data sent to the database // this is for uploaded large amounts of dummy test data to populate the database // test info that gets uploaded m_ProjectName = "TimeDemoTest"; m_sceneName = "Scene1"; m_computerName = "machine1"; m_TimeDemoName = "TimeDemoScene9"; m_TimeDemoLength = 10; m_dateOfDemo = new System.DateTime(2012, 8, 15); // fps data that gets uploaded float lengthSeconds = 10; float interval = 0.1f; float fpsMax = 60; float fpsMin = 50; float fpsDecay = 0.1f; float fpsMinSeparation = 10; for (int day = 0; day < 30; day++) { float curTime = 0; m_TimeData = new List<TimeData>(); const int numFpsEntries = 50; float[] averageFpsArray = new float[numFpsEntries]; float averageSum = 0; while (curTime <= lengthSeconds) { float fps = Random.Range(fpsMin, fpsMax); if (m_TimeData.Count == 0) { for (int init = 0; init < numFpsEntries; init++) { averageFpsArray[init] = fps; averageSum += fps; } } int i = m_TimeData.Count % numFpsEntries; averageSum -= averageFpsArray[i]; averageFpsArray[i] = fps; averageSum += fps; float averageFps = averageSum / numFpsEntries; m_TimeData.Add(new TimeData(curTime, fps, averageFps)); curTime += interval; } StartCoroutine(UploadTimeDemoData(TimeDemoUrl, false)); // get slower each day fpsMax -= fpsDecay; fpsMin = fpsMax - fpsMinSeparation; m_dateOfDemo = m_dateOfDemo.AddDays(1); } } #endregion } /* [RequireComponent(typeof(VHWayPointNavigator))] public class VHTimeDemo : MonoBehaviour { #region Constants const string TimeDemoCommand = "time_demo"; const float AmountToTurnAtWP = 360; // degrees const string TimeDemoUrl = "http://uperf/AddTimeDemo.php"; const int NumAvgFpsEntries = 50; struct TimeData { public float time; public float curfps; public float avgfps; public TimeData(float _time, float _curfps, float _avgfps) { time = _time; curfps = _curfps; avgfps = _avgfps; } } #endregion #region Variables public FpsCounter m_FpsCounter; public string m_TimeDemoName = "timeDemo01"; public string m_PerformanceLogName = "vhPerformanceLog.log"; public string m_ProjectName = "Unnamed Project"; public bool m_TurnWhenReachWP = true; float m_TurnSpeed = 180; public float m_TimeDemoLength = 10; // in seconds public float m_FpsSamplingRate = 0.1f; public float m_DelayWhenStarted = 0; public GameObject m_CallbackFunctionContainer; public string m_OnStartFuncCallbackName = ""; public string m_OnFinishFuncCallbackName = ""; // private VHWayPointNavigator m_WPNavigator; //VHBinaryParser m_BinaryParser = new VHBinaryParser(); Vector2 m_TimeDemoStartEndFrames = new Vector2(); float m_StartTime = 0; List<TimeData> m_TimeData = new List<TimeData>(); //List<float> m_Fps = new List<float>(); LinkedList<float> m_AvgFpsTracker = new LinkedList<float>(); bool m_ExitAfterFinished = false; string m_sceneName; string m_computerName; System.DateTime m_dateOfDemo; bool m_LookAtTargetWayPoint; #endregion #region Properties public float TimeDemoLength { get { return m_TimeDemoLength; } set { m_TimeDemoLength = value; } } #endregion #region Functions // Use this for initialization //public override void VHStart() void Start() { m_WPNavigator = (VHWayPointNavigator)GetComponent<VHWayPointNavigator>(); if (m_WPNavigator == null) { Debug.LogError("VHTimeDemo needs VHWayPointNavigator"); } else { if (m_TurnWhenReachWP) { m_WPNavigator.AddWayPointReachedCallback(OnWayPointReached); } m_LookAtTargetWayPoint = m_WPNavigator.m_TurnTowardsTargetPosition; m_WPNavigator.m_TurnTowardsTargetPosition = false; // we turn this off otherwise it messes up our calculations } if (m_FpsCounter == null) { Debug.LogError("VHTimeDemo needs FpsCounter"); } //Profiler.logFile = m_PerformanceLogName; //Profiler.enableBinaryLog = true; // writes to "m_PerformanceLogName.log.data" //Profiler.enabled = true; m_sceneName = Application.loadedLevelName; m_computerName = System.Environment.MachineName; if (m_WPNavigator.m_ImmediatelyStartPathing) { StartTimeDemo(false); } // uncomment this to dump a bunch of data in the database //UploadTestData(); } public void StartTimeDemo(bool exitAfterFinished) { if (m_WPNavigator == null) { m_WPNavigator = (VHWayPointNavigator)GetComponent<VHWayPointNavigator>(); } if (!string.IsNullOrEmpty(m_OnStartFuncCallbackName)) { m_CallbackFunctionContainer.SendMessage(m_OnStartFuncCallbackName, SendMessageOptions.RequireReceiver); } m_ExitAfterFinished = exitAfterFinished; m_TimeDemoStartEndFrames.x = Time.frameCount; m_StartTime = Time.timeSinceLevelLoad; // record fps StartCoroutine(RecordFPS()); } void FinishedTimeDemo() { m_TimeDemoStartEndFrames.y = Time.frameCount; m_dateOfDemo = System.DateTime.Now; //m_Fps = new List<float>((int)(m_TimeDemoStartEndFrames.y - m_TimeDemoStartEndFrames.x)); Debug.Log(Time.timeSinceLevelLoad - m_StartTime); StopAllCoroutines(); if (!string.IsNullOrEmpty(m_OnFinishFuncCallbackName)) { m_CallbackFunctionContainer.SendMessage(m_OnFinishFuncCallbackName, SendMessageOptions.RequireReceiver); } //ReadFramerateData(); StartCoroutine(UploadTimeDemoData(TimeDemoUrl, m_ExitAfterFinished)); } IEnumerator RecordFPS() { yield return new WaitForSeconds(m_DelayWhenStarted); m_TimeData.Clear(); float travelSpeedBetweenWPs = 0; if (m_TurnWhenReachWP) { // spend half your time moving between waypoints and the other half rotating // 360 degrees when you reach each waypoint travelSpeedBetweenWPs = (m_WPNavigator.GetTotalPathLength()) / (m_TimeDemoLength * 0.5f); m_TurnSpeed = (AmountToTurnAtWP * m_WPNavigator.NumWayPoints) / (m_TimeDemoLength * 0.5f); } else { // spend all your time moving, not turning travelSpeedBetweenWPs = m_WPNavigator.GetTotalPathLength() / m_TimeDemoLength; } m_WPNavigator.SetSpeed(travelSpeedBetweenWPs); m_WPNavigator.NavigatePath(true); float startTime = Time.timeSinceLevelLoad; while (true) { if (m_FpsCounter.Fps == 0) { yield return new WaitForSeconds(m_FpsSamplingRate); continue; } if (m_AvgFpsTracker.Count >= NumAvgFpsEntries) { m_AvgFpsTracker.RemoveFirst(); } m_AvgFpsTracker.AddLast(m_FpsCounter.Fps); m_TimeData.Add(new TimeData(Time.timeSinceLevelLoad - startTime, m_FpsCounter.Fps, GetSamplingAverageFps())); yield return new WaitForSeconds(m_FpsSamplingRate); } } void OnWayPointReached(VHWayPointNavigator navigator, Vector3 wp, int wpId, int totalNumWPs) { // do a 360 degree turn StartCoroutine(Turn(navigator.m_Pather, m_TurnSpeed, AmountToTurnAtWP, navigator.m_Pather.transform.up, wpId == totalNumWPs - 1)); navigator.SetIsPathing(false); } IEnumerator Turn(GameObject turner, float turnSpeed, float degreesToTurn, Vector3 rotationAxis, bool finishedPath) { if (turnSpeed == 0) yield break; float amountTurned = 0; while (true) { float amountThisFrame = turnSpeed * Time.deltaTime; amountTurned += amountThisFrame; turner.transform.Rotate(rotationAxis, amountThisFrame); if (amountTurned >= degreesToTurn) break; yield return new WaitForEndOfFrame(); } if (finishedPath) { FinishedTimeDemo(); } else { m_WPNavigator.SetIsPathing(true); if (m_LookAtTargetWayPoint) { Utils.TurnTowardsTarget(this, m_WPNavigator.m_Pather, m_WPNavigator.TurnTarget, m_WPNavigator.m_AngularVelocity); } } } //public override void VHOnApplicationQuit () void OnApplicationQuit() { //ReadPerformanceData(); //ReadFramerateData(); } void ReadFramerateData() { string line = string.Empty; string frameSearchString = "-- Frame "; string frameRateRearchString = "Framerate: "; int startIndex = 0; int currentFrame = 0; StreamReader file = null; m_Fps.Clear(); try { // Read the file and display it line by line. file = new StreamReader(m_PerformanceLogName); while((line = file.ReadLine()) != null) { // first read the frame number to make sure it's in the // time span of our time demo startIndex = line.IndexOf(frameSearchString); if (startIndex != 0) { line = line.Remove(0, startIndex + frameSearchString.Length); line = line.Substring(0, line.IndexOf(" ")); currentFrame = int.Parse(line); } if (currentFrame < m_TimeDemoStartEndFrames.x || currentFrame > m_TimeDemoStartEndFrames.y) { // the frame didn't happen during the time demo continue; } // read the fps of the frame startIndex = line.IndexOf(frameRateRearchString); if (startIndex != -1) { line = line.Remove(0, startIndex + frameRateRearchString.Length); line = line.Substring(0, line.IndexOf(" ")); m_Fps.Add(float.Parse(line)); } } } catch (System.Exception e) { Debug.LogError("Failed parsing file " + m_PerformanceLogName + " Error: " + e.Message); } finally { if (file != null) file.Close(); } } //void ReadPerformanceData() //{ // try // { // int val = 0; // m_BinaryParser.Open(m_PerformanceLogName + ".data"); // Debug.Log(val); // // Headers // val = m_BinaryParser.ReadInt32(); // 4 bytes : Length of frame data // val = m_BinaryParser.ReadInt32(); // 4 bytes : Little endian (1) or big endian (0) // val = m_BinaryParser.ReadInt32(); // 4 bytes : Profiler version // // Frame data // val = m_BinaryParser.ReadInt32(); // 4 bytes: frameIndex // val = m_BinaryParser.ReadInt32(); // 4 bytes : realFrame; // val = m_BinaryParser.ReadInt32(); // 4 bytes : Total GPU Time In MicroSec // // Memory Stats // val = m_BinaryParser.ReadInt32(); // 4 bytes : bytesUsed // val = m_BinaryParser.ReadInt32(); // 4 bytes : bytesUsedDelta // val = m_BinaryParser.ReadInt32(); // 4 bytes : textureCount // val = m_BinaryParser.ReadInt32(); // 4 bytes : textureBytes // val = m_BinaryParser.ReadInt32(); // 4 bytes : meshCount // val = m_BinaryParser.ReadInt32(); // 4 bytes : meshBytes // val = m_BinaryParser.ReadInt32(); // 4 bytes : materialCount // val = m_BinaryParser.ReadInt32(); // 4 bytes : materialBytes // val = m_BinaryParser.ReadInt32(); // 4 bytes : animationClipCount // val = m_BinaryParser.ReadInt32(); // 4 bytes : animationClipBytes // val = m_BinaryParser.ReadInt32(); // 4 bytes : audioCount // val = m_BinaryParser.ReadInt32(); // 4 bytes : audioBytes // val = m_BinaryParser.ReadInt32(); // 4 bytes : assetCount // val = m_BinaryParser.ReadInt32(); // 4 bytes : sceneObjectCount // val = m_BinaryParser.ReadInt32(); // 4 bytes : gameObjectCount // val = m_BinaryParser.ReadInt32(); // 4 bytes : totalObjectsCount // // Classes // int classCount = m_BinaryParser.ReadInt32(); //4 bytes : classCount // for (int i = 0; i < classCount; i++) // { // val = m_BinaryParser.ReadInt32(); // 4 bytes : i // val = m_BinaryParser.ReadInt32(); // 4 bytes : value // val = m_BinaryParser.ReadInt32(); // 4 bytes : -1 (ff ff ff ff) // } // // Memory Allocation // int memoryAllocatorCount = m_BinaryParser.ReadInt32(); //4 bytes : count of memoryAllocatorInformation // for (int i = 0; i < memoryAllocatorCount; i++) // { // val = m_BinaryParser.ReadInt32(); // 4 bytes : memoryAllocatorInformation[i].used // val = m_BinaryParser.ReadInt32(); // 4 bytes : memoryAllocatorInformation[i].reserved // } // // Physics stats // val = m_BinaryParser.ReadInt32(); // 4 bytes: activeRigidbodies // val = m_BinaryParser.ReadInt32(); // 4 bytes: sleepingRigidbodies // val = m_BinaryParser.ReadInt32(); // 4 bytes: numberOfShapePairs // val = m_BinaryParser.ReadInt32(); // 4 bytes: numberOfStaticColliders // val = m_BinaryParser.ReadInt32(); // 4 bytes: numberOfDynamicColliders // // Debug stats // val = m_BinaryParser.ReadInt32(); // 4 bytes : m_ProfilerMemoryUsage // val = m_BinaryParser.ReadInt32(); // 4 bytes : m_ProfilerMemoryUsageOthers // val = m_BinaryParser.ReadInt32(); // 4 bytes : m_AllocatedProfileSamples // // Audio Stats // val = m_BinaryParser.ReadInt32(); // 4 bytes : playingSources // val = m_BinaryParser.ReadInt32(); // 4 bytes : pausedSources // val = m_BinaryParser.ReadInt32(); // 4 bytes : audioCPUusage // val = m_BinaryParser.ReadInt32(); // 4 bytes : audioMemUsage // val = m_BinaryParser.ReadInt32(); // 4 bytes : audioMaxMemUsage // val = m_BinaryParser.ReadInt32(); // 4 bytes : audioVoices // // Chart sample // val = m_BinaryParser.ReadInt32(); // 4 bytes : rendering // val = m_BinaryParser.ReadInt32(); // 4 bytes : scripts // val = m_BinaryParser.ReadInt32(); // 4 bytes : physics // val = m_BinaryParser.ReadInt32(); // 4 bytes : gc // val = m_BinaryParser.ReadInt32(); // 4 bytes : vsync // val = m_BinaryParser.ReadInt32(); // 4 bytes : others // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuOpaque // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuTransparent // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuShadows // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuPostProcess // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuDeferredPrePass // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuDeferredLighting // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuOther // val = m_BinaryParser.ReadInt32(); // 4 bytes : hasGPUProfiler // // Chart sample selected // val = m_BinaryParser.ReadInt32(); // 4 bytes : rendering // val = m_BinaryParser.ReadInt32(); // 4 bytes : scripts // val = m_BinaryParser.ReadInt32(); // 4 bytes : physics // val = m_BinaryParser.ReadInt32(); // 4 bytes : gc // val = m_BinaryParser.ReadInt32(); // 4 bytes : vsync // val = m_BinaryParser.ReadInt32(); // 4 bytes : others // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuOpaque // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuTransparent // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuShadows // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuPostProcess // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuDeferredPrePass // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuDeferredLighting // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuOther // val = m_BinaryParser.ReadInt32(); // 4 bytes : hasGPUProfiler // // GPU Time Samples // int size = m_BinaryParser.ReadInt32(); //4 bytes : array size // for (int i = 0; i < size; i++) // { // //for each item in array // val = m_BinaryParser.ReadInt32(); // 4 bytes : relatedSampleIndex // val = m_BinaryParser.ReadInt32(); // 4 bytes : timerQuery // val = m_BinaryParser.ReadInt32(); // 4 bytes : gpuTimeInMicroSec // val = m_BinaryParser.ReadInt32(); // 4 bytes : GpuSection gpuSection // } // // AllocatedGCMemorySamples // size = m_BinaryParser.ReadInt32(); // 4 bytes : array size // for (int i = 0; i < size; i++) // { // //for each item in array // val = m_BinaryParser.ReadInt32(); // 4 bytes : relatedSampleIndex // val = m_BinaryParser.ReadInt32(); // 4 bytes : allocatedGCMemory // } // // Iteration on some objects // int tf = m_BinaryParser.ReadInt32(); // 4 bytes : 1 or 0 // if (tf == 1) // { // m_BinaryParser.ReadInt32(); // n bytes + (0x00000000) = Null terminated string // m_BinaryParser.ReadInt32(); // 4 bytes : flags // } // // End of Frame // m_BinaryParser.ReadInt32(); // 4 bytes : End of Frame = AFAFAFAF // } // catch (System.Exception e) // { // Debug.LogError("Failed parsing file " + m_PerformanceLogName + " Error: " + e.Message); // } //} float GetSamplingAverageFps() { float average = 0; foreach (float data in m_AvgFpsTracker) { average += data; } if (average == 0) { average = m_FpsCounter.Fps; } return average / Mathf.Max(m_AvgFpsTracker.Count, 1); } float GetTimeDemoAverageFps() { float average = 0; for (int i = 0; i < m_TimeData.Count; i++) { average += m_TimeData[i].avgfps; } if (average == 0) { average = m_FpsCounter.Fps; } return average / Mathf.Max((float)m_TimeData.Count, 1); } float GetMaxFps() { float retVal = m_TimeData[0].curfps; for (int i = 1; i < m_TimeData.Count; i++) { if (retVal < m_TimeData[i].curfps) retVal = m_TimeData[i].curfps; } return retVal; } float GetMinFps() { float retVal = m_TimeData[0].curfps; for (int i = 1; i < m_TimeData.Count; i++) { if (retVal > m_TimeData[i].curfps) retVal = m_TimeData[i].curfps; } return retVal; } string TimeDataAsString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < m_TimeData.Count; i++) { builder.Append(string.Format("{0},{1},{2}|", m_TimeData[i].time, m_TimeData[i].curfps, m_TimeData[i].avgfps)); } builder.Remove(builder.Length - 1, 1); return builder.ToString(); } IEnumerator UploadTimeDemoData(string dbUrl, bool exitApplication) { WWWForm form = new WWWForm(); form.AddField("project_name", m_ProjectName); form.AddField("scene_name", m_sceneName); form.AddField("computer_name", m_computerName); form.AddField("timedemo_name", m_TimeDemoName); form.AddField("timedemo_length", m_TimeDemoLength.ToString("F2")); form.AddField("max_fps", GetMaxFps().ToString("F2")); form.AddField("min_fps", GetMinFps().ToString("F2")); form.AddField("avg_fps", GetTimeDemoAverageFps().ToString("F2")); form.AddField("timedata", TimeDataAsString()); form.AddField("date", m_dateOfDemo.ToString("yyyy-MM-dd HH:mm:ss")); // i.e. 2012-07-06 11:45:26 WWW www = new WWW(dbUrl, form); // when uploading large data chunks at the same time, uncomment this to prevent overloading the db //while (!www.isDone) {} yield return www; if (www.error != null) { Debug.Log(www.error); } else { Debug.Log("Successfully uploaded timedemo data"); } if (exitApplication) { Application.Quit(); } } public void UploadTestData() { // modify these values to customize the data sent to the database // this is for uploaded large amounts of dummy test data to populate the database // test info that gets uploaded m_ProjectName = "TimeDemoTest"; m_sceneName = "Scene1"; m_computerName = "machine1"; m_TimeDemoName = "TimeDemoScene9"; m_TimeDemoLength = 10; m_dateOfDemo = new System.DateTime(2012, 8, 15); // fps data that gets uploaded float lengthSeconds = 10; float interval = 0.1f; float fpsMax = 60; float fpsMin = 50; float fpsDecay = 0.1f; float fpsMinSeparation = 10; for (int day = 0; day < 30; day++) { float curTime = 0; m_TimeData = new List<TimeData>(); const int numFpsEntries = 50; float [] averageFpsArray = new float[numFpsEntries]; float averageSum = 0; while (curTime <= lengthSeconds) { float fps = Random.Range(fpsMin, fpsMax); if (m_TimeData.Count == 0) { for (int init = 0; init < numFpsEntries; init++) { averageFpsArray[init] = fps; averageSum += fps; } } int i = m_TimeData.Count % numFpsEntries; averageSum -= averageFpsArray[ i ]; averageFpsArray[ i ] = fps; averageSum += fps; float averageFps = averageSum / numFpsEntries; m_TimeData.Add(new TimeData(curTime, fps, averageFps)); curTime += interval; } StartCoroutine(UploadTimeDemoData(TimeDemoUrl, false)); // get slower each day fpsMax -= fpsDecay; fpsMin = fpsMax - fpsMinSeparation; m_dateOfDemo = m_dateOfDemo.AddDays(1); } } #endregion } */
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using UnityEngine; #if UNITY_EDITOR using Microsoft.MixedReality.Toolkit.Utilities.Editor; #endif namespace Microsoft.MixedReality.Toolkit.Utilities { /// <summary> /// Shape of an articulated hand defined by joint poses. /// </summary> public class ArticulatedHandPose { private static readonly TrackedHandJoint[] Joints = Enum.GetValues(typeof(TrackedHandJoint)) as TrackedHandJoint[]; /// <summary> /// Represents the maximum number of tracked hand joints. /// </summary> public static int JointCount { get; } = Joints.Length; /// <summary> /// Joint poses are stored as right-hand poses in camera space. /// Output poses are computed in world space, and mirroring on the x axis for the left hand. /// </summary> private readonly MixedRealityPose[] localJointPoses; public ArticulatedHandPose() { localJointPoses = new MixedRealityPose[JointCount]; SetZero(); } public ArticulatedHandPose(MixedRealityPose[] localJointPoses) { this.localJointPoses = new MixedRealityPose[JointCount]; Array.Copy(localJointPoses, this.localJointPoses, JointCount); } public MixedRealityPose GetLocalJointPose(TrackedHandJoint joint, Handedness handedness) { MixedRealityPose pose = localJointPoses[(int)joint]; // Pose offset are for right hand, mirror on X axis if left hand is needed if (handedness == Handedness.Left) { pose = new MixedRealityPose( new Vector3(-pose.Position.x, pose.Position.y, pose.Position.z), new Quaternion(pose.Rotation.x, -pose.Rotation.y, -pose.Rotation.z, pose.Rotation.w)); } return pose; } /// <summary> /// Compute world space poses from camera-space joint data. /// </summary> /// <param name="handedness">Handedness of the resulting pose</param> /// <param name="rotation">Rotational offset of the resulting pose</param> /// <param name="position">Translational offset of the resulting pose</param> /// <param name="jointsOut">Output array of joint poses</param> public void ComputeJointPoses( Handedness handedness, Quaternion rotation, Vector3 position, MixedRealityPose[] jointsOut) { for (int i = 0; i < JointCount; i++) { // Initialize from local offsets MixedRealityPose pose = GetLocalJointPose(Joints[i], handedness); Vector3 p = pose.Position; Quaternion r = pose.Rotation; // Apply external transform p = position + rotation * p; r = rotation * r; jointsOut[i] = new MixedRealityPose(p, r); } } /// <summary> /// Take world space joint poses from any hand and convert into right-hand, camera-space poses. /// </summary> /// <param name="joints">Input joint poses</param> /// <param name="handedness">Handedness of the input data</param> /// <param name="rotation">Rotational offset of the input data</param> /// <param name="position">Translational offset of the input data</param> public void ParseFromJointPoses( MixedRealityPose[] joints, Handedness handedness, Quaternion rotation, Vector3 position) { Quaternion invRotation = Quaternion.Inverse(rotation); Quaternion invCameraRotation = Quaternion.Inverse(CameraCache.Main.transform.rotation); for (int i = 0; i < JointCount; i++) { Vector3 p = joints[i].Position; Quaternion r = joints[i].Rotation; // Apply inverse external transform p = invRotation * (p - position); r = invRotation * r; // To camera space p = invCameraRotation * p; r = invCameraRotation * r; // Pose offset are for right hand, mirror on X axis if left hand is given if (handedness == Handedness.Left) { p.x = -p.x; r.y = -r.y; r.z = -r.z; } localJointPoses[i] = new MixedRealityPose(p, r); } } /// <summary> /// Set all poses to zero. /// </summary> public void SetZero() { for (int i = 0; i < JointCount; i++) { localJointPoses[i] = MixedRealityPose.ZeroIdentity; } } /// <summary> /// Copy data from another articulated hand pose. /// </summary> public void Copy(ArticulatedHandPose other) { Array.Copy(other.localJointPoses, localJointPoses, JointCount); } /// <summary> /// Blend between two hand poses. /// </summary> public void InterpolateOffsets(ArticulatedHandPose poseA, ArticulatedHandPose poseB, float value) { for (int i = 0; i < JointCount; i++) { var p = Vector3.Lerp(poseA.localJointPoses[i].Position, poseB.localJointPoses[i].Position, value); var r = Quaternion.Slerp(poseA.localJointPoses[i].Rotation, poseB.localJointPoses[i].Rotation, value); localJointPoses[i] = new MixedRealityPose(p, r); } } /// <summary> /// Supported hand gestures. /// </summary> public enum GestureId { /// <summary> /// Unspecified hand shape /// </summary> None = 0, /// <summary> /// Flat hand with fingers spread out /// </summary> Flat, /// <summary> /// Relaxed hand pose /// </summary> Open, /// <summary> /// Index finger and Thumb touching, grab point does not move /// </summary> Pinch, /// <summary> /// Index finger and Thumb touching, wrist does not move /// </summary> PinchSteadyWrist, /// <summary> /// Index finger stretched out /// </summary> Poke, /// <summary> /// Grab with whole hand, fist shape /// </summary> Grab, /// <summary> /// OK sign /// </summary> ThumbsUp, /// <summary> /// Victory sign /// </summary> Victory, /// <summary> /// Relaxed hand pose, grab point does not move /// </summary> OpenSteadyGrabPoint, /// <summary> /// Hand facing upwards, Index and Thumb stretched out to start a teleport /// </summary> TeleportStart, /// <summary> /// Hand facing upwards, Index curled in to finish a teleport /// </summary> TeleportEnd, } [Obsolete("Use SimulatedArticulatedHandPoses class or other custom class")] private static readonly Dictionary<GestureId, ArticulatedHandPose> handPoses = new Dictionary<GestureId, ArticulatedHandPose>(); /// <summary> /// Get pose data for a supported gesture. /// </summary> [Obsolete("Use SimulatedArticulatedHandPoses.GetGesturePose() or other custom class")] public static ArticulatedHandPose GetGesturePose(GestureId gesture) { if (handPoses.TryGetValue(gesture, out ArticulatedHandPose pose)) { return pose; } return null; } #if UNITY_EDITOR /// <summary> /// Load pose data from files. /// </summary> [Obsolete("Use SimulatedArticulatedHandPoses or other custom class")] public static void LoadGesturePoses() { string[] gestureNames = Enum.GetNames(typeof(GestureId)); string basePath = Path.Combine("InputSimulation", "ArticulatedHandPoses"); for (int i = 0; i < gestureNames.Length; ++i) { string relPath = Path.Combine(basePath, String.Format("ArticulatedHandPose_{0}.json", gestureNames[i])); string absPath = MixedRealityToolkitFiles.MapRelativeFilePath(MixedRealityToolkitModuleType.Services, relPath); LoadGesturePose((GestureId)i, absPath); } } [Obsolete("Use SimulatedArticulatedHandPoses class or other custom class")] private static ArticulatedHandPose LoadGesturePose(GestureId gesture, string filePath) { if (!string.IsNullOrEmpty(filePath)) { var pose = new ArticulatedHandPose(); pose.FromJson(File.ReadAllText(filePath)); handPoses.Add(gesture, pose); return pose; } return null; } [Obsolete("Use SimulatedArticulatedHandPoses class or other custom class")] public static void ResetGesturePoses() { handPoses.Clear(); } #endif /// Utility class to serialize hand pose as a dictionary with full joint names [Serializable] internal struct ArticulatedHandPoseItem { private static readonly string[] jointNames = Enum.GetNames(typeof(TrackedHandJoint)); public string joint; public MixedRealityPose pose; public TrackedHandJoint JointIndex { get { int nameIndex = Array.FindIndex(jointNames, IsJointName); if (nameIndex < 0) { Debug.LogError($"Joint name {joint} not in TrackedHandJoint enum"); return TrackedHandJoint.None; } return (TrackedHandJoint)nameIndex; } set { joint = jointNames[(int)value]; } } private bool IsJointName(string s) { return s == joint; } public ArticulatedHandPoseItem(TrackedHandJoint joint, MixedRealityPose pose) { this.joint = jointNames[(int)joint]; this.pose = pose; } } /// Utility class to serialize hand pose as a dictionary with full joint names [Serializable] internal class ArticulatedHandPoseDictionary { public ArticulatedHandPoseItem[] items = null; public void FromJointPoses(MixedRealityPose[] jointPoses) { items = new ArticulatedHandPoseItem[JointCount]; for (int i = 0; i < JointCount; ++i) { items[i].JointIndex = (TrackedHandJoint)i; items[i].pose = jointPoses[i]; } } public void ToJointPoses(MixedRealityPose[] jointPoses) { for (int i = 0; i < JointCount; ++i) { jointPoses[i] = MixedRealityPose.ZeroIdentity; } foreach (var item in items) { jointPoses[(int)item.JointIndex] = item.pose; } } } /// <summary> /// Serialize pose data to JSON format. /// </summary> public string ToJson() { var dict = new ArticulatedHandPoseDictionary(); dict.FromJointPoses(localJointPoses); return JsonUtility.ToJson(dict, true); } /// <summary> /// Deserialize pose data from JSON format. /// </summary> public void FromJson(string json) { var dict = JsonUtility.FromJson<ArticulatedHandPoseDictionary>(json); dict.ToJointPoses(localJointPoses); } } }
// // MessageReaderViewController.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2014 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using Foundation; using UIKit; using MimeKit; using MimeKit.Text; namespace MessageReader.iOS { public partial class MessageReaderViewController : UIViewController { MimeMessage message; public MessageReaderViewController (IntPtr handle) : base (handle) { } public MimeMessage Message { get { return message; } set { if (value == null) throw new ArgumentNullException ("value"); message = value; Render (message.Body); } } public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } #region View lifecycle public override void ViewDidLoad () { base.ViewDidLoad (); webView.ScalesPageToFit = true; // Perform any additional setup after loading the view, typically from a nib. Message = MimeMessage.Load (GetType ().Assembly.GetManifestResourceStream ("xamarin3.msg")); } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); } public override void ViewDidAppear (bool animated) { base.ViewDidAppear (animated); } public override void ViewWillDisappear (bool animated) { base.ViewWillDisappear (animated); } public override void ViewDidDisappear (bool animated) { base.ViewDidDisappear (animated); } #endregion void RenderMultipartRelated (MultipartRelated related) { var root = related.Root; if (root == null) return; var cache = new MultipartRelatedUrlCache (related); NSUrlCache.SharedCache = cache; Render (root); } void RenderText (TextPart text) { string html; if (text.IsHtml) { // the text content is already in HTML format html = text.Text; } else if (text.IsFlowed) { var converter = new FlowedToHtml (); string delsp; // the delsp parameter specifies whether or not to delete spaces at the end of flowed lines if (!text.ContentType.Parameters.TryGetValue ("delsp", out delsp)) delsp = "no"; if (string.Compare (delsp, "yes", StringComparison.OrdinalIgnoreCase) == 0) converter.DeleteSpace = true; html = converter.Convert (text.Text); } else { html = new TextToHtml ().Convert (text.Text); } webView.LoadHtmlString (html, new NSUrl ("index.html")); } void Render (MimeEntity entity) { var related = entity as MultipartRelated; if (related != null) { RenderMultipartRelated (related); return; } var multipart = entity as Multipart; var text = entity as TextPart; // check if the entity is a multipart if (multipart != null) { if (multipart.ContentType.IsMimeType ("multipart", "alternative")) { // A multipart/alternative is just a collection of alternate views. // The last part is the format that most closely matches what the // user saw in his or her email client's WYSIWYG editor. TextPart preferred = null; for (int i = multipart.Count; i > 0; i--) { related = multipart[i - 1] as MultipartRelated; if (related != null) { var root = related.Root; if (root != null && root.ContentType.IsMimeType ("text", "html")) { RenderMultipartRelated (related); return; } continue; } text = multipart[i - 1] as TextPart; if (text == null) continue; if (text.IsHtml) { // we prefer html over plain text preferred = text; break; } if (preferred == null) { // we'll take what we can get preferred = text; } } if (preferred != null) RenderText (preferred); } else if (multipart.Count > 0) { // At this point we know we're not dealing with a multipart/related or a // multipart/alternative, so we can safely treat this as a multipart/mixed // even if it's not. // The main message body is usually the first part of a multipart/mixed. I // suppose that it might be better to render the first text/* part instead // (in case it's not the first part), but that's rare and probably also // indicates that the text is meant to be displayed between the other parts // (probably images or video?) in some sort of pseudo-multimedia "document" // layout. Modern clients don't do this, they use HTML or RTF instead. Render (multipart[0]); } } else if (text != null) { // render the text part RenderText (text); } else { // message/rfc822 part } } } }
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1) #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Linq; using System.Globalization; namespace Newtonsoft.Json.Bson { /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data. /// </summary> public class BsonWriter : JsonWriter { private readonly BsonBinaryWriter _writer; private BsonToken _root; private BsonToken _parent; private string _propertyName; /// <summary> /// Gets or sets the <see cref="DateTimeKind" /> used when writing <see cref="DateTime"/> values to BSON. /// When set to <see cref="DateTimeKind.Unspecified" /> no conversion will occur. /// </summary> /// <value>The <see cref="DateTimeKind" /> used when writing <see cref="DateTime"/> values to BSON.</value> public DateTimeKind DateTimeKindHandling { get { return _writer.DateTimeKindHandling; } set { _writer.DateTimeKindHandling = value; } } /// <summary> /// Initializes a new instance of the <see cref="BsonWriter"/> class. /// </summary> /// <param name="stream">The stream.</param> public BsonWriter(Stream stream) { ValidationUtils.ArgumentNotNull(stream, "stream"); _writer = new BsonBinaryWriter(stream); } /// <summary> /// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream. /// </summary> public override void Flush() { _writer.Flush(); } /// <summary> /// Writes the end. /// </summary> /// <param name="token">The token.</param> protected override void WriteEnd(JsonToken token) { base.WriteEnd(token); RemoveParent(); if (Top == 0) { _writer.WriteToken(_root); } } /// <summary> /// Writes out a comment <code>/*...*/</code> containing the specified text. /// </summary> /// <param name="text">Text to place inside the comment.</param> public override void WriteComment(string text) { throw new JsonWriterException("Cannot write JSON comment as BSON."); } /// <summary> /// Writes the start of a constructor with the given name. /// </summary> /// <param name="name">The name of the constructor.</param> public override void WriteStartConstructor(string name) { throw new JsonWriterException("Cannot write JSON constructor as BSON."); } /// <summary> /// Writes raw JSON. /// </summary> /// <param name="json">The raw JSON to write.</param> public override void WriteRaw(string json) { throw new JsonWriterException("Cannot write raw JSON as BSON."); } /// <summary> /// Writes raw JSON where a value is expected and updates the writer's state. /// </summary> /// <param name="json">The raw JSON to write.</param> public override void WriteRawValue(string json) { throw new JsonWriterException("Cannot write raw JSON as BSON."); } /// <summary> /// Writes the beginning of a Json array. /// </summary> public override void WriteStartArray() { base.WriteStartArray(); AddParent(new BsonArray()); } /// <summary> /// Writes the beginning of a Json object. /// </summary> public override void WriteStartObject() { base.WriteStartObject(); AddParent(new BsonObject()); } /// <summary> /// Writes the property name of a name/value pair on a Json object. /// </summary> /// <param name="name">The name of the property.</param> public override void WritePropertyName(string name) { base.WritePropertyName(name); _propertyName = name; } /// <summary> /// Closes this stream and the underlying stream. /// </summary> public override void Close() { base.Close(); if (CloseOutput && _writer != null) _writer.Close(); } private void AddParent(BsonToken container) { AddToken(container); _parent = container; } private void RemoveParent() { _parent = _parent.Parent; } private void AddValue(object value, BsonType type) { AddToken(new BsonValue(value, type)); } internal void AddToken(BsonToken token) { if (_parent != null) { if (_parent is BsonObject) { ((BsonObject)_parent).Add(_propertyName, token); _propertyName = null; } else { ((BsonArray)_parent).Add(token); } } else { if (token.Type != BsonType.Object && token.Type != BsonType.Array) throw new JsonWriterException("Error writing {0} value. BSON must start with an Object or Array.".FormatWith(CultureInfo.InvariantCulture, token.Type)); _parent = token; _root = token; } } #region WriteValue methods /// <summary> /// Writes a null value. /// </summary> public override void WriteNull() { base.WriteNull(); AddValue(null, BsonType.Null); } /// <summary> /// Writes an undefined value. /// </summary> public override void WriteUndefined() { base.WriteUndefined(); AddValue(null, BsonType.Undefined); } /// <summary> /// Writes a <see cref="String"/> value. /// </summary> /// <param name="value">The <see cref="String"/> value to write.</param> public override void WriteValue(string value) { base.WriteValue(value); if (value == null) AddValue(null, BsonType.Null); else AddToken(new BsonString(value, true)); } /// <summary> /// Writes a <see cref="Int32"/> value. /// </summary> /// <param name="value">The <see cref="Int32"/> value to write.</param> public override void WriteValue(int value) { base.WriteValue(value); AddValue(value, BsonType.Integer); } /// <summary> /// Writes a <see cref="UInt32"/> value. /// </summary> /// <param name="value">The <see cref="UInt32"/> value to write.</param> // public override void WriteValue(uint value) { if (value > int.MaxValue) throw new JsonWriterException("Value is too large to fit in a signed 32 bit integer. BSON does not support unsigned values."); base.WriteValue(value); AddValue(value, BsonType.Integer); } /// <summary> /// Writes a <see cref="Int64"/> value. /// </summary> /// <param name="value">The <see cref="Int64"/> value to write.</param> public override void WriteValue(long value) { base.WriteValue(value); AddValue(value, BsonType.Long); } /// <summary> /// Writes a <see cref="UInt64"/> value. /// </summary> /// <param name="value">The <see cref="UInt64"/> value to write.</param> // public override void WriteValue(ulong value) { if (value > long.MaxValue) throw new JsonWriterException("Value is too large to fit in a signed 64 bit integer. BSON does not support unsigned values."); base.WriteValue(value); AddValue(value, BsonType.Long); } /// <summary> /// Writes a <see cref="Single"/> value. /// </summary> /// <param name="value">The <see cref="Single"/> value to write.</param> public override void WriteValue(float value) { base.WriteValue(value); AddValue(value, BsonType.Number); } /// <summary> /// Writes a <see cref="Double"/> value. /// </summary> /// <param name="value">The <see cref="Double"/> value to write.</param> public override void WriteValue(double value) { base.WriteValue(value); AddValue(value, BsonType.Number); } /// <summary> /// Writes a <see cref="Boolean"/> value. /// </summary> /// <param name="value">The <see cref="Boolean"/> value to write.</param> public override void WriteValue(bool value) { base.WriteValue(value); AddValue(value, BsonType.Boolean); } /// <summary> /// Writes a <see cref="Int16"/> value. /// </summary> /// <param name="value">The <see cref="Int16"/> value to write.</param> public override void WriteValue(short value) { base.WriteValue(value); AddValue(value, BsonType.Integer); } /// <summary> /// Writes a <see cref="UInt16"/> value. /// </summary> /// <param name="value">The <see cref="UInt16"/> value to write.</param> // public override void WriteValue(ushort value) { base.WriteValue(value); AddValue(value, BsonType.Integer); } /// <summary> /// Writes a <see cref="Char"/> value. /// </summary> /// <param name="value">The <see cref="Char"/> value to write.</param> public override void WriteValue(char value) { base.WriteValue(value); AddToken(new BsonString(value.ToString(), true)); } /// <summary> /// Writes a <see cref="Byte"/> value. /// </summary> /// <param name="value">The <see cref="Byte"/> value to write.</param> public override void WriteValue(byte value) { base.WriteValue(value); AddValue(value, BsonType.Integer); } /// <summary> /// Writes a <see cref="SByte"/> value. /// </summary> /// <param name="value">The <see cref="SByte"/> value to write.</param> // public override void WriteValue(sbyte value) { base.WriteValue(value); AddValue(value, BsonType.Integer); } /// <summary> /// Writes a <see cref="Decimal"/> value. /// </summary> /// <param name="value">The <see cref="Decimal"/> value to write.</param> public override void WriteValue(decimal value) { base.WriteValue(value); AddValue(value, BsonType.Number); } /// <summary> /// Writes a <see cref="DateTime"/> value. /// </summary> /// <param name="value">The <see cref="DateTime"/> value to write.</param> public override void WriteValue(DateTime value) { base.WriteValue(value); AddValue(value, BsonType.Date); } /// <summary> /// Writes a <see cref="DateTimeOffset"/> value. /// </summary> /// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param> public override void WriteValue(DateTimeOffset value) { base.WriteValue(value); AddValue(value, BsonType.Date); } /// <summary> /// Writes a <see cref="T:Byte[]"/> value. /// </summary> /// <param name="value">The <see cref="T:Byte[]"/> value to write.</param> public override void WriteValue(byte[] value) { base.WriteValue(value); AddValue(value, BsonType.Binary); } /// <summary> /// Writes a <see cref="Guid"/> value. /// </summary> /// <param name="value">The <see cref="Guid"/> value to write.</param> public override void WriteValue(Guid value) { base.WriteValue(value); AddToken(new BsonString(value.ToString(), true)); } /// <summary> /// Writes a <see cref="TimeSpan"/> value. /// </summary> /// <param name="value">The <see cref="TimeSpan"/> value to write.</param> public override void WriteValue(TimeSpan value) { base.WriteValue(value); AddToken(new BsonString(value.ToString(), true)); } /// <summary> /// Writes a <see cref="Uri"/> value. /// </summary> /// <param name="value">The <see cref="Uri"/> value to write.</param> public override void WriteValue(Uri value) { base.WriteValue(value); AddToken(new BsonString(value.ToString(), true)); } #endregion /// <summary> /// Writes a <see cref="T:Byte[]"/> value that represents a BSON object id. /// </summary> /// <param name="value"></param> public void WriteObjectId(byte[] value) { ValidationUtils.ArgumentNotNull(value, "value"); if (value.Length != 12) throw new Exception("An object id must be 12 bytes"); // hack to update the writer state AutoComplete(JsonToken.Undefined); AddValue(value, BsonType.Oid); } /// <summary> /// Writes a BSON regex. /// </summary> /// <param name="pattern">The regex pattern.</param> /// <param name="options">The regex options.</param> public void WriteRegex(string pattern, string options) { ValidationUtils.ArgumentNotNull(pattern, "pattern"); // hack to update the writer state AutoComplete(JsonToken.Undefined); AddToken(new BsonRegex(pattern, options)); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // InstanceDescriptorTest.cs - Unit tests for // System.ComponentModel.Design.Serialization.InstanceDescriptor // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (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. // using Xunit; using System.ComponentModel.Design.Serialization; using System.Reflection; using System.Threading; namespace System.ComponentModel.Tests { public class InstanceDescriptorTest { private const string url = "http://www.mono-project.com/"; private ConstructorInfo ci; public InstanceDescriptorTest() { ci = typeof(Uri).GetConstructor(new Type[1] { typeof(string) }); } [Fact] public void Constructor0_Arguments_Mismatch() { ArgumentException ex = Assert.Throws<ArgumentException>(() => new InstanceDescriptor(ci, null)); // Length mismatch Assert.Equal(typeof(ArgumentException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Null(ex.ParamName); } [Fact] public void Constructor_MemberInfo_ICollection() { InstanceDescriptor id = new InstanceDescriptor(ci, new object[] { url }); Assert.Equal(1, id.Arguments.Count); Assert.True(id.IsComplete); Assert.Same(ci, id.MemberInfo); Uri uri = (Uri)id.Invoke(); Assert.Equal(url, uri.AbsoluteUri); } [Fact] public void Constructor_MemberInfo_Null_Boolean() { Assert.Throws<ArgumentException>(() => new InstanceDescriptor(ci, null, false)); // mismatch for required parameters } [Fact] public void Constructor_MemberInfo_ICollection_Boolean() { InstanceDescriptor id = new InstanceDescriptor(ci, new object[] { url }, false); Assert.Equal(1, id.Arguments.Count); Assert.False(id.IsComplete); Assert.Same(ci, id.MemberInfo); Uri uri = (Uri)id.Invoke(); Assert.Equal(url, uri.AbsoluteUri); } [Fact] public void Field_Arguments_Empty() { FieldInfo fi = typeof(Uri).GetField("SchemeDelimiter"); InstanceDescriptor id = new InstanceDescriptor(fi, new object[0]); Assert.Equal(0, id.Arguments.Count); Assert.True(id.IsComplete); Assert.Same(fi, id.MemberInfo); Assert.NotNull(id.Invoke()); } [Fact] public void Field_Arguments_Mismatch() { FieldInfo fi = typeof(Uri).GetField("SchemeDelimiter"); ArgumentException ex = Assert.Throws<ArgumentException>(() => new InstanceDescriptor(fi, new object[] { url })); // Parameter must be static Assert.Equal(typeof(ArgumentException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Null(ex.ParamName); } [Fact] public void Field_Arguments_Null() { FieldInfo fi = typeof(Uri).GetField("SchemeDelimiter"); InstanceDescriptor id = new InstanceDescriptor(fi, null); Assert.Equal(0, id.Arguments.Count); Assert.True(id.IsComplete); Assert.Same(fi, id.MemberInfo); Assert.NotNull(id.Invoke()); } [Fact] public void Field_MemberInfo_NonStatic() { FieldInfo fi = typeof(InstanceField).GetField("Name"); ArgumentException ex = Assert.Throws<ArgumentException>(() => new InstanceDescriptor(fi, null)); // Parameter must be static Assert.Equal(typeof(ArgumentException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Null(ex.ParamName); } [Fact] public void Property_Arguments_Mismatch() { PropertyInfo pi = typeof(Thread).GetProperty("CurrentThread"); InstanceDescriptor id = new InstanceDescriptor(pi, new object[] { url }); Assert.Equal(1, id.Arguments.Count); object[] arguments = new object[id.Arguments.Count]; id.Arguments.CopyTo(arguments, 0); Assert.Same(url, arguments[0]); Assert.True(id.IsComplete); Assert.Same(pi, id.MemberInfo); Assert.Throws<TargetParameterCountException>(() => id.Invoke()); } [Fact] public void Property_Arguments_Null() { PropertyInfo pi = typeof(Thread).GetProperty("CurrentThread"); InstanceDescriptor id = new InstanceDescriptor(pi, null); Assert.Equal(0, id.Arguments.Count); Assert.True(id.IsComplete); Assert.Same(pi, id.MemberInfo); Assert.NotNull(id.Invoke()); } [Fact] public void Property_MemberInfo_NonStatic() { PropertyInfo pi = typeof(Uri).GetProperty("Host"); ArgumentException ex; ex = Assert.Throws<ArgumentException>(() => new InstanceDescriptor(pi, null)); // Parameter must be static Assert.Equal(typeof(ArgumentException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Null(ex.ParamName); ex = Assert.Throws<ArgumentException>(() => new InstanceDescriptor(pi, null, false)); // Parameter must be static Assert.Equal(typeof(ArgumentException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Null(ex.ParamName); } [Fact] public void Property_MemberInfo_WriteOnly() { PropertyInfo pi = typeof(WriteOnlyProperty).GetProperty("Name"); ArgumentException ex = Assert.Throws<ArgumentException>(() => new InstanceDescriptor(pi, null)); // Parameter must be readable Assert.Equal(typeof(ArgumentException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Null(ex.ParamName); } private class WriteOnlyProperty { public static string Name { set { } } } public class InstanceField { public string Name; } } }
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 Apress.WebApi.Recipes.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; } } }
#region License /* * HttpRequest.cs * * The MIT License * * Copyright (c) 2012-2015 sta.blockhead * * 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 #region Contributors /* * Contributors: * - David Burhans */ #endregion using System; using System.Collections.Specialized; using System.IO; using System.Text; using WebSocketSharp.Net; namespace WebSocketSharp { internal class HttpRequest : HttpBase { #region Private Fields private CookieCollection _cookies; private string _method; private string _uri; #endregion #region Private Constructors private HttpRequest (string method, string uri, Version version, NameValueCollection headers) : base (version, headers) { _method = method; _uri = uri; } #endregion #region Internal Constructors internal HttpRequest (string method, string uri) : this (method, uri, HttpVersion.Version11, new NameValueCollection ()) { Headers["User-Agent"] = "websocket-sharp/1.0"; } #endregion #region Public Properties public AuthenticationResponse AuthenticationResponse { get { var res = Headers["Authorization"]; return res != null && res.Length > 0 ? AuthenticationResponse.Parse (res) : null; } } public CookieCollection Cookies { get { if (_cookies == null) _cookies = Headers.GetCookies (false); return _cookies; } } public string HttpMethod { get { return _method; } } public bool IsWebSocketRequest { get { return _method == "GET" && ProtocolVersion > HttpVersion.Version10 && Headers.Upgrades ("websocket"); } } public string RequestUri { get { return _uri; } } #endregion #region Internal Methods internal static HttpRequest CreateConnectRequest (Uri uri) { var host = uri.DnsSafeHost; var port = uri.Port; var authority = String.Format ("{0}:{1}", host, port); var req = new HttpRequest ("CONNECT", authority); req.Headers["Host"] = port == 80 ? host : authority; return req; } internal static HttpRequest CreateWebSocketRequest (Uri uri) { var req = new HttpRequest ("GET", uri.PathAndQuery); var headers = req.Headers; // Only includes a port number in the Host header value if it's non-default. // See: https://tools.ietf.org/html/rfc6455#page-17 var port = uri.Port; var schm = uri.Scheme; headers["Host"] = (port == 80 && schm == "ws") || (port == 443 && schm == "wss") ? uri.DnsSafeHost : uri.Authority; headers["Upgrade"] = "websocket"; headers["Connection"] = "Upgrade"; return req; } internal HttpResponse GetResponse (Stream stream, int millisecondsTimeout) { var buff = ToByteArray (); stream.Write (buff, 0, buff.Length); return Read<HttpResponse> (stream, HttpResponse.Parse, millisecondsTimeout); } internal static HttpRequest Parse (string[] headerParts) { var requestLine = headerParts[0].Split (new[] { ' ' }, 3); if (requestLine.Length != 3) throw new ArgumentException ("Invalid request line: " + headerParts[0]); var headers = new WebHeaderCollection (); for (int i = 1; i < headerParts.Length; i++) headers.InternalSet (headerParts[i], false); return new HttpRequest ( requestLine[0], requestLine[1], new Version (requestLine[2].Substring (5)), headers); } internal static HttpRequest Read (Stream stream, int millisecondsTimeout) { return Read<HttpRequest> (stream, Parse, millisecondsTimeout); } #endregion #region Public Methods public void SetCookies (CookieCollection cookies) { if (cookies == null || cookies.Count == 0) return; var buff = new StringBuilder (64); foreach (var cookie in cookies.Sorted) if (!cookie.Expired) buff.AppendFormat ("{0}; ", cookie.ToString ()); var len = buff.Length; if (len > 2) { buff.Length = len - 2; Headers["Cookie"] = buff.ToString (); } } public override string ToString () { var output = new StringBuilder (64); output.AppendFormat ("{0} {1} HTTP/{2}{3}", _method, _uri, ProtocolVersion, CrLf); var headers = Headers; foreach (var key in headers.AllKeys) output.AppendFormat ("{0}: {1}{2}", key, headers[key], CrLf); output.Append (CrLf); var entity = EntityBody; if (entity.Length > 0) output.Append (entity); return output.ToString (); } #endregion } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using Quartz.Spi; namespace Quartz { /// <summary> /// TriggerBuilder is used to instantiate <see cref="ITrigger" />s. /// </summary> /// <remarks> /// <para> /// The builder will always try to keep itself in a valid state, with /// reasonable defaults set for calling build() at any point. For instance /// if you do not invoke <i>WithSchedule(..)</i> method, a default schedule /// of firing once immediately will be used. As another example, if you /// do not invoked <i>WithIdentity(..)</i> a trigger name will be generated /// for you. /// </para> /// <para> /// Quartz provides a builder-style API for constructing scheduling-related /// entities via a Domain-Specific Language (DSL). The DSL can best be /// utilized through the usage of static imports of the methods on the classes /// <see cref="TriggerBuilder" />, <see cref="JobBuilder" />, /// <see cref="DateBuilder" />, <see cref="JobKey" />, <see cref="TriggerKey" /> /// and the various <see cref="IScheduleBuilder" /> implementations. /// </para> /// <para> /// Client code can then use the DSL to write code such as this: /// </para> /// <code> /// IJobDetail job = JobBuilder.Create&lt;MyJob>() /// .WithIdentity("myJob") /// .Build(); /// ITrigger trigger = TriggerBuilder.Create() /// .WithIdentity("myTrigger", "myTriggerGroup") /// .WithSimpleSchedule(x => x /// .WithIntervalInHours(1) /// .RepeatForever()) /// .StartAt(DateBuilder.FutureDate(10, IntervalUnit.Minute)) /// .Build(); /// scheduler.scheduleJob(job, trigger); /// </code> /// </remarks> /// <seealso cref="JobBuilder" /> /// <seealso cref="IScheduleBuilder" /> /// <seealso cref="DateBuilder" /> /// <seealso cref="ITrigger" /> public class TriggerBuilder { private TriggerKey key; private string description; private DateTimeOffset startTime = SystemTime.UtcNow(); private DateTimeOffset? endTime; private int priority = TriggerConstants.DefaultPriority; private string calendarName; private JobKey jobKey; private JobDataMap jobDataMap = new JobDataMap(); private IScheduleBuilder scheduleBuilder; private TriggerBuilder() { } /// <summary> /// Create a new TriggerBuilder with which to define a /// specification for a Trigger. /// </summary> /// <remarks> /// </remarks> /// <returns>the new TriggerBuilder</returns> public static TriggerBuilder Create() { return new TriggerBuilder(); } /// <summary> /// Produce the <see cref="ITrigger" />. /// </summary> /// <remarks> /// </remarks> /// <returns>a Trigger that meets the specifications of the builder.</returns> public ITrigger Build() { if (scheduleBuilder == null) { scheduleBuilder = SimpleScheduleBuilder.Create(); } IMutableTrigger trig = scheduleBuilder.Build(); trig.CalendarName = calendarName; trig.Description = description; trig.StartTimeUtc = startTime; trig.EndTimeUtc = endTime; if (key == null) { key = new TriggerKey(Guid.NewGuid().ToString(), null); } trig.Key = key; if (jobKey != null) { trig.JobKey = jobKey; } trig.Priority = priority; if (!jobDataMap.IsEmpty) { trig.JobDataMap = jobDataMap; } return trig; } /// <summary> /// Use a <see cref="TriggerKey" /> with the given name and default group to /// identify the Trigger. /// </summary> /// <remarks> /// <para>If none of the 'withIdentity' methods are set on the TriggerBuilder, /// then a random, unique TriggerKey will be generated.</para> /// </remarks> /// <param name="name">the name element for the Trigger's TriggerKey</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="TriggerKey" /> /// <seealso cref="ITrigger.Key" /> public TriggerBuilder WithIdentity(string name) { key = new TriggerKey(name, null); return this; } /// <summary> /// Use a TriggerKey with the given name and group to /// identify the Trigger. /// </summary> /// <remarks> /// <para>If none of the 'withIdentity' methods are set on the TriggerBuilder, /// then a random, unique TriggerKey will be generated.</para> /// </remarks> /// <param name="name">the name element for the Trigger's TriggerKey</param> /// <param name="group">the group element for the Trigger's TriggerKey</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="TriggerKey" /> /// <seealso cref="ITrigger.Key" /> public TriggerBuilder WithIdentity(string name, string group) { key = new TriggerKey(name, group); return this; } /// <summary> /// Use the given TriggerKey to identify the Trigger. /// </summary> /// <remarks> /// <para>If none of the 'withIdentity' methods are set on the TriggerBuilder, /// then a random, unique TriggerKey will be generated.</para> /// </remarks> /// <param name="key">the TriggerKey for the Trigger to be built</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="TriggerKey" /> /// <seealso cref="ITrigger.Key" /> public TriggerBuilder WithIdentity(TriggerKey key) { this.key = key; return this; } /// <summary> /// Set the given (human-meaningful) description of the Trigger. /// </summary> /// <remarks> /// </remarks> /// <param name="description">the description for the Trigger</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.Description" /> public TriggerBuilder WithDescription(string description) { this.description = description; return this; } /// <summary> /// Set the Trigger's priority. When more than one Trigger have the same /// fire time, the scheduler will fire the one with the highest priority /// first. /// </summary> /// <remarks> /// </remarks> /// <param name="priority">the priority for the Trigger</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="TriggerConstants.DefaultPriority" /> /// <seealso cref="ITrigger.Priority" /> public TriggerBuilder WithPriority(int priority) { this.priority = priority; return this; } /// <summary> /// Set the name of the <see cref="ICalendar" /> that should be applied to this /// Trigger's schedule. /// </summary> /// <remarks> /// </remarks> /// <param name="calendarName">the name of the Calendar to reference.</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ICalendar" /> /// <seealso cref="ITrigger.CalendarName" /> public TriggerBuilder ModifiedByCalendar(string calendarName) { this.calendarName = calendarName; return this; } /// <summary> /// Set the time the Trigger should start at - the trigger may or may /// not fire at this time - depending upon the schedule configured for /// the Trigger. However the Trigger will NOT fire before this time, /// regardless of the Trigger's schedule. /// </summary> /// <remarks> /// </remarks> /// <param name="startTimeUtc">the start time for the Trigger.</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.StartTimeUtc" /> /// <seealso cref="DateBuilder" /> public TriggerBuilder StartAt(DateTimeOffset startTimeUtc) { startTime = startTimeUtc; return this; } /// <summary> /// Set the time the Trigger should start at to the current moment - /// the trigger may or may not fire at this time - depending upon the /// schedule configured for the Trigger. /// </summary> /// <remarks> /// </remarks> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.StartTimeUtc" /> public TriggerBuilder StartNow() { startTime = SystemTime.UtcNow(); return this; } /// <summary> /// Set the time at which the Trigger will no longer fire - even if it's /// schedule has remaining repeats. /// </summary> /// <remarks> /// </remarks> /// <param name="endTimeUtc">the end time for the Trigger. If null, the end time is indefinite.</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.EndTimeUtc" /> /// <seealso cref="DateBuilder" /> public TriggerBuilder EndAt(DateTimeOffset? endTimeUtc) { endTime = endTimeUtc; return this; } /// <summary> /// Set the <see cref="IScheduleBuilder" /> that will be used to define the /// Trigger's schedule. /// </summary> /// <remarks> /// <para>The particular <see cref="IScheduleBuilder" /> used will dictate /// the concrete type of Trigger that is produced by the TriggerBuilder.</para> /// </remarks> /// <param name="scheduleBuilder">the SchedulerBuilder to use.</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="IScheduleBuilder" /> /// <seealso cref="SimpleScheduleBuilder" /> /// <seealso cref="CronScheduleBuilder" /> /// <seealso cref="CalendarIntervalScheduleBuilder" /> public TriggerBuilder WithSchedule(IScheduleBuilder scheduleBuilder) { this.scheduleBuilder = scheduleBuilder; return this; } /// <summary> /// Set the identity of the Job which should be fired by the produced /// Trigger. /// </summary> /// <remarks> /// </remarks> /// <param name="jobKey">the identity of the Job to fire.</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.JobKey" /> public TriggerBuilder ForJob(JobKey jobKey) { this.jobKey = jobKey; return this; } /// <summary> /// Set the identity of the Job which should be fired by the produced /// Trigger - a <see cref="JobKey" /> will be produced with the given /// name and default group. /// </summary> /// <remarks> /// </remarks> /// <param name="jobName">the name of the job (in default group) to fire.</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.JobKey" /> public TriggerBuilder ForJob(string jobName) { jobKey = new JobKey(jobName, null); return this; } /// <summary> /// Set the identity of the Job which should be fired by the produced /// Trigger - a <see cref="JobKey" /> will be produced with the given /// name and group. /// </summary> /// <remarks> /// </remarks> /// <param name="jobName">the name of the job to fire.</param> /// <param name="jobGroup">the group of the job to fire.</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.JobKey" /> public TriggerBuilder ForJob(string jobName, string jobGroup) { jobKey = new JobKey(jobName, jobGroup); return this; } /// <summary> /// Set the identity of the Job which should be fired by the produced /// Trigger, by extracting the JobKey from the given job. /// </summary> /// <remarks> /// </remarks> /// <param name="jobDetail">the Job to fire.</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.JobKey" /> public TriggerBuilder ForJob(IJobDetail jobDetail) { JobKey k = jobDetail.Key; if (k.Name == null) { throw new ArgumentException("The given job has not yet had a name assigned to it."); } jobKey = k; return this; } /// <summary> /// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />. /// </summary> /// <remarks> /// </remarks> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.JobDataMap" /> public TriggerBuilder UsingJobData(string key, string value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />. /// </summary> /// <remarks> /// </remarks> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.JobDataMap" /> public TriggerBuilder UsingJobData(string key, int value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />. /// </summary> /// <remarks> /// </remarks> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.JobDataMap" /> public TriggerBuilder UsingJobData(string key, long value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />. /// </summary> /// <remarks> /// </remarks> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.JobDataMap" /> public TriggerBuilder UsingJobData(string key, float value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />. /// </summary> /// <remarks> /// </remarks> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.JobDataMap" /> public TriggerBuilder UsingJobData(string key, double value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />. /// </summary> /// <remarks> /// </remarks> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.JobDataMap" /> public TriggerBuilder UsingJobData(string key, decimal value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />. /// </summary> /// <remarks> /// </remarks> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.JobDataMap" /> public TriggerBuilder UsingJobData(string key, bool value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />. /// </summary> /// <remarks> /// </remarks> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.JobDataMap" /> public TriggerBuilder UsingJobData(JobDataMap newJobDataMap) { // add any existing data to this new map foreach (string k in jobDataMap.Keys) { newJobDataMap.Put(k, jobDataMap.Get(k)); } jobDataMap = newJobDataMap; // set new map as the map to use return this; } } }