context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyInteger { using System.Threading.Tasks; using Models; /// <summary> /// Extension methods for IntModel. /// </summary> public static partial class IntModelExtensions { /// <summary> /// Get null Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetNull(this IIntModel operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetNullAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get null Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<int?> GetNullAsync(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get invalid Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetInvalid(this IIntModel operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<int?> GetInvalidAsync(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get overflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetOverflowInt32(this IIntModel operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt32Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<int?> GetOverflowInt32Async(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetOverflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get underflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetUnderflowInt32(this IIntModel operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt32Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<int?> GetUnderflowInt32Async(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetUnderflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get overflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static long? GetOverflowInt64(this IIntModel operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt64Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<long?> GetOverflowInt64Async(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetOverflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get underflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static long? GetUnderflowInt64(this IIntModel operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt64Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<long?> GetUnderflowInt64Async(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetUnderflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put max int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMax32(this IIntModel operations, int intBody) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).PutMax32Async(intBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PutMax32Async(this IIntModel operations, int intBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PutMax32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put max int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMax64(this IIntModel operations, long intBody) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).PutMax64Async(intBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PutMax64Async(this IIntModel operations, long intBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PutMax64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put min int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMin32(this IIntModel operations, int intBody) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).PutMin32Async(intBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PutMin32Async(this IIntModel operations, int intBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PutMin32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put min int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMin64(this IIntModel operations, long intBody) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).PutMin64Async(intBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PutMin64Async(this IIntModel operations, long intBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PutMin64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get datetime encoded as Unix time value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetUnixTime(this IIntModel operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetUnixTimeAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get datetime encoded as Unix time value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.DateTime?> GetUnixTimeAsync(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put datetime encoded as Unix time /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutUnixTimeDate(this IIntModel operations, System.DateTime intBody) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).PutUnixTimeDateAsync(intBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put datetime encoded as Unix time /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PutUnixTimeDateAsync(this IIntModel operations, System.DateTime intBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PutUnixTimeDateWithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get invalid Unix time value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetInvalidUnixTime(this IIntModel operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidUnixTimeAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid Unix time value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.DateTime?> GetInvalidUnixTimeAsync(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetInvalidUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get null Unix time value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetNullUnixTime(this IIntModel operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetNullUnixTimeAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get null Unix time value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.DateTime?> GetNullUnixTimeAsync(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetNullUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
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 Samples.RegistrationList.Web.Areas.HelpPage.ModelDescriptions; using Samples.RegistrationList.Web.Areas.HelpPage.Models; namespace Samples.RegistrationList.Web.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); } } } }
/* * [The "BSD license"] * Copyright (c) 2013 Terence Parr * Copyright (c) 2013 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.Text; using Antlr4.Runtime; using Antlr4.Runtime.Atn; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Sharpen; namespace Antlr4.Runtime.Atn { /// <summary>A tuple: (ATN state, predicted alt, syntactic, semantic context).</summary> /// <remarks> /// A tuple: (ATN state, predicted alt, syntactic, semantic context). /// The syntactic context is a graph-structured stack node whose /// path(s) to the root is the rule invocation(s) /// chain used to arrive at the state. The semantic context is /// the tree of semantic predicates encountered before reaching /// an ATN state. /// </remarks> public class ATNConfig { /// <summary> /// This field stores the bit mask for implementing the /// <see cref="PrecedenceFilterSuppressed()"/> /// property as a bit within the /// existing /// <see cref="altAndOuterContextDepth"/> /// field. /// </summary> private const int SuppressPrecedenceFilter = unchecked((int)(0x80000000)); /// <summary>The ATN state associated with this configuration</summary> [NotNull] private readonly ATNState state; /// <summary>This is a bit-field currently containing the following values.</summary> /// <remarks> /// This is a bit-field currently containing the following values. /// <ul> /// <li>0x00FFFFFF: Alternative</li> /// <li>0x7F000000: Outer context depth</li> /// <li>0x80000000: Suppress precedence filter</li> /// </ul> /// </remarks> private int altAndOuterContextDepth; /// <summary> /// The stack of invoking states leading to the rule/states associated /// with this config. /// </summary> /// <remarks> /// The stack of invoking states leading to the rule/states associated /// with this config. We track only those contexts pushed during /// execution of the ATN simulator. /// </remarks> [NotNull] private PredictionContext context; protected internal ATNConfig(ATNState state, int alt, PredictionContext context) { System.Diagnostics.Debug.Assert((alt & unchecked((int)(0xFFFFFF))) == alt); this.state = state; this.altAndOuterContextDepth = alt; this.context = context; } protected internal ATNConfig(Antlr4.Runtime.Atn.ATNConfig c, ATNState state, PredictionContext context) { this.state = state; this.altAndOuterContextDepth = c.altAndOuterContextDepth; this.context = context; } public static Antlr4.Runtime.Atn.ATNConfig Create(ATNState state, int alt, PredictionContext context) { return Create(state, alt, context, Antlr4.Runtime.Atn.SemanticContext.None, null); } public static Antlr4.Runtime.Atn.ATNConfig Create(ATNState state, int alt, PredictionContext context, Antlr4.Runtime.Atn.SemanticContext semanticContext) { return Create(state, alt, context, semanticContext, null); } public static Antlr4.Runtime.Atn.ATNConfig Create(ATNState state, int alt, PredictionContext context, Antlr4.Runtime.Atn.SemanticContext semanticContext, LexerActionExecutor lexerActionExecutor) { if (semanticContext != Antlr4.Runtime.Atn.SemanticContext.None) { if (lexerActionExecutor != null) { return new ATNConfig.ActionSemanticContextATNConfig(lexerActionExecutor, semanticContext, state, alt, context, false); } else { return new ATNConfig.SemanticContextATNConfig(semanticContext, state, alt, context); } } else { if (lexerActionExecutor != null) { return new ATNConfig.ActionATNConfig(lexerActionExecutor, state, alt, context, false); } else { return new Antlr4.Runtime.Atn.ATNConfig(state, alt, context); } } } /// <summary>Gets the ATN state associated with this configuration.</summary> /// <remarks>Gets the ATN state associated with this configuration.</remarks> public ATNState State { get { return state; } } /// <summary>What alt (or lexer rule) is predicted by this configuration.</summary> /// <remarks>What alt (or lexer rule) is predicted by this configuration.</remarks> public int Alt { get { return altAndOuterContextDepth & unchecked((int)(0x00FFFFFF)); } } public virtual PredictionContext Context { get { return context; } set { PredictionContext context = value; this.context = context; } } public bool ReachesIntoOuterContext { get { return OuterContextDepth != 0; } } /// <summary> /// We cannot execute predicates dependent upon local context unless /// we know for sure we are in the correct context. /// </summary> /// <remarks> /// We cannot execute predicates dependent upon local context unless /// we know for sure we are in the correct context. Because there is /// no way to do this efficiently, we simply cannot evaluate /// dependent predicates unless we are in the rule that initially /// invokes the ATN simulator. /// <p> /// closure() tracks the depth of how far we dip into the outer context: /// depth &gt; 0. Note that it may not be totally accurate depth since I /// don't ever decrement. TODO: make it a boolean then</p> /// </remarks> public virtual int OuterContextDepth { get { return ((int)(((uint)altAndOuterContextDepth) >> 24)) & unchecked((int)(0x7F)); } set { int outerContextDepth = value; System.Diagnostics.Debug.Assert(outerContextDepth >= 0); // saturate at 0x7F - everything but zero/positive is only used for debug information anyway outerContextDepth = Math.Min(outerContextDepth, unchecked((int)(0x7F))); this.altAndOuterContextDepth = (outerContextDepth << 24) | (altAndOuterContextDepth & ~unchecked((int)(0x7F000000))); } } public virtual LexerActionExecutor ActionExecutor { get { return null; } } public virtual Antlr4.Runtime.Atn.SemanticContext SemanticContext { get { return Antlr4.Runtime.Atn.SemanticContext.None; } } public virtual bool PassedThroughNonGreedyDecision { get { return false; } } public Antlr4.Runtime.Atn.ATNConfig Clone() { return Transform(this.State, false); } public Antlr4.Runtime.Atn.ATNConfig Transform(ATNState state, bool checkNonGreedy) { return Transform(state, this.context, this.SemanticContext, checkNonGreedy, this.ActionExecutor); } public Antlr4.Runtime.Atn.ATNConfig Transform(ATNState state, Antlr4.Runtime.Atn.SemanticContext semanticContext, bool checkNonGreedy) { return Transform(state, this.context, semanticContext, checkNonGreedy, this.ActionExecutor); } public Antlr4.Runtime.Atn.ATNConfig Transform(ATNState state, PredictionContext context, bool checkNonGreedy) { return Transform(state, context, this.SemanticContext, checkNonGreedy, this.ActionExecutor); } public Antlr4.Runtime.Atn.ATNConfig Transform(ATNState state, LexerActionExecutor lexerActionExecutor, bool checkNonGreedy) { return Transform(state, context, this.SemanticContext, checkNonGreedy, lexerActionExecutor); } private Antlr4.Runtime.Atn.ATNConfig Transform(ATNState state, PredictionContext context, Antlr4.Runtime.Atn.SemanticContext semanticContext, bool checkNonGreedy, LexerActionExecutor lexerActionExecutor) { bool passedThroughNonGreedy = checkNonGreedy && CheckNonGreedyDecision(this, state); if (semanticContext != Antlr4.Runtime.Atn.SemanticContext.None) { if (lexerActionExecutor != null || passedThroughNonGreedy) { return new ATNConfig.ActionSemanticContextATNConfig(lexerActionExecutor, semanticContext, this, state, context, passedThroughNonGreedy); } else { return new ATNConfig.SemanticContextATNConfig(semanticContext, this, state, context); } } else { if (lexerActionExecutor != null || passedThroughNonGreedy) { return new ATNConfig.ActionATNConfig(lexerActionExecutor, this, state, context, passedThroughNonGreedy); } else { return new Antlr4.Runtime.Atn.ATNConfig(this, state, context); } } } private static bool CheckNonGreedyDecision(Antlr4.Runtime.Atn.ATNConfig source, ATNState target) { return source.PassedThroughNonGreedyDecision || target is DecisionState && ((DecisionState)target).nonGreedy; } public virtual Antlr4.Runtime.Atn.ATNConfig AppendContext(int context, PredictionContextCache contextCache) { PredictionContext appendedContext = Context.AppendContext(context, contextCache); Antlr4.Runtime.Atn.ATNConfig result = Transform(State, appendedContext, false); return result; } public virtual Antlr4.Runtime.Atn.ATNConfig AppendContext(PredictionContext context, PredictionContextCache contextCache) { PredictionContext appendedContext = Context.AppendContext(context, contextCache); Antlr4.Runtime.Atn.ATNConfig result = Transform(State, appendedContext, false); return result; } public virtual bool Contains(Antlr4.Runtime.Atn.ATNConfig subconfig) { if (this.state.stateNumber != subconfig.State.stateNumber || this.Alt != subconfig.Alt || !this.SemanticContext.Equals(subconfig.SemanticContext)) { return false; } Stack<PredictionContext> leftWorkList = new Stack<PredictionContext>(); Stack<PredictionContext> rightWorkList = new Stack<PredictionContext>(); leftWorkList.Push(Context); rightWorkList.Push(subconfig.Context); while (leftWorkList.Count > 0) { PredictionContext left = leftWorkList.Pop(); PredictionContext right = rightWorkList.Pop(); if (left == right) { return true; } if (left.Size < right.Size) { return false; } if (right.IsEmpty) { return left.HasEmpty; } else { for (int i = 0; i < right.Size; i++) { int index = left.FindReturnState(right.GetReturnState(i)); if (index < 0) { // assumes invokingStates has no duplicate entries return false; } leftWorkList.Push(left.GetParent(index)); rightWorkList.Push(right.GetParent(i)); } } } return false; } public bool PrecedenceFilterSuppressed { get { return (altAndOuterContextDepth & SuppressPrecedenceFilter) != 0; } set { if (value) { this.altAndOuterContextDepth |= SuppressPrecedenceFilter; } else { this.altAndOuterContextDepth &= ~SuppressPrecedenceFilter; } } } /// <summary> /// An ATN configuration is equal to another if both have /// the same state, they predict the same alternative, and /// syntactic/semantic contexts are the same. /// </summary> /// <remarks> /// An ATN configuration is equal to another if both have /// the same state, they predict the same alternative, and /// syntactic/semantic contexts are the same. /// </remarks> public override bool Equals(object o) { if (!(o is Antlr4.Runtime.Atn.ATNConfig)) { return false; } return this.Equals((Antlr4.Runtime.Atn.ATNConfig)o); } public virtual bool Equals(Antlr4.Runtime.Atn.ATNConfig other) { if (this == other) { return true; } else { if (other == null) { return false; } } return this.State.stateNumber == other.State.stateNumber && this.Alt == other.Alt && this.ReachesIntoOuterContext == other.ReachesIntoOuterContext && this.Context.Equals(other.Context) && this.SemanticContext.Equals(other.SemanticContext) && this.PrecedenceFilterSuppressed == other.PrecedenceFilterSuppressed && this.PassedThroughNonGreedyDecision == other.PassedThroughNonGreedyDecision && EqualityComparer<LexerActionExecutor>.Default.Equals(this.ActionExecutor, other.ActionExecutor); } public override int GetHashCode() { int hashCode = MurmurHash.Initialize(7); hashCode = MurmurHash.Update(hashCode, State.stateNumber); hashCode = MurmurHash.Update(hashCode, Alt); hashCode = MurmurHash.Update(hashCode, ReachesIntoOuterContext ? 1 : 0); hashCode = MurmurHash.Update(hashCode, Context); hashCode = MurmurHash.Update(hashCode, SemanticContext); hashCode = MurmurHash.Update(hashCode, PassedThroughNonGreedyDecision ? 1 : 0); hashCode = MurmurHash.Update(hashCode, ActionExecutor); hashCode = MurmurHash.Finish(hashCode, 7); return hashCode; } public virtual string ToDotString() { #if COMPACT throw new NotImplementedException("The current platform does not provide RuntimeHelpers.GetHashCode(object)."); #else StringBuilder builder = new StringBuilder(); builder.Append("digraph G {\n"); builder.Append("rankdir=LR;\n"); HashSet<PredictionContext> visited = new HashSet<PredictionContext>(); Stack<PredictionContext> workList = new Stack<PredictionContext>(); workList.Push(Context); visited.Add(Context); while (workList.Count > 0) { PredictionContext current = workList.Pop(); for (int i = 0; i < current.Size; i++) { builder.Append(" s").Append(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(current)); builder.Append("->"); builder.Append("s").Append(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(current.GetParent(i))); builder.Append("[label=\"").Append(current.GetReturnState(i)).Append("\"];\n"); if (visited.Add(current.GetParent(i))) { workList.Push(current.GetParent(i)); } } } builder.Append("}\n"); return builder.ToString(); #endif } public override string ToString() { return ToString(null, true, false); } public virtual string ToString(IRecognizer recog, bool showAlt) { return ToString(recog, showAlt, true); } public virtual string ToString(IRecognizer recog, bool showAlt, bool showContext) { StringBuilder buf = new StringBuilder(); // if ( state.ruleIndex>=0 ) { // if ( recog!=null ) buf.append(recog.getRuleNames()[state.ruleIndex]+":"); // else buf.append(state.ruleIndex+":"); // } string[] contexts; if (showContext) { contexts = Context.ToStrings(recog, this.State.stateNumber); } else { contexts = new string[] { "?" }; } bool first = true; foreach (string contextDesc in contexts) { if (first) { first = false; } else { buf.Append(", "); } buf.Append('('); buf.Append(State); if (showAlt) { buf.Append(","); buf.Append(Alt); } if (Context != null) { buf.Append(","); buf.Append(contextDesc); } if (SemanticContext != null && SemanticContext != Antlr4.Runtime.Atn.SemanticContext.None) { buf.Append(","); buf.Append(SemanticContext); } if (ReachesIntoOuterContext) { buf.Append(",up=").Append(OuterContextDepth); } buf.Append(')'); } return buf.ToString(); } private class SemanticContextATNConfig : ATNConfig { [NotNull] private readonly Antlr4.Runtime.Atn.SemanticContext semanticContext; public SemanticContextATNConfig(Antlr4.Runtime.Atn.SemanticContext semanticContext, ATNState state, int alt, PredictionContext context) : base(state, alt, context) { this.semanticContext = semanticContext; } public SemanticContextATNConfig(Antlr4.Runtime.Atn.SemanticContext semanticContext, ATNConfig c, ATNState state, PredictionContext context) : base(c, state, context) { this.semanticContext = semanticContext; } public override Antlr4.Runtime.Atn.SemanticContext SemanticContext { get { return semanticContext; } } } private class ActionATNConfig : ATNConfig { private readonly LexerActionExecutor lexerActionExecutor; private readonly bool passedThroughNonGreedyDecision; public ActionATNConfig(LexerActionExecutor lexerActionExecutor, ATNState state, int alt, PredictionContext context, bool passedThroughNonGreedyDecision) : base(state, alt, context) { this.lexerActionExecutor = lexerActionExecutor; this.passedThroughNonGreedyDecision = passedThroughNonGreedyDecision; } protected internal ActionATNConfig(LexerActionExecutor lexerActionExecutor, ATNConfig c, ATNState state, PredictionContext context, bool passedThroughNonGreedyDecision) : base(c, state, context) { if (c.SemanticContext != SemanticContext.None) { throw new NotSupportedException(); } this.lexerActionExecutor = lexerActionExecutor; this.passedThroughNonGreedyDecision = passedThroughNonGreedyDecision; } public override LexerActionExecutor ActionExecutor { get { return lexerActionExecutor; } } public override bool PassedThroughNonGreedyDecision { get { return passedThroughNonGreedyDecision; } } } private class ActionSemanticContextATNConfig : ATNConfig.SemanticContextATNConfig { private readonly LexerActionExecutor lexerActionExecutor; private readonly bool passedThroughNonGreedyDecision; public ActionSemanticContextATNConfig(LexerActionExecutor lexerActionExecutor, SemanticContext semanticContext, ATNState state, int alt, PredictionContext context, bool passedThroughNonGreedyDecision) : base(semanticContext, state, alt, context) { this.lexerActionExecutor = lexerActionExecutor; this.passedThroughNonGreedyDecision = passedThroughNonGreedyDecision; } public ActionSemanticContextATNConfig(LexerActionExecutor lexerActionExecutor, SemanticContext semanticContext, ATNConfig c, ATNState state, PredictionContext context, bool passedThroughNonGreedyDecision) : base(semanticContext, c, state, context) { this.lexerActionExecutor = lexerActionExecutor; this.passedThroughNonGreedyDecision = passedThroughNonGreedyDecision; } public override LexerActionExecutor ActionExecutor { get { return lexerActionExecutor; } } public override bool PassedThroughNonGreedyDecision { get { return passedThroughNonGreedyDecision; } } } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Web; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web; using Umbraco.ModelsBuilder; using Umbraco.ModelsBuilder.Umbraco; [assembly: PureLiveAssembly] [assembly:ModelsBuilderAssembly(PureLive = true, SourceHash = "c78a81249667a243")] [assembly:System.Reflection.AssemblyVersion("0.0.0.1")] // FILE: models.generated.cs //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Umbraco.ModelsBuilder v3.0.7.99 // // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Umbraco.Web.PublishedContentModels { /// <summary>Home</summary> [PublishedContentModel("home")] public partial class Home : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "home"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public Home(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Home, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Heading ///</summary> [ImplementPropertyType("heading")] public string Heading { get { return this.GetPropertyValue<string>("heading"); } } ///<summary> /// Subheading ///</summary> [ImplementPropertyType("subheading")] public string Subheading { get { return this.GetPropertyValue<string>("subheading"); } } } /// <summary>Header</summary> [PublishedContentModel("header")] public partial class Header : Home { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "header"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public Header(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Header, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } } /// <summary>Navigation Link</summary> [PublishedContentModel("navigationLink")] public partial class NavigationLink : Home { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "navigationLink"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public NavigationLink(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<NavigationLink, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// URL ///</summary> [ImplementPropertyType("linkURL")] public string LinkUrl { get { return this.GetPropertyValue<string>("linkURL"); } } } /// <summary>Section</summary> [PublishedContentModel("page")] public partial class Page : Home { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "page"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public Page(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Page, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Content ///</summary> [ImplementPropertyType("content")] public IHtmlString Content { get { return this.GetPropertyValue<IHtmlString>("content"); } } } /// <summary>Project</summary> [PublishedContentModel("project")] public partial class Project : Home { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "project"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public Project(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Project, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Code URL ///</summary> [ImplementPropertyType("codeURL")] public string CodeUrl { get { return this.GetPropertyValue<string>("codeURL"); } } ///<summary> /// Content ///</summary> [ImplementPropertyType("content")] public IHtmlString Content { get { return this.GetPropertyValue<IHtmlString>("content"); } } ///<summary> /// Demo URL ///</summary> [ImplementPropertyType("demoURL")] public string DemoUrl { get { return this.GetPropertyValue<string>("demoURL"); } } ///<summary> /// Image ///</summary> [ImplementPropertyType("image")] public IPublishedContent Image { get { return this.GetPropertyValue<IPublishedContent>("image"); } } } /// <summary>Web Page</summary> [PublishedContentModel("webPage")] public partial class WebPage : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "webPage"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public WebPage(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<WebPage, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Background Color ///</summary> [ImplementPropertyType("backgroundColor")] public string BackgroundColor { get { return this.GetPropertyValue<string>("backgroundColor"); } } ///<summary> /// Key Color ///</summary> [ImplementPropertyType("keyColor")] public string KeyColor { get { return this.GetPropertyValue<string>("keyColor"); } } ///<summary> /// Mountain Dark Color ///</summary> [ImplementPropertyType("mountainDarkColor")] public string MountainDarkColor { get { return this.GetPropertyValue<string>("mountainDarkColor"); } } ///<summary> /// Mountain Shadow Color ///</summary> [ImplementPropertyType("mountainShadowColor")] public string MountainShadowColor { get { return this.GetPropertyValue<string>("mountainShadowColor"); } } ///<summary> /// Secondary Color ///</summary> [ImplementPropertyType("secondaryColor")] public string SecondaryColor { get { return this.GetPropertyValue<string>("secondaryColor"); } } ///<summary> /// Sky Greadient: Paste hex color values comma separated, https://codepen.io/zessx/pen/rDEAl/ ///</summary> [ImplementPropertyType("skyGreadient")] public string SkyGreadient { get { return this.GetPropertyValue<string>("skyGreadient"); } } } /// <summary>Skill</summary> [PublishedContentModel("skill")] public partial class Skill : Home { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "skill"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public Skill(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Skill, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Content ///</summary> [ImplementPropertyType("content")] public IHtmlString Content { get { return this.GetPropertyValue<IHtmlString>("content"); } } ///<summary> /// Image ///</summary> [ImplementPropertyType("image")] public IPublishedContent Image { get { return this.GetPropertyValue<IPublishedContent>("image"); } } ///<summary> /// Years ///</summary> [ImplementPropertyType("years")] public int Years { get { return this.GetPropertyValue<int>("years"); } } } /// <summary>Folder</summary> [PublishedContentModel("Folder")] public partial class Folder : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "Folder"; public new const PublishedItemType ModelItemType = PublishedItemType.Media; #pragma warning restore 0109 public Folder(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Folder, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Contents: ///</summary> [ImplementPropertyType("contents")] public object Contents { get { return this.GetPropertyValue("contents"); } } } /// <summary>Image</summary> [PublishedContentModel("Image")] public partial class Image : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "Image"; public new const PublishedItemType ModelItemType = PublishedItemType.Media; #pragma warning restore 0109 public Image(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Image, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Size ///</summary> [ImplementPropertyType("umbracoBytes")] public string UmbracoBytes { get { return this.GetPropertyValue<string>("umbracoBytes"); } } ///<summary> /// Type ///</summary> [ImplementPropertyType("umbracoExtension")] public string UmbracoExtension { get { return this.GetPropertyValue<string>("umbracoExtension"); } } ///<summary> /// Upload image ///</summary> [ImplementPropertyType("umbracoFile")] public Umbraco.Web.Models.ImageCropDataSet UmbracoFile { get { return this.GetPropertyValue<Umbraco.Web.Models.ImageCropDataSet>("umbracoFile"); } } ///<summary> /// Height ///</summary> [ImplementPropertyType("umbracoHeight")] public string UmbracoHeight { get { return this.GetPropertyValue<string>("umbracoHeight"); } } ///<summary> /// Width ///</summary> [ImplementPropertyType("umbracoWidth")] public string UmbracoWidth { get { return this.GetPropertyValue<string>("umbracoWidth"); } } } /// <summary>File</summary> [PublishedContentModel("File")] public partial class File : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "File"; public new const PublishedItemType ModelItemType = PublishedItemType.Media; #pragma warning restore 0109 public File(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<File, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Size ///</summary> [ImplementPropertyType("umbracoBytes")] public string UmbracoBytes { get { return this.GetPropertyValue<string>("umbracoBytes"); } } ///<summary> /// Type ///</summary> [ImplementPropertyType("umbracoExtension")] public string UmbracoExtension { get { return this.GetPropertyValue<string>("umbracoExtension"); } } ///<summary> /// Upload file ///</summary> [ImplementPropertyType("umbracoFile")] public string UmbracoFile { get { return this.GetPropertyValue<string>("umbracoFile"); } } } /// <summary>Member</summary> [PublishedContentModel("Member")] public partial class Member : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "Member"; public new const PublishedItemType ModelItemType = PublishedItemType.Member; #pragma warning restore 0109 public Member(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Member, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Is Approved ///</summary> [ImplementPropertyType("umbracoMemberApproved")] public bool UmbracoMemberApproved { get { return this.GetPropertyValue<bool>("umbracoMemberApproved"); } } ///<summary> /// Comments ///</summary> [ImplementPropertyType("umbracoMemberComments")] public string UmbracoMemberComments { get { return this.GetPropertyValue<string>("umbracoMemberComments"); } } ///<summary> /// Failed Password Attempts ///</summary> [ImplementPropertyType("umbracoMemberFailedPasswordAttempts")] public string UmbracoMemberFailedPasswordAttempts { get { return this.GetPropertyValue<string>("umbracoMemberFailedPasswordAttempts"); } } ///<summary> /// Last Lockout Date ///</summary> [ImplementPropertyType("umbracoMemberLastLockoutDate")] public string UmbracoMemberLastLockoutDate { get { return this.GetPropertyValue<string>("umbracoMemberLastLockoutDate"); } } ///<summary> /// Last Login Date ///</summary> [ImplementPropertyType("umbracoMemberLastLogin")] public string UmbracoMemberLastLogin { get { return this.GetPropertyValue<string>("umbracoMemberLastLogin"); } } ///<summary> /// Last Password Change Date ///</summary> [ImplementPropertyType("umbracoMemberLastPasswordChangeDate")] public string UmbracoMemberLastPasswordChangeDate { get { return this.GetPropertyValue<string>("umbracoMemberLastPasswordChangeDate"); } } ///<summary> /// Is Locked Out ///</summary> [ImplementPropertyType("umbracoMemberLockedOut")] public bool UmbracoMemberLockedOut { get { return this.GetPropertyValue<bool>("umbracoMemberLockedOut"); } } ///<summary> /// Password Answer ///</summary> [ImplementPropertyType("umbracoMemberPasswordRetrievalAnswer")] public string UmbracoMemberPasswordRetrievalAnswer { get { return this.GetPropertyValue<string>("umbracoMemberPasswordRetrievalAnswer"); } } ///<summary> /// Password Question ///</summary> [ImplementPropertyType("umbracoMemberPasswordRetrievalQuestion")] public string UmbracoMemberPasswordRetrievalQuestion { get { return this.GetPropertyValue<string>("umbracoMemberPasswordRetrievalQuestion"); } } } } // EOF
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; using System.Net.Security; using System.Runtime.InteropServices; namespace System.Net { // Authentication SSPI (Kerberos, NTLM, Negotiate and WDigest): internal class SSPIAuthType : SSPIInterface { private static volatile SecurityPackageInfoClass[] s_securityPackages; public SecurityPackageInfoClass[] SecurityPackages { get { return s_securityPackages; } set { s_securityPackages = value; } } public int EnumerateSecurityPackages(out int pkgnum, out SafeFreeContextBuffer pkgArray) { GlobalLog.Print("SSPIAuthType::EnumerateSecurityPackages()"); return SafeFreeContextBuffer.EnumeratePackages(out pkgnum, out pkgArray); } public int AcquireCredentialsHandle(string moduleName, Interop.SspiCli.CredentialUse usage, ref Interop.SspiCli.AuthIdentity authdata, out SafeFreeCredentials outCredential) { return SafeFreeCredentials.AcquireCredentialsHandle(moduleName, usage, ref authdata, out outCredential); } public int AcquireCredentialsHandle(string moduleName, Interop.SspiCli.CredentialUse usage, ref SafeSspiAuthDataHandle authdata, out SafeFreeCredentials outCredential) { return SafeFreeCredentials.AcquireCredentialsHandle(moduleName, usage, ref authdata, out outCredential); } public int AcquireDefaultCredential(string moduleName, Interop.SspiCli.CredentialUse usage, out SafeFreeCredentials outCredential) { return SafeFreeCredentials.AcquireDefaultCredential(moduleName, usage, out outCredential); } public int AcquireCredentialsHandle(string moduleName, Interop.SspiCli.CredentialUse usage, ref Interop.SspiCli.SecureCredential authdata, out SafeFreeCredentials outCredential) { return SafeFreeCredentials.AcquireCredentialsHandle(moduleName, usage, ref authdata, out outCredential); } public int AcceptSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer inputBuffer, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) { return SafeDeleteContext.AcceptSecurityContext(ref credential, ref context, inFlags, endianness, inputBuffer, null, outputBuffer, ref outFlags); } public int AcceptSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer[] inputBuffers, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) { return SafeDeleteContext.AcceptSecurityContext(ref credential, ref context, inFlags, endianness, null, inputBuffers, outputBuffer, ref outFlags); } public int InitializeSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) { return SafeDeleteContext.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, endianness, inputBuffer, null, outputBuffer, ref outFlags); } public int InitializeSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) { return SafeDeleteContext.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, endianness, null, inputBuffers, outputBuffer, ref outFlags); } public int EncryptMessage(SafeDeleteContext context, Interop.SspiCli.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { try { bool ignore = false; context.DangerousAddRef(ref ignore); return Interop.SspiCli.EncryptMessage(ref context._handle, 0, inputOutput, sequenceNumber); } finally { context.DangerousRelease(); } } public unsafe int DecryptMessage(SafeDeleteContext context, Interop.SspiCli.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { int status = (int)Interop.SecurityStatus.InvalidHandle; uint qop = 0; try { bool ignore = false; context.DangerousAddRef(ref ignore); status = Interop.SspiCli.DecryptMessage(ref context._handle, inputOutput, sequenceNumber, &qop); } finally { context.DangerousRelease(); } if (status == 0 && qop == Interop.SspiCli.SECQOP_WRAP_NO_ENCRYPT) { GlobalLog.Assert("SspiCli.DecryptMessage", "Expected qop = 0, returned value = " + qop.ToString("x", CultureInfo.InvariantCulture)); throw new InvalidOperationException(SR.net_auth_message_not_encrypted); } return status; } public int MakeSignature(SafeDeleteContext context, Interop.SspiCli.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { try { bool ignore = false; context.DangerousAddRef(ref ignore); return Interop.SspiCli.EncryptMessage(ref context._handle, Interop.SspiCli.SECQOP_WRAP_NO_ENCRYPT, inputOutput, sequenceNumber); } finally { context.DangerousRelease(); } } public unsafe int VerifySignature(SafeDeleteContext context, Interop.SspiCli.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { try { bool ignore = false; uint qop = 0; context.DangerousAddRef(ref ignore); return Interop.SspiCli.DecryptMessage(ref context._handle, inputOutput, sequenceNumber, &qop); } finally { context.DangerousRelease(); } } public int QueryContextChannelBinding(SafeDeleteContext context, Interop.SspiCli.ContextAttribute attribute, out SafeFreeContextBufferChannelBinding binding) { // Querying an auth SSP for a CBT is not supported. binding = null; throw new NotSupportedException(); } public unsafe int QueryContextAttributes(SafeDeleteContext context, Interop.SspiCli.ContextAttribute attribute, byte[] buffer, Type handleType, out SafeHandle refHandle) { refHandle = null; if (handleType != null) { if (handleType == typeof(SafeFreeContextBuffer)) { refHandle = SafeFreeContextBuffer.CreateEmptyHandle(); } else if (handleType == typeof(SafeFreeCertContext)) { refHandle = new SafeFreeCertContext(); } else { throw new ArgumentException(SR.Format(SR.SSPIInvalidHandleType, handleType.FullName), "handleType"); } } fixed (byte* bufferPtr = buffer) { return SafeFreeContextBuffer.QueryContextAttributes(context, attribute, bufferPtr, refHandle); } } public int SetContextAttributes(SafeDeleteContext context, Interop.SspiCli.ContextAttribute attribute, byte[] buffer) { throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); } public int QuerySecurityContextToken(SafeDeleteContext phContext, out SecurityContextTokenHandle phToken) { return GetSecurityContextToken(phContext, out phToken); } public int CompleteAuthToken(ref SafeDeleteContext refContext, SecurityBuffer[] inputBuffers) { return SafeDeleteContext.CompleteAuthToken(ref refContext, inputBuffers); } private static int GetSecurityContextToken(SafeDeleteContext phContext, out SecurityContextTokenHandle safeHandle) { safeHandle = null; try { bool ignore = false; phContext.DangerousAddRef(ref ignore); return Interop.SspiCli.QuerySecurityContextToken(ref phContext._handle, out safeHandle); } finally { phContext.DangerousRelease(); } } } }
/////////////////////////////////////////////////////////////////////////////// using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; /// /// BaseMachineEditor.cs /// /// (c)2014 Kim, Hyoun Woo /// /////////////////////////////////////////////////////////////////////////////// using UnityEngine; /// <summary></summary> [CustomEditor(typeof(BaseMachine))] public class BaseMachineEditor : Editor { protected BaseMachine machine; protected readonly string NoTemplateString = "No Template File Found"; protected virtual void Import(bool reimport = false) { Debug.LogWarning("!!! It should be implemented in the derived class !!!"); } /// <summary> /// Generate script files with the given templates. Total four files are generated, two for /// runtime and others for editor. /// </summary> protected virtual ScriptPrescription Generate(BaseMachine m) { if (m == null) return null; ScriptPrescription sp = new ScriptPrescription(); if (m.onlyCreateDataClass) { CreateDataClassScript(m, sp); } else { CreateScriptableObjectClassScript(m, sp); CreateScriptableObjectEditorClassScript(m, sp); CreateDataClassScript(m, sp); CreateAssetCreationScript(m, sp); } AssetDatabase.Refresh(); return sp; } /// <summary>Create a ScriptableObject class and write it down on the specified folder.</summary> protected void CreateScriptableObjectClassScript(BaseMachine machine, ScriptPrescription sp) { sp.className = machine.WorkSheetName; sp.dataClassName = machine.WorkSheetName + "Data"; sp.template = GetTemplate("ScriptableObjectClass"); // check the directory path exists string fullPath = TargetPathForClassScript(machine.WorkSheetName); string folderPath = Path.GetDirectoryName(fullPath); if (!Directory.Exists(folderPath)) { EditorUtility.DisplayDialog( "Warning", "The folder for runtime script files does not exist. Check the path " + folderPath + " exists.", "OK" ); return; } StreamWriter writer = null; try { // write a script to the given folder. writer = new StreamWriter(fullPath); writer.Write(new NewScriptGenerator(sp).ToString()); } catch (System.Exception e) { Debug.LogError(e); } finally { if (writer != null) { writer.Close(); writer.Dispose(); } } } /// <summary>Create a ScriptableObject editor class and write it down on the specified folder.</summary> protected void CreateScriptableObjectEditorClassScript(BaseMachine machine, ScriptPrescription sp) { sp.className = machine.WorkSheetName + "Editor"; sp.worksheetClassName = machine.WorkSheetName; sp.dataClassName = machine.WorkSheetName + "Data"; sp.template = GetTemplate("ScriptableObjectEditorClass"); // check the directory path exists string fullPath = TargetPathForEditorScript(machine.WorkSheetName); string folderPath = Path.GetDirectoryName(fullPath); if (!Directory.Exists(folderPath)) { EditorUtility.DisplayDialog( "Warning", "The folder for editor script files does not exist. Check the path " + folderPath + " exists.", "OK" ); return; } StreamWriter writer = null; try { // write a script to the given folder. writer = new StreamWriter(fullPath); writer.Write(new NewScriptGenerator(sp).ToString()); } catch (System.Exception e) { Debug.LogError(e); } finally { if (writer != null) { writer.Close(); writer.Dispose(); } } } /// <summary> /// Create a data class which describes the spreadsheet and write it down on the specified folder. /// </summary> protected void CreateDataClassScript(BaseMachine machine, ScriptPrescription sp) { // check the directory path exists string fullPath = TargetPathForData(machine.WorkSheetName); string folderPath = Path.GetDirectoryName(fullPath); if (!Directory.Exists(folderPath)) { EditorUtility.DisplayDialog( "Warning", "The folder for runtime script files does not exist. Check the path " + folderPath + " exists.", "OK" ); return; } List<MemberFieldData> fieldList = new List<MemberFieldData>(); //FIXME: replace ValueType to CellType and support Enum type. foreach (HeaderColumn header in machine.HeaderColumnList) { MemberFieldData member = new MemberFieldData(); member.Name = header.name; member.type = header.type; member.IsArrayType = header.isArray; fieldList.Add(member); } sp.className = machine.WorkSheetName + "Data"; sp.template = GetTemplate("DataClass"); sp.memberFields = fieldList.ToArray(); // write a script to the given folder. using (var writer = new StreamWriter(fullPath)) { writer.Write(new NewScriptGenerator(sp).ToString()); writer.Close(); } } protected virtual void CreateAssetCreationScript(BaseMachine m, ScriptPrescription sp) { Debug.LogWarning("!!! It should be implemented in the derived class !!!"); } /// <summary>e.g. "Assets/Script/Data/Runtime/Item.cs"</summary> protected string TargetPathForClassScript(string worksheetName) { return Path.Combine("Assets/" + machine.RuntimeClassPath, worksheetName + "." + "cs"); } /// <summary>e.g. "Assets/Script/Data/Editor/ItemEditor.cs"</summary> protected string TargetPathForEditorScript(string worksheetName) { return Path.Combine("Assets/" + machine.EditorClassPath, worksheetName + "Editor" + "." + "cs"); } /// <summary>data class script file has 'WorkSheetNameData' for its filename. e.g. "Assets/Script/Data/Runtime/ItemData.cs"</summary> protected string TargetPathForData(string worksheetName) { return Path.Combine("Assets/" + machine.RuntimeClassPath, worksheetName + "Data" + "." + "cs"); } /// <summary>e.g. "Assets/Script/Data/Editor/ItemAssetCreator.cs"</summary> protected string TargetPathForAssetFileCreateFunc(string worksheetName) { return Path.Combine("Assets/" + machine.EditorClassPath, worksheetName + "AssetCreator" + "." + "cs"); } /// <summary>AssetPostprocessor class should be under "Editor" folder.</summary> protected string TargetPathForAssetPostProcessorFile(string worksheetName) { return Path.Combine("Assets/" + machine.EditorClassPath, worksheetName + "AssetPostProcessor" + "." + "cs"); } /// <summary>Retrieves all ascii text in the given template file.</summary> protected string GetTemplate(string nameWithoutExtension) { string path = Path.Combine(GetAbsoluteCustomTemplatePath(), nameWithoutExtension + ".txt"); if (File.Exists(path)) return File.ReadAllText(path); path = Path.Combine(GetAbsoluteBuiltinTemplatePath(), nameWithoutExtension + ".txt"); if (File.Exists(path)) return File.ReadAllText(path); return NoTemplateString; } /// <summary>e.g. "Assets/QuickSheet/Templates"</summary> protected string GetAbsoluteCustomTemplatePath() { return Path.Combine(Application.dataPath, machine.TemplatePath); } /// <summary>e.g. "C:/Program File(x86)/Unity/Editor/Data"</summary> protected string GetAbsoluteBuiltinTemplatePath() { return Path.Combine(EditorApplication.applicationContentsPath, machine.TemplatePath); } protected void DrawHeaderSetting(BaseMachine m) { if (m.HasHeadColumn()) { //EditorGUILayout.LabelField("type settings"); GUIStyle headerStyle = GUIHelper.MakeHeader(); GUILayout.Label("Type Settings:", headerStyle); //curretScroll = EditorGUILayout.BeginScrollView(curretScroll, false, false); EditorGUILayout.BeginVertical("box"); //string lastCellName = string.Empty; foreach (HeaderColumn header in m.HeaderColumnList) { GUILayout.BeginHorizontal(); EditorGUILayout.LabelField(header.name, GUILayout.MaxWidth(250)); header.type = (CellType)EditorGUILayout.EnumPopup(header.type, GUILayout.MaxWidth(150)); GUILayout.Space(20); EditorGUILayout.LabelField("array:", GUILayout.MaxWidth(40)); header.isArray = EditorGUILayout.Toggle(header.isArray, GUILayout.MaxWidth(50)); GUILayout.EndHorizontal(); } EditorGUILayout.EndVertical(); //EditorGUILayout.EndScrollView(); } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using org.swyn.foundation.utils; namespace tdbadmin { /// <summary> /// Summary description for Country. /// </summary> public class FCur : System.Windows.Forms.Form { private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox TDB_abgrp; private System.Windows.Forms.Button TDB_ab_clr; private System.Windows.Forms.Button TDB_ab_sel; private System.Windows.Forms.Button TDB_ab_exit; private System.Windows.Forms.Button TDB_ab_del; private System.Windows.Forms.Button TDB_ab_upd; private System.Windows.Forms.Button TDB_ab_ins; private System.Windows.Forms.Label tdb_e_id; private System.Windows.Forms.TextBox tdb_e_bez; private System.Windows.Forms.TextBox tdb_e_code; private System.Windows.Forms.TextBox tdb_e_text; private System.Windows.Forms.Label tdb_l_text; private System.Windows.Forms.Label tdb_l_code; private System.Windows.Forms.Label tdb_l_bez; private System.Windows.Forms.Label tdb_l_id; private tdbgui.GUIcur Cur; private System.Windows.Forms.ComboBox Whr_e_sta; private System.Windows.Forms.Label Whr_l_sta; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public FCur() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // Cur = new tdbgui.GUIcur(); } /// <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.groupBox1 = new System.Windows.Forms.GroupBox(); this.tdb_e_id = new System.Windows.Forms.Label(); this.Whr_l_sta = new System.Windows.Forms.Label(); this.Whr_e_sta = new System.Windows.Forms.ComboBox(); this.tdb_e_bez = new System.Windows.Forms.TextBox(); this.tdb_e_code = new System.Windows.Forms.TextBox(); this.tdb_e_text = new System.Windows.Forms.TextBox(); this.tdb_l_text = new System.Windows.Forms.Label(); this.tdb_l_code = new System.Windows.Forms.Label(); this.tdb_l_bez = new System.Windows.Forms.Label(); this.tdb_l_id = new System.Windows.Forms.Label(); this.TDB_abgrp = new System.Windows.Forms.GroupBox(); this.TDB_ab_clr = new System.Windows.Forms.Button(); this.TDB_ab_sel = new System.Windows.Forms.Button(); this.TDB_ab_exit = new System.Windows.Forms.Button(); this.TDB_ab_del = new System.Windows.Forms.Button(); this.TDB_ab_upd = new System.Windows.Forms.Button(); this.TDB_ab_ins = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.TDB_abgrp.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.Whr_e_sta); this.groupBox1.Controls.Add(this.Whr_l_sta); this.groupBox1.Controls.Add(this.tdb_e_id); this.groupBox1.Controls.Add(this.tdb_e_bez); this.groupBox1.Controls.Add(this.tdb_e_code); this.groupBox1.Controls.Add(this.tdb_e_text); this.groupBox1.Controls.Add(this.tdb_l_text); this.groupBox1.Controls.Add(this.tdb_l_code); this.groupBox1.Controls.Add(this.tdb_l_bez); this.groupBox1.Controls.Add(this.tdb_l_id); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox1.Location = new System.Drawing.Point(0, 0); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(608, 285); this.groupBox1.TabIndex = 13; this.groupBox1.TabStop = false; this.groupBox1.Text = "Description"; // // Whr_e_sta // this.Whr_e_sta.Location = new System.Drawing.Point(136, 192); this.Whr_e_sta.Name = "Whr_e_sta"; this.Whr_e_sta.Size = new System.Drawing.Size(256, 21); this.Whr_e_sta.TabIndex = 11; // // Whr_l_sta // this.Whr_l_sta.Location = new System.Drawing.Point(8, 192); this.Whr_l_sta.Name = "Whr_l_sta"; this.Whr_l_sta.TabIndex = 10; this.Whr_l_sta.Text = "Status"; // // tdb_e_id // this.tdb_e_id.Location = new System.Drawing.Point(136, 24); this.tdb_e_id.Name = "tdb_e_id"; this.tdb_e_id.Size = new System.Drawing.Size(64, 16); this.tdb_e_id.TabIndex = 9; // // tdb_e_bez // this.tdb_e_bez.Location = new System.Drawing.Point(136, 40); this.tdb_e_bez.Name = "tdb_e_bez"; this.tdb_e_bez.Size = new System.Drawing.Size(456, 20); this.tdb_e_bez.TabIndex = 0; this.tdb_e_bez.Text = ""; // // tdb_e_code // this.tdb_e_code.Location = new System.Drawing.Point(136, 64); this.tdb_e_code.Name = "tdb_e_code"; this.tdb_e_code.Size = new System.Drawing.Size(456, 20); this.tdb_e_code.TabIndex = 1; this.tdb_e_code.Text = ""; // // tdb_e_text // this.tdb_e_text.Location = new System.Drawing.Point(136, 88); this.tdb_e_text.Multiline = true; this.tdb_e_text.Name = "tdb_e_text"; this.tdb_e_text.Size = new System.Drawing.Size(456, 88); this.tdb_e_text.TabIndex = 2; this.tdb_e_text.Text = ""; // // tdb_l_text // this.tdb_l_text.Location = new System.Drawing.Point(8, 121); this.tdb_l_text.Name = "tdb_l_text"; this.tdb_l_text.RightToLeft = System.Windows.Forms.RightToLeft.No; this.tdb_l_text.TabIndex = 4; this.tdb_l_text.Text = "Description"; // // tdb_l_code // this.tdb_l_code.Location = new System.Drawing.Point(8, 63); this.tdb_l_code.Name = "tdb_l_code"; this.tdb_l_code.TabIndex = 3; this.tdb_l_code.Text = "Code"; // // tdb_l_bez // this.tdb_l_bez.Location = new System.Drawing.Point(8, 39); this.tdb_l_bez.Name = "tdb_l_bez"; this.tdb_l_bez.TabIndex = 2; this.tdb_l_bez.Text = "Title"; // // tdb_l_id // this.tdb_l_id.Location = new System.Drawing.Point(8, 21); this.tdb_l_id.Name = "tdb_l_id"; this.tdb_l_id.TabIndex = 1; this.tdb_l_id.Text = "ID"; // // TDB_abgrp // this.TDB_abgrp.Controls.Add(this.TDB_ab_clr); this.TDB_abgrp.Controls.Add(this.TDB_ab_sel); this.TDB_abgrp.Controls.Add(this.TDB_ab_exit); this.TDB_abgrp.Controls.Add(this.TDB_ab_del); this.TDB_abgrp.Controls.Add(this.TDB_ab_upd); this.TDB_abgrp.Controls.Add(this.TDB_ab_ins); this.TDB_abgrp.Dock = System.Windows.Forms.DockStyle.Bottom; this.TDB_abgrp.Location = new System.Drawing.Point(0, 232); this.TDB_abgrp.Name = "TDB_abgrp"; this.TDB_abgrp.Size = new System.Drawing.Size(608, 53); this.TDB_abgrp.TabIndex = 15; this.TDB_abgrp.TabStop = false; this.TDB_abgrp.Text = "Actions"; // // TDB_ab_clr // this.TDB_ab_clr.Dock = System.Windows.Forms.DockStyle.Right; this.TDB_ab_clr.Location = new System.Drawing.Point(455, 16); this.TDB_ab_clr.Name = "TDB_ab_clr"; this.TDB_ab_clr.Size = new System.Drawing.Size(75, 34); this.TDB_ab_clr.TabIndex = 10; this.TDB_ab_clr.Text = "Clear"; this.TDB_ab_clr.Click += new System.EventHandler(this.TDB_ab_clr_Click); // // TDB_ab_sel // this.TDB_ab_sel.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(192)), ((System.Byte)(255))); this.TDB_ab_sel.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_sel.Location = new System.Drawing.Point(228, 16); this.TDB_ab_sel.Name = "TDB_ab_sel"; this.TDB_ab_sel.Size = new System.Drawing.Size(80, 34); this.TDB_ab_sel.TabIndex = 8; this.TDB_ab_sel.Text = "Select"; this.TDB_ab_sel.Click += new System.EventHandler(this.TDB_ab_sel_Click); // // TDB_ab_exit // this.TDB_ab_exit.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_exit.Dock = System.Windows.Forms.DockStyle.Right; this.TDB_ab_exit.Location = new System.Drawing.Point(530, 16); this.TDB_ab_exit.Name = "TDB_ab_exit"; this.TDB_ab_exit.Size = new System.Drawing.Size(75, 34); this.TDB_ab_exit.TabIndex = 9; this.TDB_ab_exit.Text = "Exit"; this.TDB_ab_exit.Click += new System.EventHandler(this.TDB_ab_exit_Click); // // TDB_ab_del // this.TDB_ab_del.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_del.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_del.Location = new System.Drawing.Point(153, 16); this.TDB_ab_del.Name = "TDB_ab_del"; this.TDB_ab_del.Size = new System.Drawing.Size(75, 34); this.TDB_ab_del.TabIndex = 7; this.TDB_ab_del.Text = "Delete"; this.TDB_ab_del.Click += new System.EventHandler(this.TDB_ab_del_Click); // // TDB_ab_upd // this.TDB_ab_upd.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_upd.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_upd.Location = new System.Drawing.Point(78, 16); this.TDB_ab_upd.Name = "TDB_ab_upd"; this.TDB_ab_upd.Size = new System.Drawing.Size(75, 34); this.TDB_ab_upd.TabIndex = 6; this.TDB_ab_upd.Text = "Update"; this.TDB_ab_upd.Click += new System.EventHandler(this.TDB_ab_upd_Click); // // TDB_ab_ins // this.TDB_ab_ins.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_ins.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_ins.Location = new System.Drawing.Point(3, 16); this.TDB_ab_ins.Name = "TDB_ab_ins"; this.TDB_ab_ins.Size = new System.Drawing.Size(75, 34); this.TDB_ab_ins.TabIndex = 5; this.TDB_ab_ins.Text = "Insert"; this.TDB_ab_ins.Click += new System.EventHandler(this.TDB_ab_ins_Click); // // FCur // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(608, 285); this.Controls.Add(this.TDB_abgrp); this.Controls.Add(this.groupBox1); this.Name = "FCur"; this.Text = "Currency"; this.Load += new System.EventHandler(this.FPrg_Load); this.groupBox1.ResumeLayout(false); this.TDB_abgrp.ResumeLayout(false); this.ResumeLayout(false); } #endregion #region Form callbacks private void TDB_ab_sel_Click(object sender, System.EventArgs e) { SelForm Fsel = new SelForm(); Cur.Sel(Fsel.GetLV); Fsel.Accept += new EventHandler(TDB_ab_sel_Click_Return); Fsel.ShowDialog(this); } void TDB_ab_sel_Click_Return(object sender, EventArgs e) { int id = -1, rows = 0; SelForm Fsel = (SelForm)sender; id = Fsel.GetID; Cur.Get(id, ref rows); this.tdb_e_id.Text = Cur.ObjId.ToString(); this.tdb_e_bez.Text = Cur.ObjBez; this.tdb_e_code.Text = Cur.ObjCode; this.tdb_e_text.Text = Cur.ObjText; this.Whr_e_sta.SelectedValue = Cur.ObjStaid; } private void TDB_ab_exit_Click(object sender, System.EventArgs e) { Close(); } private void TDB_ab_ins_Click(object sender, System.EventArgs e) { Cur.InsUpd(true, tdb_e_bez.Text, tdb_e_code.Text, tdb_e_text.Text, (int)this.Whr_e_sta.SelectedValue); tdb_e_id.Text = Cur.ObjId.ToString(); } private void TDB_ab_upd_Click(object sender, System.EventArgs e) { Cur.InsUpd(false, tdb_e_bez.Text, tdb_e_code.Text, tdb_e_text.Text, (int)this.Whr_e_sta.SelectedValue); } private void TDB_ab_del_Click(object sender, System.EventArgs e) { int rows = 0; Cur.Get(Convert.ToInt32(tdb_e_id.Text), ref rows); Cur.Delete(); } private void TDB_ab_clr_Click(object sender, System.EventArgs e) { tdb_e_id.Text = ""; tdb_e_bez.Text = ""; tdb_e_code.Text = ""; tdb_e_text.Text = ""; } private void FPrg_Load(object sender, System.EventArgs e) { tdbgui.GUIsta S = new tdbgui.GUIsta(); S.ObjTyp = tdb.StatusTypes.stawhr; S.SetCombo(this.Whr_e_sta); } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Threading; using System.Windows.Forms; using mshtml; using OpenLiveWriter.Api; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.BlogClient.Detection; using OpenLiveWriter.CoreServices; using OpenLiveWriter.HtmlEditor; using OpenLiveWriter.Interop.Com; using OpenLiveWriter.Interop.Com.Ribbon; using OpenLiveWriter.Localization; using AsyncOperation = OpenLiveWriter.CoreServices.AsyncOperation; namespace OpenLiveWriter.PostEditor.Commands { public delegate string TemplateHtmlDelegate(); /// <summary> /// Asynchronously fetches gallery preview images for a particular blog and set of class ids /// </summary> internal class UpdateSemanticHtmlPreviewAsyncOperation : AsyncOperation { private readonly bool _isRtl; private readonly string _blogId; private readonly string[] _elementIds; private readonly string _html; private readonly int _previewImageWidth; private readonly int _previewImageHeight; private HtmlScreenCaptureCore _screenCapture; private readonly IBlogPostEditingSite _editingSite; internal string BlogId { get { return _blogId; } } private object _previewLock; internal UpdateSemanticHtmlPreviewAsyncOperation(IBlogPostEditingSite editingSite, string blogId, string[] elementIds, string templateHtml, string postBodyHtml, bool isRtl, ISynchronizeInvoke target, object previewLock, int previewImageWidth, int previewImageHeight) : base(target) { _blogId = blogId; _elementIds = elementIds; _isRtl = isRtl; _html = templateHtml.Replace(BlogEditingTemplate.POST_BODY_MARKER, postBodyHtml); _previewLock = previewLock; _previewImageWidth = previewImageWidth; _previewImageHeight = previewImageHeight; _editingSite = editingSite; } #region Overrides of AsyncOperation protected override void DoWork() { Trace.WriteLine("UpdateSemanticHtmlPreviewAsyncOperation started for blog(" + BlogId + ")"); Size newSize = new Size(1500, 1000); _screenCapture = new HtmlScreenCaptureCore(_html, newSize.Width); _screenCapture.Ids = _elementIds; _screenCapture.HtmlScreenCaptureAvailable += new HtmlScreenCaptureAvailableHandlerCore(screenCapture_HtmlScreenCaptureAvailable); _screenCapture.MaximumHeight = newSize.Height; _screenCapture.CaptureHtml(45000); } #endregion private void screenCapture_HtmlScreenCaptureAvailable(object sender, HtmlScreenCaptureAvailableEventArgsCore e) { if (e.CaptureCompleted && e.Bitmap != null) { // Ensure that the path exists try { // Problem because this check is pumping messages on bg thread? string directory = BlogEditingTemplate.GetBlogTemplateDir(_blogId); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); } catch (Exception ex) { Trace.Fail(ex.ToString()); return; } // Now we should have all of the element images foreach (string elementId in _screenCapture.Ids) { using (Bitmap elementBitmap = _screenCapture.GetElementCaptureProperties(elementId).Bitmap) { // Warning. elementBitmap may be null. string path = SemanticHtmlPreviewManager.GetPreviewBitmapPath(_blogId, elementId); try { // We take the lock here to ensure that we don't try to read a halfway-written file on the UI thread. lock (_previewLock) { ElementCaptureProperties properties = _screenCapture.GetElementCaptureProperties(elementId); using (Bitmap previewBitmap = GetGalleryPreviewImageFromElementImage(elementBitmap, _previewImageWidth, _previewImageHeight, properties.BackgroundColor, properties.Padding, _isRtl)) { previewBitmap.Save(path); } } } catch (Exception ex) { Trace.WriteLine("Failed to get preview image for blog(" + _blogId + ") and element(" + elementId + "): " + ex); try { File.Delete(path); } catch (Exception ex2) { Trace.WriteLine("Failed to delete preview image after failing to get it:" + ex2); } return; } } } try { _editingSite.FrameWindow.Invoke(new ThreadStart(() => _editingSite.CommandManager.Invalidate( CommandId.SemanticHtmlGallery)), null); } catch (Exception ex) { Trace.WriteLine("NotifyWeblogStylePreviewChanged failed: " + ex.Message); } } } private static Bitmap GetGalleryPreviewImageFromElementImage(Bitmap elementBitmap, int width, int height, Color background, Padding padding, bool isRtl) { Bitmap previewBitmap = null; try { previewBitmap = new Bitmap((int)DisplayHelper.ScaleX(width), (int)DisplayHelper.ScaleY(height)); using (Graphics g = Graphics.FromImage(previewBitmap)) { int left = isRtl ? previewBitmap.Width - elementBitmap.Width : 0; g.Clear(background); if (elementBitmap != null) g.DrawImageUnscaled(elementBitmap, left, (previewBitmap.Height - elementBitmap.Height - padding.Vertical + 1) / 2); return previewBitmap; } } catch (Exception) { if (previewBitmap != null) previewBitmap.Dispose(); throw; } } } internal class SemanticHtmlPreviewManager { private readonly IBlogPostEditingSite _editingSite; private readonly int _width; private readonly int _height; private readonly object _previewLock; public object Lock { get { return _previewLock; } } internal class BlogPreviewInfo { [ThreadStatic] private Dictionary<string, Bitmap> _bitmaps; internal BlogPreviewInfo(string blogId, string[] elementIds, bool isRtl, TemplateHtmlDelegate templateHtmlDelegate, string postBodyHtml) { IsRtl = isRtl; _blogId = blogId; _elementIds = elementIds; _templateHtmlLazyLoader = new LazyLoader<string>(delegate { return templateHtmlDelegate(); }); string style = isRtl ? "dir=\"rtl\" style=\"direction: rtl; text-align: right" : "dir=\"ltr\" style=\"direction: ltr; text-align: left"; style += "; width: 500px; text-indent: 0px; margin: 0px; overflow: visible; vertical-align: baseline; white-space: nowrap; line-height: normal; position: static\""; _postBodyHtml = postBodyHtml.Replace("{style}", style); _bitmaps = new Dictionary<string, Bitmap>(elementIds.Length); } ~BlogPreviewInfo() { foreach (Bitmap bitmap in _bitmaps.Values) { bitmap.Dispose(); } } public void SetBitmap(string elementId, Bitmap bitmap) { if (_bitmaps.ContainsKey(elementId)) { Bitmap oldBitmap = _bitmaps[elementId]; oldBitmap.Dispose(); _bitmaps.Remove(elementId); } _bitmaps.Add(elementId, bitmap); } public Bitmap GetBitmap(string elementId) { Bitmap bitmap = _bitmaps[elementId]; if (bitmap != null) { return bitmap.Clone() as Bitmap; } return null; } public void Clear() { foreach (string elementId in ElementIds) { // Remove from cache if (_bitmaps.ContainsKey(elementId)) { if (_bitmaps[elementId] != null) _bitmaps[elementId].Dispose(); _bitmaps.Remove(elementId); } // Remove from disk string path = GetPreviewBitmapPath(_blogId, elementId); File.Delete(path); } } public bool BitmapCached(string elementId) { return _bitmaps.ContainsKey(elementId); } private readonly LazyLoader<string> _templateHtmlLazyLoader; public string[] ElementIds { get { return _elementIds; } } public string TemplateHtml { get { return _templateHtmlLazyLoader.Value; } } public string PostBodyHtml { get { return _postBodyHtml; } } public bool IsRtl { get; set; } private readonly string _blogId; private readonly string _postBodyHtml; private readonly string[] _elementIds; } internal SemanticHtmlPreviewManager(IBlogPostEditingSite editingSite, TemplateHtmlDelegate templateHtmlDelegate, int width, int height) { _previewLock = new object(); _editingSite = editingSite; _templateHtmlDelegate = templateHtmlDelegate; _width = width; _height = height; string previewText = HtmlServices.HtmlEncode(Res.Get(StringId.SemanticHtmlPreviewText)); _postBodyHtml = @"<h1 {style} id=" + PreviewId_H1 + @">" + previewText + @"</h1> <h2 {style} id=" + PreviewId_H2 + @">" + previewText + @"</h2> <h3 {style} id=" + PreviewId_H3 + @">" + previewText + @"</h3> <h4 {style} id=" + PreviewId_H4 + @">" + previewText + @"</h4> <h5 {style} id=" + PreviewId_H5 + @">" + previewText + @"</h5> <h6 {style} id=" + PreviewId_H6 + @">" + previewText + @"</h6> <p {style} id=" + PreviewId_P + @">" + previewText + @"</p>"; } private Dictionary<string, UpdateSemanticHtmlPreviewAsyncOperation> _asyncOps = new Dictionary<string, UpdateSemanticHtmlPreviewAsyncOperation>(); private Dictionary<string, BlogPreviewInfo> _blogPreviewInfo = new Dictionary<string, BlogPreviewInfo>(); internal Bitmap GetPreviewBitmap(string blogId, string elementId) { Debug.Assert(_blogPreviewInfo.ContainsKey(blogId), "Need to register blog for preview"); Debug.Assert(((ISynchronizeInvoke)_editingSite).InvokeRequired == false, "This should only be called on the UI thread"); string path = GetPreviewBitmapPath(blogId, elementId); try { lock (Lock) { BlogPreviewInfo info = _blogPreviewInfo[blogId]; if (info.BitmapCached(elementId)) { return info.GetBitmap(elementId); } else if (File.Exists(path)) { MemoryStream ms; using (FileStream fs = File.OpenRead(path)) { ms = new MemoryStream((int)fs.Length); StreamHelper.Transfer(fs, ms); ms.Seek(0, SeekOrigin.Begin); } info.SetBitmap(elementId, new Bitmap(ms)); return info.GetBitmap(elementId); } if (!_asyncOps.ContainsKey(blogId)) { // Fetch asynchronously UpdateSemanticHtmlPreviewAsyncOperation asyncOperation = new UpdateSemanticHtmlPreviewAsyncOperation(_editingSite, blogId, info.ElementIds, info.TemplateHtml, info.PostBodyHtml, info.IsRtl, _editingSite.FrameWindow, Lock, _width, _height); _asyncOps.Add(blogId, asyncOperation); asyncOperation.Failed += new ThreadExceptionEventHandler(asyncOperation_Failed); asyncOperation.Completed += new EventHandler(asyncOperation_Completed); asyncOperation.Start(); } // else we're already fetching } } catch (Exception ex) { Trace.Fail("Failed to get preview bitmap for blog(" + blogId + ") and element(" + elementId + "): " + ex); } return null; } void asyncOperation_Completed(object sender, EventArgs e) { UpdateSemanticHtmlPreviewAsyncOperation asyncOperation = (UpdateSemanticHtmlPreviewAsyncOperation)sender; lock (Lock) { _asyncOps.Remove(asyncOperation.BlogId); } } void asyncOperation_Failed(object sender, ThreadExceptionEventArgs e) { UpdateSemanticHtmlPreviewAsyncOperation asyncOperation = (UpdateSemanticHtmlPreviewAsyncOperation)sender; Trace.WriteLine("UpdateSemanticHtmlPreviewAsyncOperation failed for blog(" + asyncOperation.BlogId + "): " + e.Exception); // Note: We intentionally do not remove this async op from asyncOps in order to prevent an infinite loop of failures. } public static string GetPreviewBitmapPath(string blogId, string elementId) { string blogTemplateDir = BlogEditingTemplate.GetBlogTemplateDir(blogId); string previewBitmapFilename = elementId.Replace(PreviewGuid, ".bmp"); return Path.Combine(blogTemplateDir, previewBitmapFilename); } private const string PreviewGuid = "-D983805A-53FF-452D-AEA5-45CD81EF54DD"; public const string PreviewId_H1 = "H1" + PreviewGuid; public const string PreviewId_H2 = "H2" + PreviewGuid; public const string PreviewId_H3 = "H3" + PreviewGuid; public const string PreviewId_H4 = "H4" + PreviewGuid; public const string PreviewId_H5 = "H5" + PreviewGuid; public const string PreviewId_H6 = "H6" + PreviewGuid; public const string PreviewId_P = "P" + PreviewGuid; private string _postBodyHtml; private readonly TemplateHtmlDelegate _templateHtmlDelegate; /// <summary> /// Associates a set of element ids and template html with a blog for the purpose of gallery preview image extraction /// </summary> /// <param name="blogId"></param> /// <param name="elementIds"></param> public void RegisterBlog(string blogId, string[] elementIds, bool isRtl) { if (!_blogPreviewInfo.ContainsKey(blogId)) _blogPreviewInfo.Add(blogId, new BlogPreviewInfo(blogId, elementIds, isRtl, _templateHtmlDelegate, _postBodyHtml)); } public void UnregisterBlog(string blogId) { try { lock (Lock) { if (_blogPreviewInfo.ContainsKey(blogId)) { _blogPreviewInfo[blogId].Clear(); _blogPreviewInfo.Remove(blogId); } } } catch (Exception ex) { Trace.Fail("Failed to unregister blog: " + ex); } } } public class SemanticHtmlGalleryCommand : GalleryCommand<string> { private string[] _ids; private IBlogPostEditingSite _editingSite; private List<SemanticHtmlElementInfo> _elements; private SemanticHtmlPreviewManager _previewManager; private IHtmlEditorComponentContext _componentContext; public SemanticHtmlGalleryCommand(CommandId commandId, IBlogPostEditingSite editingSite, TemplateHtmlDelegate templateHtmlDelegate, CommandManager commandManager, IHtmlEditorComponentContext componentContext) : base(commandId) { _editingSite = editingSite; _componentContext = componentContext; _elements = new List<SemanticHtmlElementInfo>(7); _elements.Add(new SemanticHtmlElementInfo("p", _ELEMENT_TAG_ID.TAGID_P, Res.Get(StringId.Paragraph), SemanticHtmlPreviewManager.PreviewId_P, CommandId.ApplySemanticParagraph)); _elements.Add(new SemanticHtmlElementInfo("h1", _ELEMENT_TAG_ID.TAGID_H1, Res.Get(StringId.Heading1), SemanticHtmlPreviewManager.PreviewId_H1, CommandId.ApplySemanticHeader1)); _elements.Add(new SemanticHtmlElementInfo("h2", _ELEMENT_TAG_ID.TAGID_H2, Res.Get(StringId.Heading2), SemanticHtmlPreviewManager.PreviewId_H2, CommandId.ApplySemanticHeader2)); _elements.Add(new SemanticHtmlElementInfo("h3", _ELEMENT_TAG_ID.TAGID_H3, Res.Get(StringId.Heading3), SemanticHtmlPreviewManager.PreviewId_H3, CommandId.ApplySemanticHeader3)); _elements.Add(new SemanticHtmlElementInfo("h4", _ELEMENT_TAG_ID.TAGID_H4, Res.Get(StringId.Heading4), SemanticHtmlPreviewManager.PreviewId_H4, CommandId.ApplySemanticHeader4)); _elements.Add(new SemanticHtmlElementInfo("h5", _ELEMENT_TAG_ID.TAGID_H5, Res.Get(StringId.Heading5), SemanticHtmlPreviewManager.PreviewId_H5, CommandId.ApplySemanticHeader5)); _elements.Add(new SemanticHtmlElementInfo("h6", _ELEMENT_TAG_ID.TAGID_H6, Res.Get(StringId.Heading6), SemanticHtmlPreviewManager.PreviewId_H6, CommandId.ApplySemanticHeader6)); _previewManager = new SemanticHtmlPreviewManager(_editingSite, templateHtmlDelegate, RibbonHelper.InGalleryImageWidth, RibbonHelper.InGalleryImageHeightWithoutLabel); _ids = new string[_elements.Count]; for (int i = 0; i < _ids.Length; i++) { _ids[i] = _elements[i].HtmlId; int index = i; OverridableCommand command = new OverridableCommand(_elements[i].CommandId); command.Execute += (sender, e) => SelectedIndex = index; commandManager.Add(command); } } public override int OverrideProperty(ref PropertyKey key, PropVariantRef overrideValue) { // In this case the override applies to each of the commands associated with each gallery item as well. // Normally, you can't disable individual gallery items, but these items have shortcuts associated with // them that must be disabled/enabled according to the override. foreach (var v in _elements) { _editingSite.CommandManager.OverrideProperty((uint)v.CommandId, ref key, overrideValue); } return base.OverrideProperty(ref key, overrideValue); } public override int CancelOverride(ref PropertyKey key) { // In this case the override applies to each of the commands associated with each gallery item as well. // Normally, you can't disable individual gallery items, but these items have shortcuts associated with // them that must be disabled/enabled according to the override. foreach (var v in _elements) { _editingSite.CommandManager.CancelOverride((uint)v.CommandId, ref key); } return base.CancelOverride(ref key); } public override bool Enabled { set { base.Enabled = value; foreach (var v in _elements) { _editingSite.CommandManager.SetEnabled(v.CommandId, value); } } } public string SelectedStyle { set { for (int i = 0; i < _elements.Count; i++) { if (_elements[i].HtmlName == value) { if (selectedIndex != i) { selectedIndex = i; InvalidateSelectedItemProperties(); OnStateChanged(EventArgs.Empty); } break; } } } } public override void Invalidate() { items.Clear(); base.Invalidate(); } private string _blogId; private bool _isRtl; public void SetAccountId(string blogId, bool isRtl, bool forceRefresh) { if (_blogId != blogId || forceRefresh) { if (forceRefresh) _previewManager.UnregisterBlog(blogId); _blogId = blogId; _isRtl = isRtl; items.Clear(); LoadItems(); } } internal class SemanticHtmlElementInfo { internal SemanticHtmlElementInfo(string htmlName, _ELEMENT_TAG_ID tagId, string displayName, string htmlId, CommandId commandId) { _htmlName = htmlName; _tagId = tagId; _displayName = displayName; _htmlId = htmlId; _commandId = commandId; } public CommandId CommandId { get { return _commandId; } } public string HtmlName { get { return _htmlName; } } public string DisplayName { get { return _displayName; } } public _ELEMENT_TAG_ID TagId { get { return _tagId; } } public string HtmlId { get { return _htmlId; } } private CommandId _commandId; private string _htmlId; private string _htmlName; private _ELEMENT_TAG_ID _tagId; private string _displayName; } public class SemanticHtmlGalleryItem : GalleryItem, IHtmlFormattingStyle { public SemanticHtmlGalleryItem(string elementName, _ELEMENT_TAG_ID elementTagId, string label, Bitmap bitmap) : base(label, bitmap, label) { this.elementName = elementName; this.elementTagId = elementTagId; } #region Implementation of IHtmlFormattingStyle public string DisplayName { get { return Label; } } private string elementName; public string ElementName { get { return elementName; } } private _ELEMENT_TAG_ID elementTagId; public _ELEMENT_TAG_ID ElementTagId { get { return elementTagId; } } #endregion } public override void LoadItems() { if (items.Count == 0) { items.Clear(); _previewManager.RegisterBlog(_blogId, _ids, _isRtl); foreach (var v in _elements) { items.Add(new SemanticHtmlGalleryItem(v.HtmlName, v.TagId, v.DisplayName, _previewManager.GetPreviewBitmap(_blogId, v.HtmlId))); } base.LoadItems(); OnStateChanged(EventArgs.Empty); } } } }
/*************************************************************************** copyright : (C) 2005 by Brian Nickel email : brian.nickel@gmail.com based on : flacfile.cpp from TagLib ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * ***************************************************************************/ using System.Collections.Generic; using System; namespace TagLib.Flac { public enum BlockType { StreamInfo = 0, Padding, Application, SeekTable, VorbisComment, CueSheet, Picture } [SupportedMimeType("taglib/flac", "flac")] [SupportedMimeType("audio/x-flac")] [SupportedMimeType("application/x-flac")] [SupportedMimeType("audio/flac")] public class File : TagLib.File { ////////////////////////////////////////////////////////////////////////// // private properties ////////////////////////////////////////////////////////////////////////// private Id3v2.Tag id3v2_tag; private Id3v1.Tag id3v1_tag; private Ogg.XiphComment comment; private PictureTag picture_tag; private CombinedTag tag; private Properties properties; ////////////////////////////////////////////////////////////////////////// // public methods ////////////////////////////////////////////////////////////////////////// public File (string file, Properties.ReadStyle properties_style) : base (file) { comment = null; properties = null; tag = new CombinedTag (); Mode = AccessMode.Read; Read (properties_style); Mode = AccessMode.Closed; } public File (string file) : this (file, Properties.ReadStyle.Average) { } public override void Save () { Mode = AccessMode.Write; long tag_start, tag_end; // Update ID3v2 tag FindId3v2 (out tag_start, out tag_end); if(id3v2_tag != null) { ByteVector id3v2_tag_data = id3v2_tag.Render (); Insert (id3v2_tag_data, tag_start, tag_end - tag_start); tag_end = tag_start + id3v2_tag_data.Count; } // Get all the blocks, but don't read the data for ones we're filling // with stored data. BlockType[] types = {BlockType.VorbisComment, BlockType.Picture}; List<Block> old_blocks = ReadBlocks (tag_end, Length, types, BlockMode.Blacklist); // Find the range currently holding the blocks. tag_start = old_blocks [0].Position; tag_end = old_blocks [old_blocks.Count - 1].NextBlockPosition; // Create new vorbis comments is they don't exist. GetTag (TagTypes.Xiph, true); // Create new blocks and add the basics. List<Block> new_blocks = new List<Block> (); new_blocks.Add (old_blocks [0]); // Add blocks we don't deal with from the file. foreach (Block block in old_blocks) if (block.Type != BlockType.StreamInfo && block.Type != BlockType.VorbisComment && block.Type != BlockType.Picture && block.Type != BlockType.Padding) new_blocks.Add (block); new_blocks.Add (new Block (BlockType.VorbisComment, comment.Render (false))); foreach (IPicture picture in picture_tag.Pictures) new_blocks.Add (new Block (BlockType.Picture, Picture.Render (picture))); // Get the length of the blocks. long length = 0; foreach (Block block in new_blocks) length += block.TotalLength; // Find the padding size to avoid trouble. If that fails make some. long padding_size = tag_end - tag_start - BlockHeader.Length - length; if (padding_size < 0) padding_size = 1024 * 4; // Add a padding block. if (padding_size != 0) new_blocks.Add (new Block (BlockType.Padding, new ByteVector ((int) padding_size))); // Render the blocks. ByteVector block_data = new ByteVector (); for (int i = 0; i < new_blocks.Count; i ++) block_data.Add (new_blocks [i].Render (i == new_blocks.Count - 1)); // Update the blocks. Insert (block_data, tag_start, tag_end - tag_start); // Update ID3v1 tag FindId3v1 (out tag_start, out tag_end); if(id3v1_tag != null) { Insert (id3v1_tag.Render (), tag_start, tag_end - tag_start); } Mode = AccessMode.Closed; } public override TagLib.Tag GetTag (TagTypes type, bool create) { switch (type) { case TagTypes.Id3v1: { if (create && id3v1_tag == null) { id3v1_tag = new Id3v1.Tag (); if (tag != null) TagLib.Tag.Duplicate (tag, id3v1_tag, true); tag.SetTags (picture_tag, comment, id3v2_tag, id3v1_tag); } return id3v1_tag; } case TagTypes.Id3v2: { if (create && id3v2_tag == null) { id3v2_tag = new Id3v2.Tag (); if (tag != null) TagLib.Tag.Duplicate (tag, id3v2_tag, true); tag.SetTags (picture_tag, comment, id3v2_tag, id3v1_tag); } return id3v2_tag; } case TagTypes.Xiph: { if (create && comment == null) { comment = new Ogg.XiphComment (); if (tag != null) TagLib.Tag.Duplicate (tag, comment, true); tag.SetTags (picture_tag, comment, id3v2_tag, id3v1_tag); } return comment; } default: return null; } } ////////////////////////////////////////////////////////////////////////// // public properties ////////////////////////////////////////////////////////////////////////// public override TagLib.Tag Tag {get {return tag;}} public override AudioProperties AudioProperties {get {return properties;}} ////////////////////////////////////////////////////////////////////////// // private methods ////////////////////////////////////////////////////////////////////////// private void Read (Properties.ReadStyle properties_style) { long flac_data_begin, flac_data_end, dummy; id3v2_tag = ReadId3v2Tag (out dummy, out flac_data_begin); id3v1_tag = ReadId3v1Tag (out flac_data_end, out dummy); BlockType[] types = {BlockType.StreamInfo, BlockType.VorbisComment, BlockType.Picture}; List<Block> blocks = ReadBlocks (flac_data_begin, flac_data_end, types, BlockMode.Whitelist); // Find the first vorbis comment inside the blocks. foreach (Block block in blocks) if (block.Type == BlockType.VorbisComment && block.Data.Count > 0) { comment = new Ogg.XiphComment (block.Data); break; } // Find the images. List<IPicture> pictures = new List<IPicture>(); foreach (Block block in blocks) if (block.Type == BlockType.Picture && block.Data.Count > 0) { try { pictures.Add (new Picture (block.Data)); } catch {} } picture_tag = new PictureTag (pictures.ToArray ()); // Set the tags in the CombinedTag. tag.SetTags (picture_tag, comment, id3v2_tag, id3v1_tag); // Make sure we have a Vorbis Comment. GetTag (TagTypes.Xiph, true); // The stream exists from the end of the last block to the end of the file. long stream_length = flac_data_end - blocks [blocks.Count - 1].NextBlockPosition; if(properties_style != Properties.ReadStyle.None) properties = new Properties (blocks [0].Data, stream_length, properties_style); } private Id3v2.Tag ReadId3v2Tag (out long start, out long end) { return FindId3v2 (out start, out end) ? new Id3v2.Tag (this, start) : null; } private Id3v1.Tag ReadId3v1Tag (out long start, out long end) { return FindId3v1 (out start, out end) ? new Id3v1.Tag (this, start) : null; } private enum BlockMode { Blacklist, Whitelist } private List<Block> ReadBlocks (long start, long end, BlockType[] types, BlockMode mode) { List<Block> blocks = new List<Block>(); long block_position = Find ("fLaC", start); if (block_position < 0) throw new CorruptFileException ("FLAC stream not found at starting position."); block_position += 4; Block block; do { Seek (block_position); block = ReadMetadataBlock (types, mode); blocks.Add (block); if (block.NextBlockPosition > end) throw new CorruptFileException ("Next block position exceeds length of stream."); block_position = block.NextBlockPosition; } while (!block.IsLastBlock); // Check that the first block is a METADATA_BLOCK_STREAMINFO. if (blocks [0].Type != BlockType.StreamInfo) throw new CorruptFileException ("FLAC stream does not begin with StreamInfo."); return blocks; } private BlockHeader ReadMetadataBlockHeader () { return new BlockHeader (ReadBlock (4)); } private Block ReadMetadataBlock (BlockType[] types, BlockMode mode) { long position = Tell; BlockHeader header = ReadMetadataBlockHeader (); ByteVector data = null; if (types != null) { bool found = false; foreach (BlockType type in types) if (header.BlockType == type) found = true; if ((mode == BlockMode.Whitelist && found) || (mode == BlockMode.Blacklist && !found)) data = ReadBlock ((int) header.BlockLength); } return new Block (header, data, position); } private bool FindId3v1 (out long start, out long end) { Seek (-128, System.IO.SeekOrigin.End); start = Tell; end = Length; if (ReadBlock (3) == Id3v1.Tag.FileIdentifier) return true; start = end; return false; } private bool FindId3v2 (out long start, out long end) { start = end = 0; Seek (0); ByteVector data = ReadBlock (10); if (data.Mid (0, 3) == Id3v2.Header.FileIdentifier) { Id3v2.Header header = new Id3v2.Header (data); if (header.TagSize != 0) { end = header.CompleteTagSize; return true; } } return false; } ////////////////////////////////////////////////////////////////////////// // BlockHeader class ////////////////////////////////////////////////////////////////////////// private class BlockHeader { private BlockType block_type; private bool is_last_block; private uint block_length; public BlockHeader (ByteVector data) { block_type = (BlockType) (data[0] & 0x7f); is_last_block = (data[0] & 0x80) != 0; block_length = data.Mid (1,3).ToUInt (); } public BlockHeader (BlockType type, uint length) { block_type = type; is_last_block = false; block_length = length; } public ByteVector Render (bool is_last_block) { ByteVector data = ByteVector.FromUInt (block_length); data [0] = (byte)(block_type + (is_last_block ? 0x80 : 0)); return data; } public static uint Length {get {return 4;}} public BlockType BlockType {get {return block_type;}} public bool IsLastBlock {get {return is_last_block;}} public uint BlockLength {get {return block_length;}} } ////////////////////////////////////////////////////////////////////////// // Block class ////////////////////////////////////////////////////////////////////////// private class Block { private BlockHeader header; private ByteVector data; private long position; public Block (BlockHeader header, ByteVector data, long position) { this.header = header; this.data = data; this.position = position; } public Block (BlockType type, ByteVector data) { this.header = new BlockHeader (type, (uint) data.Count); this.data = data; this.position = 0; } public ByteVector Render (bool is_last_block) { ByteVector data = header.Render (is_last_block); data.Add (this.data); return data; } public BlockType Type {get {return header.BlockType;}} public bool IsLastBlock {get {return header.IsLastBlock;}} public uint Length {get {return header.BlockLength;}} public uint TotalLength {get {return Length + 4;}} public ByteVector Data {get {return data;}} public long Position {get {return position;}} public long NextBlockPosition {get {return Position + BlockHeader.Length + header.BlockLength;}} } ////////////////////////////////////////////////////////////////////////// // PictureTag class ////////////////////////////////////////////////////////////////////////// private class PictureTag : Tag { private IPicture[] pictures; public PictureTag (IPicture[] pictures) { this.pictures = pictures; } public override IPicture[] Pictures { get {return pictures != null ? pictures : new IPicture [] {};} set {pictures = value;} } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Diagnostics; using Internal.Cryptography; namespace System.Security.Cryptography { public class Rfc2898DeriveBytes : DeriveBytes { public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) { if (salt == null) throw new ArgumentNullException("salt"); if (salt.Length < MinimumSaltSize) throw new ArgumentException(SR.Cryptography_PasswordDerivedBytes_FewBytesSalt, "salt"); if (iterations <= 0) throw new ArgumentOutOfRangeException("iterations", SR.ArgumentOutOfRange_NeedPosNum); if (password == null) throw new NullReferenceException(); // This "should" be ArgumentNullException but for compat, we throw NullReferenceException. _salt = salt.CloneByteArray(); _iterations = (uint)iterations; _password = password.CloneByteArray(); _hmacSha1 = new HMACSHA1(_password); Initialize(); } public Rfc2898DeriveBytes(string password, byte[] salt) : this(password, salt, 1000) { } public Rfc2898DeriveBytes(string password, byte[] salt, int iterations) : this(new UTF8Encoding(false).GetBytes(password), salt, iterations) { } public Rfc2898DeriveBytes(string password, int saltSize) : this(password, saltSize, 1000) { } public Rfc2898DeriveBytes(string password, int saltSize, int iterations) { if (saltSize < 0) throw new ArgumentOutOfRangeException("saltSize", SR.ArgumentOutOfRange_NeedNonNegNum); if (saltSize < MinimumSaltSize) throw new ArgumentException(SR.Cryptography_PasswordDerivedBytes_FewBytesSalt, "saltSize"); if (iterations <= 0) throw new ArgumentOutOfRangeException("iterations", SR.ArgumentOutOfRange_NeedPosNum); _salt = Helpers.GenerateRandom(saltSize); _iterations = (uint)iterations; _password = new UTF8Encoding(false).GetBytes(password); _hmacSha1 = new HMACSHA1(_password); Initialize(); } public int IterationCount { get { return (int)_iterations; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedPosNum); _iterations = (uint)value; Initialize(); } } public byte[] Salt { get { return _salt.CloneByteArray(); } set { if (value == null) throw new ArgumentNullException("value"); if (value.Length < MinimumSaltSize) throw new ArgumentException(SR.Cryptography_PasswordDerivedBytes_FewBytesSalt); _salt = value.CloneByteArray(); Initialize(); } } protected override void Dispose(bool disposing) { if (disposing) { if (_hmacSha1 != null) _hmacSha1.Dispose(); _hmacSha1 = null; if (_buffer != null) Array.Clear(_buffer, 0, _buffer.Length); if (_password != null) Array.Clear(_password, 0, _password.Length); if (_salt != null) Array.Clear(_salt, 0, _salt.Length); } base.Dispose(disposing); } public override byte[] GetBytes(int cb) { if (cb <= 0) throw new ArgumentOutOfRangeException("cb", SR.ArgumentOutOfRange_NeedPosNum); byte[] password = new byte[cb]; int offset = 0; int size = _endIndex - _startIndex; if (size > 0) { if (cb >= size) { Array.Copy(_buffer, _startIndex, password, 0, size); _startIndex = _endIndex = 0; offset += size; } else { Array.Copy(_buffer, _startIndex, password, 0, cb); _startIndex += cb; return password; } } Debug.Assert(_startIndex == 0 && _endIndex == 0, "Invalid start or end index in the internal buffer."); while (offset < cb) { byte[] T_block = Func(); int remainder = cb - offset; if (remainder > BlockSize) { Array.Copy(T_block, 0, password, offset, BlockSize); offset += BlockSize; } else { Array.Copy(T_block, 0, password, offset, remainder); offset += remainder; Array.Copy(T_block, remainder, _buffer, _startIndex, BlockSize - remainder); _endIndex += (BlockSize - remainder); return password; } } return password; } public override void Reset() { Initialize(); } private void Initialize() { if (_buffer != null) Array.Clear(_buffer, 0, _buffer.Length); _buffer = new byte[BlockSize]; _block = 1; _startIndex = _endIndex = 0; } // This function is defined as follows: // Func (S, i) = HMAC(S || i) | HMAC2(S || i) | ... | HMAC(iterations) (S || i) // where i is the block number. private byte[] Func() { byte[] temp = new byte[_salt.Length + sizeof(uint)]; Buffer.BlockCopy(_salt, 0, temp, 0, _salt.Length); Helpers.WriteInt(_block, temp, _salt.Length); temp = _hmacSha1.ComputeHash(temp); byte[] ret = temp; for (int i = 2; i <= _iterations; i++) { temp = _hmacSha1.ComputeHash(temp); for (int j = 0; j < BlockSize; j++) { ret[j] ^= temp[j]; } } // increment the block count. _block++; return ret; } private readonly byte[] _password; private byte[] _salt; private uint _iterations; private HMACSHA1 _hmacSha1; private byte[] _buffer; private uint _block; private int _startIndex; private int _endIndex; private const int BlockSize = 20; private const int MinimumSaltSize = 8; } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using AllReady.Models; namespace AllReady.Migrations { [DbContext(typeof(AllReadyContext))] [Migration("20160616190604_ItineraryRequestChanges")] partial class ItineraryRequestChanges { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<DateTimeOffset?>("EndDateTime"); b.Property<int?>("EventId"); b.Property<bool>("IsAllowWaitList"); b.Property<bool>("IsLimitVolunteers"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<int?>("OrganizationId"); b.Property<DateTimeOffset?>("StartDateTime"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<string>("FirstName"); b.Property<string>("LastName"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<int?>("OrganizationId"); b.Property<string>("PasswordHash"); b.Property<string>("PendingNewEmail"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<string>("TimeZoneId") .IsRequired(); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignImpactId"); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<string>("ExternalUrl"); b.Property<string>("ExternalUrlText"); b.Property<bool>("Featured"); b.Property<string>("FullDescription"); b.Property<string>("ImageUrl"); b.Property<int?>("LocationId"); b.Property<bool>("Locked"); b.Property<int>("ManagingOrganizationId"); b.Property<string>("Name") .IsRequired(); b.Property<string>("OrganizerId"); b.Property<DateTimeOffset>("StartDateTime"); b.Property<string>("TimeZoneId") .IsRequired(); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.Property<int>("CampaignId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("CampaignId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.CampaignImpact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CurrentImpactLevel"); b.Property<bool>("Display"); b.Property<int>("ImpactType"); b.Property<int>("NumericImpactGoal"); b.Property<string>("TextualImpactGoal"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignId"); b.Property<int?>("OrganizationId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ClosestLocation", b => { b.Property<string>("PostalCode"); b.Property<string>("City"); b.Property<double>("Distance"); b.Property<string>("State"); b.HasKey("PostalCode"); }); modelBuilder.Entity("AllReady.Models.Contact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Email"); b.Property<string>("FirstName"); b.Property<string>("LastName"); b.Property<string>("PhoneNumber"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Event", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CampaignId"); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<int>("EventType"); b.Property<string>("ImageUrl"); b.Property<bool>("IsAllowWaitList"); b.Property<bool>("IsLimitVolunteers"); b.Property<int?>("LocationId"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<string>("OrganizerId"); b.Property<DateTimeOffset>("StartDateTime"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.EventSignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AdditionalInfo"); b.Property<DateTime?>("CheckinDateTime"); b.Property<int?>("EventId"); b.Property<string>("PreferredEmail"); b.Property<string>("PreferredPhoneNumber"); b.Property<DateTime>("SignupDateTime"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.EventSkill", b => { b.Property<int>("EventId"); b.Property<int>("SkillId"); b.HasKey("EventId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.Itinerary", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("Date"); b.Property<int>("EventId"); b.Property<string>("Name"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ItineraryRequest", b => { b.Property<int>("ItineraryId"); b.Property<Guid>("RequestId"); b.Property<DateTime>("DateAssigned"); b.Property<int>("OrderIndex"); b.HasKey("ItineraryId", "RequestId"); }); modelBuilder.Entity("AllReady.Models.Location", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address1"); b.Property<string>("Address2"); b.Property<string>("City"); b.Property<string>("Country"); b.Property<string>("Name"); b.Property<string>("PhoneNumber"); b.Property<string>("PostalCode"); b.Property<string>("State"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Organization", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("LocationId"); b.Property<string>("LogoUrl"); b.Property<string>("Name") .IsRequired(); b.Property<string>("PrivacyPolicy"); b.Property<string>("WebUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.OrganizationContact", b => { b.Property<int>("OrganizationId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("OrganizationId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b => { b.Property<string>("PostalCode"); b.Property<string>("City"); b.Property<string>("State"); b.HasKey("PostalCode"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeoCoordinate", b => { b.Property<double>("Latitude"); b.Property<double>("Longitude"); b.HasKey("Latitude", "Longitude"); }); modelBuilder.Entity("AllReady.Models.Request", b => { b.Property<Guid>("RequestId") .ValueGeneratedOnAdd(); b.Property<string>("Address"); b.Property<string>("City"); b.Property<DateTime>("DateAdded"); b.Property<string>("Email"); b.Property<int?>("EventId"); b.Property<double>("Latitude"); b.Property<double>("Longitude"); b.Property<string>("Name"); b.Property<string>("Phone"); b.Property<string>("ProviderData"); b.Property<string>("ProviderId"); b.Property<string>("State"); b.Property<int>("Status"); b.Property<string>("Zip"); b.HasKey("RequestId"); }); modelBuilder.Entity("AllReady.Models.Resource", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CategoryTag"); b.Property<string>("Description"); b.Property<string>("MediaUrl"); b.Property<string>("Name"); b.Property<DateTime>("PublishDateBegin"); b.Property<DateTime>("PublishDateEnd"); b.Property<string>("ResourceUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<string>("Name") .IsRequired(); b.Property<int?>("OwningOrganizationId"); b.Property<int?>("ParentSkillId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AdditionalInfo"); b.Property<int?>("ItineraryId"); b.Property<string>("PreferredEmail"); b.Property<string>("PreferredPhoneNumber"); b.Property<string>("Status"); b.Property<DateTime>("StatusDateTimeUtc"); b.Property<string>("StatusDescription"); b.Property<int?>("TaskId"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.Property<int>("TaskId"); b.Property<int>("SkillId"); b.HasKey("TaskId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.Property<string>("UserId"); b.Property<int>("SkillId"); b.HasKey("UserId", "SkillId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.HasOne("AllReady.Models.CampaignImpact") .WithMany() .HasForeignKey("CampaignImpactId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("ManagingOrganizationId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Event", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.EventSignup", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.EventSkill", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); }); modelBuilder.Entity("AllReady.Models.Itinerary", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); }); modelBuilder.Entity("AllReady.Models.ItineraryRequest", b => { b.HasOne("AllReady.Models.Itinerary") .WithMany() .HasForeignKey("ItineraryId"); b.HasOne("AllReady.Models.Request") .WithMany() .HasForeignKey("RequestId"); }); modelBuilder.Entity("AllReady.Models.Organization", b => { b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); }); modelBuilder.Entity("AllReady.Models.OrganizationContact", b => { b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Request", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OwningOrganizationId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("ParentSkillId"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.HasOne("AllReady.Models.Itinerary") .WithMany() .HasForeignKey("ItineraryId"); b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Description { using System.Globalization; using System.ServiceModel.Channels; using System.ServiceModel; using System.Collections.Generic; public static class MetadataExchangeBindings { static Binding httpBinding; static Binding httpGetBinding; static Binding httpsBinding; static Binding httpsGetBinding; static Binding tcpBinding; static Binding pipeBinding; internal static Binding Http { get { // don't need to lock because no guarantee of instance identity if (httpBinding == null) { httpBinding = CreateHttpBinding(); } return httpBinding; } } internal static Binding HttpGet { get { // don't need to lock because no guarantee of instance identity if (httpGetBinding == null) { httpGetBinding = CreateHttpGetBinding(); } return httpGetBinding; } } internal static Binding Https { get { // don't need to lock because no guarantee of instance identity if (httpsBinding == null) { httpsBinding = CreateHttpsBinding(); } return httpsBinding; } } internal static Binding HttpsGet { get { // don't need to lock because no guarantee of instance identity if (httpsGetBinding == null) { httpsGetBinding = CreateHttpsGetBinding(); } return httpsGetBinding; } } internal static Binding Tcp { get { // don't need to lock because no guarantee of instance identity if (tcpBinding == null) { tcpBinding = CreateTcpBinding(); } return tcpBinding; } } internal static Binding NamedPipe { get { // don't need to lock because no guarantee of instance identity if (pipeBinding == null) { pipeBinding = CreateNamedPipeBinding(); } return pipeBinding; } } public static Binding CreateMexHttpBinding() { return MetadataExchangeBindings.CreateHttpBinding(); } public static Binding CreateMexHttpsBinding() { return MetadataExchangeBindings.CreateHttpsBinding(); } public static Binding CreateMexTcpBinding() { return MetadataExchangeBindings.CreateTcpBinding(); } public static Binding CreateMexNamedPipeBinding() { return MetadataExchangeBindings.CreateNamedPipeBinding(); } internal static Binding GetBindingForScheme(string scheme) { Binding binding = null; TryGetBindingForScheme(scheme, out binding); return binding; } internal static bool TryGetBindingForScheme(string scheme, out Binding binding) { if (String.Compare(scheme, "http", StringComparison.OrdinalIgnoreCase) == 0) { binding = Http; } else if (String.Compare(scheme, "https", StringComparison.OrdinalIgnoreCase) == 0) { binding = Https; } else if (String.Compare(scheme, "net.tcp", StringComparison.OrdinalIgnoreCase) == 0) { binding = Tcp; } else if (String.Compare(scheme, "net.pipe", StringComparison.OrdinalIgnoreCase) == 0) { binding = NamedPipe; } else { binding = null; } return binding != null; } static WSHttpBinding CreateHttpBinding() { WSHttpBinding binding = new WSHttpBinding(SecurityMode.None, /* reliableSessionEnabled */ false); binding.Name = MetadataStrings.MetadataExchangeStrings.HttpBindingName; binding.Namespace = MetadataStrings.MetadataExchangeStrings.BindingNamespace; return binding; } static WSHttpBinding CreateHttpsBinding() { WSHttpBinding binding = new WSHttpBinding( new WSHttpSecurity(SecurityMode.Transport, new HttpTransportSecurity(), new NonDualMessageSecurityOverHttp()), /* reliableSessionEnabled */ false); binding.Name = MetadataStrings.MetadataExchangeStrings.HttpsBindingName; binding.Namespace = MetadataStrings.MetadataExchangeStrings.BindingNamespace; return binding; } static CustomBinding CreateHttpGetBinding() { return CreateGetBinding(new HttpTransportBindingElement()); } static CustomBinding CreateHttpsGetBinding() { return CreateGetBinding(new HttpsTransportBindingElement()); } static CustomBinding CreateGetBinding(HttpTransportBindingElement httpTransport) { TextMessageEncodingBindingElement textEncoding = new TextMessageEncodingBindingElement(); textEncoding.MessageVersion = MessageVersion.None; httpTransport.Method = "GET"; httpTransport.InheritBaseAddressSettings = true; return new CustomBinding(textEncoding, httpTransport); } static CustomBinding CreateTcpBinding() { CustomBinding binding = new CustomBinding(MetadataStrings.MetadataExchangeStrings.TcpBindingName, MetadataStrings.MetadataExchangeStrings.BindingNamespace); TcpTransportBindingElement tcpTransport = new TcpTransportBindingElement(); binding.Elements.Add(tcpTransport); return binding; } static CustomBinding CreateNamedPipeBinding() { CustomBinding binding = new CustomBinding(MetadataStrings.MetadataExchangeStrings.NamedPipeBindingName, MetadataStrings.MetadataExchangeStrings.BindingNamespace); NamedPipeTransportBindingElement pipeTransport = new NamedPipeTransportBindingElement(); binding.Elements.Add(pipeTransport); return binding; } internal static bool IsSchemeSupported(string scheme) { Binding binding; return TryGetBindingForScheme(scheme, out binding); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// LoadBalancersOperations operations. /// </summary> internal partial class LoadBalancersOperations : IServiceOperations<NetworkClient>, ILoadBalancersOperations { /// <summary> /// Initializes a new instance of the LoadBalancersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal LoadBalancersOperations(NetworkClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkClient /// </summary> public NetworkClient Client { get; private set; } /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LoadBalancer>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LoadBalancer>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<LoadBalancer>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<LoadBalancer> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LoadBalancer>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LoadBalancer>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//------------------------------------------------------------------------------ // <copyright file="AssemblyResourceLoader.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Handlers { using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Reflection; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.Compilation; using System.Web.Configuration; using System.Web.Hosting; using System.Web.Management; using System.Web.RegularExpressions; using System.Web.Security.Cryptography; using System.Web.UI; using System.Web.Util; /// <devdoc> /// Provides a way to load client-side resources from assemblies /// </devdoc> public sealed class AssemblyResourceLoader : IHttpHandler { private const string _webResourceUrl = "WebResource.axd"; private readonly static Regex webResourceRegex = new WebResourceRegex(); private static IDictionary _urlCache = Hashtable.Synchronized(new Hashtable()); private static IDictionary _assemblyInfoCache = Hashtable.Synchronized(new Hashtable()); private static IDictionary _webResourceCache = Hashtable.Synchronized(new Hashtable()); private static IDictionary _typeAssemblyCache = Hashtable.Synchronized(new Hashtable()); // This group of fields is used for backwards compatibility. In v1.x you could // technically customize the files in the /aspnet_client/ folder whereas in v2.x // we serve those files using WebResource.axd. These fields are used to check // if there is a customized version of the file and use that instead of the resource. private static bool _webFormsScriptChecked; private static VirtualPath _webFormsScriptLocation; private static bool _webUIValidationScriptChecked; private static VirtualPath _webUIValidationScriptLocation; private static bool _smartNavScriptChecked; private static VirtualPath _smartNavScriptLocation; private static bool _smartNavPageChecked; private static VirtualPath _smartNavPageLocation; private static bool _handlerExistenceChecked; private static bool _handlerExists; // set by unit tests to avoid dependency on httpruntime. internal static string _applicationRootPath; private static bool DebugMode { get { return HttpContext.Current.IsDebuggingEnabled; } } /// <devdoc> /// Create a cache key for the UrlCache. /// /// requirement: If assembly1 and assembly2 represent the same assembly, /// then they must be the same object; otherwise this method will fail to generate /// a unique cache key. /// </devdoc> private static int CreateWebResourceUrlCacheKey(Assembly assembly, string resourceName, bool htmlEncoded, bool forSubstitution, bool enableCdn, bool debuggingEnabled, bool secureConnection) { int hashCode = HashCodeCombiner.CombineHashCodes( assembly.GetHashCode(), resourceName.GetHashCode(), htmlEncoded.GetHashCode(), forSubstitution.GetHashCode(), enableCdn.GetHashCode()); return HashCodeCombiner.CombineHashCodes(hashCode, debuggingEnabled.GetHashCode(), secureConnection.GetHashCode()); } /// <devdoc> /// Validates that the WebResource.axd handler is registered in config and actually /// points to the correct handler type. /// </devdoc> private static void EnsureHandlerExistenceChecked() { // First we have to check that the handler is registered: // <add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" /> if (!_handlerExistenceChecked) { HttpContext context = HttpContext.Current; IIS7WorkerRequest iis7WorkerRequest = (context != null) ? context.WorkerRequest as IIS7WorkerRequest : null; string webResourcePath = UrlPath.Combine(HttpRuntime.AppDomainAppVirtualPathString, _webResourceUrl); if (iis7WorkerRequest != null) { // check the IIS <handlers> section by mapping the handler string handlerTypeString = iis7WorkerRequest.MapHandlerAndGetHandlerTypeString(method: "GET", path: UrlPath.Combine(HttpRuntime.AppDomainAppVirtualPathString, _webResourceUrl), convertNativeStaticFileModule: false, ignoreWildcardMappings: true); if (!String.IsNullOrEmpty(handlerTypeString)) { _handlerExists = (typeof(AssemblyResourceLoader) == BuildManager.GetType(handlerTypeString, true /*throwOnFail*/, false /*ignoreCase*/)); } } else { // check the <httpHandlers> section HttpHandlerAction httpHandler = RuntimeConfig.GetConfig(VirtualPath.Create(webResourcePath)).HttpHandlers.FindMapping("GET", VirtualPath.Create(_webResourceUrl)); _handlerExists = (httpHandler != null) && (httpHandler.TypeInternal == typeof(AssemblyResourceLoader)); } _handlerExistenceChecked = true; } } /// <devdoc> /// Performs the actual putting together of the resource reference URL. /// </devdoc> private static string FormatWebResourceUrl(string assemblyName, string resourceName, long assemblyDate, bool htmlEncoded) { string encryptedData = Page.EncryptString(assemblyName + "|" + resourceName, Purpose.AssemblyResourceLoader_WebResourceUrl); if (htmlEncoded) { return String.Format(CultureInfo.InvariantCulture, _webResourceUrl + "?d={0}&amp;t={1}", encryptedData, assemblyDate); } else { return String.Format(CultureInfo.InvariantCulture, _webResourceUrl + "?d={0}&t={1}", encryptedData, assemblyDate); } } internal static Assembly GetAssemblyFromType(Type type) { Assembly assembly = (Assembly)_typeAssemblyCache[type]; if (assembly == null) { assembly = type.Assembly; _typeAssemblyCache[type] = assembly; } return assembly; } private static Pair GetAssemblyInfo(Assembly assembly) { Pair assemblyInfo = _assemblyInfoCache[assembly] as Pair; if (assemblyInfo == null) { assemblyInfo = GetAssemblyInfoWithAssertInternal(assembly); _assemblyInfoCache[assembly] = assemblyInfo; } Debug.Assert(assemblyInfo != null, "Assembly info should not be null"); return assemblyInfo; } [FileIOPermission(SecurityAction.Assert, Unrestricted = true)] private static Pair GetAssemblyInfoWithAssertInternal(Assembly assembly) { AssemblyName assemblyName = assembly.GetName(); long assemblyDate = File.GetLastWriteTime(new Uri(assemblyName.CodeBase).LocalPath).Ticks; Pair assemblyInfo = new Pair(assemblyName, assemblyDate); return assemblyInfo; } /// <devdoc> /// Gets the virtual path of a physical resource file. Null is /// returned if the resource does not exist. /// We assert full FileIOPermission so that we can map paths. /// </devdoc> [FileIOPermission(SecurityAction.Assert, Unrestricted = true)] private static VirtualPath GetDiskResourcePath(string resourceName) { VirtualPath clientScriptsLocation = Util.GetScriptLocation(); VirtualPath resourceVirtualPath = clientScriptsLocation.SimpleCombine(resourceName); string resourcePhysicalPath = resourceVirtualPath.MapPath(); if (File.Exists(resourcePhysicalPath)) { return resourceVirtualPath; } else { return null; } } internal static string GetWebResourceUrl(Type type, string resourceName) { return GetWebResourceUrl(type, resourceName, false, null); } internal static string GetWebResourceUrl(Type type, string resourceName, bool htmlEncoded) { return GetWebResourceUrl(type, resourceName, htmlEncoded, null); } internal static string GetWebResourceUrl(Type type, string resourceName, bool htmlEncoded, IScriptManager scriptManager) { bool enableCdn = (scriptManager != null && scriptManager.EnableCdn); return GetWebResourceUrl(type, resourceName, htmlEncoded, scriptManager, enableCdn: enableCdn); } /// <devdoc> /// Gets a URL resource reference to a client-side resource /// </devdoc> internal static string GetWebResourceUrl(Type type, string resourceName, bool htmlEncoded, IScriptManager scriptManager, bool enableCdn) { Assembly assembly = GetAssemblyFromType(type); Debug.Assert(assembly != null, "Type.Assembly should never be null."); // If the resource request is for System.Web.dll and more specifically // it is for a file that we shipped in v1.x, we have to check if a // customized copy of the file exists. See notes at the top of the file // regarding this. if (assembly == typeof(AssemblyResourceLoader).Assembly) { if (String.Equals(resourceName, "WebForms.js", StringComparison.Ordinal)) { if (!_webFormsScriptChecked) { _webFormsScriptLocation = GetDiskResourcePath(resourceName); _webFormsScriptChecked = true; } if (_webFormsScriptLocation != null) { return _webFormsScriptLocation.VirtualPathString; } } else if (String.Equals(resourceName, "WebUIValidation.js", StringComparison.Ordinal)) { if (!_webUIValidationScriptChecked) { _webUIValidationScriptLocation = GetDiskResourcePath(resourceName); _webUIValidationScriptChecked = true; } if (_webUIValidationScriptLocation != null) { return _webUIValidationScriptLocation.VirtualPathString; } } else if (String.Equals(resourceName, "SmartNav.htm", StringComparison.Ordinal)) { if (!_smartNavPageChecked) { _smartNavPageLocation = GetDiskResourcePath(resourceName); _smartNavPageChecked = true; } if (_smartNavPageLocation != null) { return _smartNavPageLocation.VirtualPathString; } } else if (String.Equals(resourceName, "SmartNav.js", StringComparison.Ordinal)) { if (!_smartNavScriptChecked) { _smartNavScriptLocation = GetDiskResourcePath(resourceName); _smartNavScriptChecked = true; } if (_smartNavScriptLocation != null) { return _smartNavScriptLocation.VirtualPathString; } } } return GetWebResourceUrlInternal(assembly, resourceName, htmlEncoded, false, scriptManager, enableCdn); } private static WebResourceAttribute FindWebResourceAttribute(Assembly assembly, string resourceName) { object[] attrs = assembly.GetCustomAttributes(false); for (int i = 0; i < attrs.Length; i++) { WebResourceAttribute wra = attrs[i] as WebResourceAttribute; if ((wra != null) && String.Equals(wra.WebResource, resourceName, StringComparison.Ordinal)) { return wra; } } return null; } internal static string FormatCdnUrl(Assembly assembly, string cdnPath) { // {0} = Short Assembly Name // {1} = Assembly Version // {2} = Assembly File Version // use a new AssemblyName because assembly.GetName() doesn't work in medium trust. AssemblyName assemblyName = new AssemblyName(assembly.FullName); return String.Format(CultureInfo.InvariantCulture, cdnPath, HttpUtility.UrlEncode(assemblyName.Name), HttpUtility.UrlEncode(assemblyName.Version.ToString(4)), HttpUtility.UrlEncode(AssemblyUtil.GetAssemblyFileVersion(assembly))); } private static string GetCdnPath(string resourceName, Assembly assembly, bool secureConnection) { string cdnPath = null; WebResourceAttribute wra = FindWebResourceAttribute(assembly, resourceName); if (wra != null) { cdnPath = secureConnection ? wra.CdnPathSecureConnection : wra.CdnPath; if (!String.IsNullOrEmpty(cdnPath)) { cdnPath = FormatCdnUrl(assembly, cdnPath); } } return cdnPath; } internal static string GetWebResourceUrlInternal(Assembly assembly, string resourceName, bool htmlEncoded, bool forSubstitution, IScriptManager scriptManager) { bool enableCdn = (scriptManager != null && scriptManager.EnableCdn); return GetWebResourceUrlInternal(assembly, resourceName, htmlEncoded, forSubstitution, scriptManager, enableCdn: enableCdn); } internal static string GetWebResourceUrlInternal(Assembly assembly, string resourceName, bool htmlEncoded, bool forSubstitution, IScriptManager scriptManager, bool enableCdn) { // When this url is being inserted as a substitution in another resource, // it should just be "WebResource.axd?d=..." since the resource is already coming // from the app root (i.e. no need for a full absolute /app/WebResource.axd). // Otherwise we must return a path that is absolute (starts with '/') or // a full absolute uri (http://..) as in the case of a CDN Path. EnsureHandlerExistenceChecked(); if (!_handlerExists) { throw new InvalidOperationException(SR.GetString(SR.AssemblyResourceLoader_HandlerNotRegistered)); } Assembly effectiveAssembly = assembly; string effectiveResourceName = resourceName; bool debuggingEnabled = false; bool secureConnection; if (scriptManager != null) { debuggingEnabled = scriptManager.IsDebuggingEnabled; secureConnection = scriptManager.IsSecureConnection; } else { secureConnection = ((HttpContext.Current != null) && (HttpContext.Current.Request != null) && HttpContext.Current.Request.IsSecureConnection); debuggingEnabled = (HttpContext.Current != null) && HttpContext.Current.IsDebuggingEnabled; } int urlCacheKey = CreateWebResourceUrlCacheKey(assembly, resourceName, htmlEncoded, forSubstitution, enableCdn, debuggingEnabled, secureConnection); string url = (string)_urlCache[urlCacheKey]; if (url == null) { IScriptResourceDefinition definition = null; if (ClientScriptManager._scriptResourceMapping != null) { definition = ClientScriptManager._scriptResourceMapping.GetDefinition(resourceName, assembly); if (definition != null) { if (!String.IsNullOrEmpty(definition.ResourceName)) { effectiveResourceName = definition.ResourceName; } if (definition.ResourceAssembly != null) { effectiveAssembly = definition.ResourceAssembly; } } } string path = null; // if a resource mapping exists, take it's settings into consideration // it might supply a path or a cdnpath. if (definition != null) { if (enableCdn) { // Winner is first path defined, falling back on the effectiveResourceName/Assembly // Debug Mode : d.CdnDebugPath, d.DebugPath, *wra.CdnPath, d.Path // Release Mode: d.CdnPath , *wra.CdnPath, d.Path // * the WebResourceAttribute corresponding to the resource defined in the definition, not the // the original resource. // Also, if the definition has a CdnPath but it cannot be converted to a secure one during https, // the WRA's CdnPath is not considered. if (debuggingEnabled) { path = secureConnection ? definition.CdnDebugPathSecureConnection : definition.CdnDebugPath; if (String.IsNullOrEmpty(path)) { path = definition.DebugPath; if (String.IsNullOrEmpty(path)) { // Get CDN Path from the redirected resource name/assembly, not the original one, // but not if this is a secure connection and the only reason we didn't use the definition // cdn path is because it doesnt support secure connections. if (!secureConnection || String.IsNullOrEmpty(definition.CdnDebugPath)) { path = GetCdnPath(effectiveResourceName, effectiveAssembly, secureConnection); } if (String.IsNullOrEmpty(path)) { path = definition.Path; } } } } else { path = secureConnection ? definition.CdnPathSecureConnection : definition.CdnPath; if (String.IsNullOrEmpty(path)) { // Get CDN Path from the redirected resource name/assembly, not the original one // but not if this is a secure connection and the only reason we didn't use the definition // cdn path is because it doesnt support secure connections. if (!secureConnection || String.IsNullOrEmpty(definition.CdnPath)) { path = GetCdnPath(effectiveResourceName, effectiveAssembly, secureConnection); } if (String.IsNullOrEmpty(path)) { path = definition.Path; } } } } // cdn else { // Winner is first path defined, falling back on the effectiveResourceName/Assembly // Debug Mode : d.DebugPath, d.Path // Release Mode: d.Path if (debuggingEnabled) { path = definition.DebugPath; if (String.IsNullOrEmpty(path)) { path = definition.Path; } } else { path = definition.Path; } } } // does not have definition else if (enableCdn) { path = GetCdnPath(effectiveResourceName, effectiveAssembly, secureConnection); } if (!String.IsNullOrEmpty(path)) { // assembly based resource has been overridden by a path, // whether that be a CDN Path or a definition.Path or DebugPath. // We must return a path that is absolute (starts with '/') or // a full absolute uri (http://..) as in the case of a CDN Path. // An overridden Path that is not a CDN Path is required to be absolute // or app relative. if (UrlPath.IsAppRelativePath(path)) { // expand ~/. If it is rooted (/) or an absolute uri, no conversion needed if (_applicationRootPath == null) { url = VirtualPathUtility.ToAbsolute(path); } else { url = VirtualPathUtility.ToAbsolute(path, _applicationRootPath); } } else { // must be a full uri or already rooted. url = path; } if (htmlEncoded) { url = HttpUtility.HtmlEncode(url); } } else { string urlAssemblyName; Pair assemblyInfo = GetAssemblyInfo(effectiveAssembly); AssemblyName assemblyName = (AssemblyName)assemblyInfo.First; long assemblyDate = (long)assemblyInfo.Second; string assemblyVersion = assemblyName.Version.ToString(); if (effectiveAssembly.GlobalAssemblyCache) { // If the assembly is in the GAC, we need to store a full name to load the assembly later if (effectiveAssembly == HttpContext.SystemWebAssembly) { urlAssemblyName = "s"; } else { // Pack the necessary values into a more compact format than FullName StringBuilder builder = new StringBuilder(); builder.Append('f'); builder.Append(assemblyName.Name); builder.Append(','); builder.Append(assemblyVersion); builder.Append(','); if (assemblyName.CultureInfo != null) { builder.Append(assemblyName.CultureInfo.ToString()); } builder.Append(','); byte[] token = assemblyName.GetPublicKeyToken(); for (int i = 0; i < token.Length; i++) { builder.Append(token[i].ToString("x2", CultureInfo.InvariantCulture)); } urlAssemblyName = builder.ToString(); } } else { // Otherwise, we can just use a partial name urlAssemblyName = "p" + assemblyName.Name; } url = FormatWebResourceUrl(urlAssemblyName, effectiveResourceName, assemblyDate, htmlEncoded); if (!forSubstitution && (HttpRuntime.AppDomainAppVirtualPathString != null)) { // When this url is being inserted as a substitution in another resource, // it should just be "WebResource.axd?d=..." since the resource is already coming // from the app root (i.e. no need for a full absolute /app/WebResource.axd). url = UrlPath.Combine(HttpRuntime.AppDomainAppVirtualPathString, url); } } _urlCache[urlCacheKey] = url; } return url; } internal static bool IsValidWebResourceRequest(HttpContext context) { EnsureHandlerExistenceChecked(); if (!_handlerExists) { // If the handler isn't properly registered, it can't // possibly be a valid web resource request. return false; } string webResourceHandlerUrl = UrlPath.Combine(HttpRuntime.AppDomainAppVirtualPathString, _webResourceUrl); string requestPath = context.Request.Path; if (String.Equals(requestPath, webResourceHandlerUrl, StringComparison.OrdinalIgnoreCase)) { return true; } return false; } internal static void LogWebResourceFailure(string decryptedData, Exception exception) { string errorMessage = null; if (decryptedData != null) { errorMessage = SR.GetString(SR.Webevent_msg_RuntimeErrorWebResourceFailure_ResourceMissing, decryptedData); } else { errorMessage = SR.GetString(SR.Webevent_msg_RuntimeErrorWebResourceFailure_DecryptionError); } WebBaseEvent.RaiseSystemEvent(message: errorMessage, source: null, eventCode: WebEventCodes.RuntimeErrorWebResourceFailure, eventDetailCode: WebEventCodes.UndefinedEventDetailCode, exception: exception); } /// <internalonly/> bool IHttpHandler.IsReusable { get { return true; } } /// <internalonly/> void IHttpHandler.ProcessRequest(HttpContext context) { // Make sure we don't get any extra content in this handler (like Application.BeginRequest stuff); context.Response.Clear(); Stream resourceStream = null; string decryptedData = null; bool resourceIdentifierPresent = false; Exception exception = null; try { NameValueCollection queryString = context.Request.QueryString; string encryptedData = queryString["d"]; if (String.IsNullOrEmpty(encryptedData)) { throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest)); } resourceIdentifierPresent = true; decryptedData = Page.DecryptString(encryptedData, Purpose.AssemblyResourceLoader_WebResourceUrl); int separatorIndex = decryptedData.IndexOf('|'); Debug.Assert(separatorIndex != -1, "The decrypted data must contain a separator."); string assemblyName = decryptedData.Substring(0, separatorIndex); if (String.IsNullOrEmpty(assemblyName)) { throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_AssemblyNotFound, assemblyName)); } string resourceName = decryptedData.Substring(separatorIndex + 1); if (String.IsNullOrEmpty(resourceName)) { throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_ResourceNotFound, resourceName)); } char nameType = assemblyName[0]; assemblyName = assemblyName.Substring(1); Assembly assembly = null; // If it was a full name, create an AssemblyName and load from that if (nameType == 'f') { string[] parts = assemblyName.Split(','); if (parts.Length != 4) { throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest)); } AssemblyName realName = new AssemblyName(); realName.Name = parts[0]; realName.Version = new Version(parts[1]); string cultureString = parts[2]; // Try to determine the culture, using the invariant culture if there wasn't one (doesn't work without it) if (cultureString.Length > 0) { realName.CultureInfo = new CultureInfo(cultureString); } else { realName.CultureInfo = CultureInfo.InvariantCulture; } // Parse up the public key token which is represented as hex bytes in a string string token = parts[3]; byte[] tokenBytes = new byte[token.Length / 2]; for (int i = 0; i < tokenBytes.Length; i++) { tokenBytes[i] = Byte.Parse(token.Substring(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); } realName.SetPublicKeyToken(tokenBytes); assembly = Assembly.Load(realName); } // System.Web special case else if (nameType == 's') { assembly = typeof(AssemblyResourceLoader).Assembly; } // If was a partial name, just try to load it else if (nameType == 'p') { assembly = Assembly.Load(assemblyName); } else { throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest)); } // Dev10 Bugs 602949: Throw 404 if resource not found rather than do nothing. // This is done before creating the cache entry, since it could be that the assembly is loaded // later on without the app restarting. if (assembly == null) { throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest)); } bool performSubstitution = false; bool validResource = false; string contentType = String.Empty; // Check the validation cache to see if the resource has already been validated int cacheKey = HashCodeCombiner.CombineHashCodes(assembly.GetHashCode(), resourceName.GetHashCode()); Triplet resourceTriplet = (Triplet)_webResourceCache[cacheKey]; if (resourceTriplet != null) { validResource = (bool)resourceTriplet.First; contentType = (string)resourceTriplet.Second; performSubstitution = (bool)resourceTriplet.Third; } else { // Validation cache is empty, find out if it's valid and add it to the cache WebResourceAttribute wra = FindWebResourceAttribute(assembly, resourceName); if (wra != null) { resourceName = wra.WebResource; validResource = true; contentType = wra.ContentType; performSubstitution = wra.PerformSubstitution; } // Cache the result so we don't have to do this again try { if (validResource) { // a WebResourceAttribute was found, but does the resource really exist? validResource = false; resourceStream = assembly.GetManifestResourceStream(resourceName); validResource = (resourceStream != null); } } finally { // Cache the results, even if there was an exception getting the stream, // so we don't have to do this again Triplet triplet = new Triplet(); triplet.First = validResource; triplet.Second = contentType; triplet.Third = performSubstitution; _webResourceCache[cacheKey] = triplet; } } if (validResource) { // Cache the resource so we don't keep processing the same requests HttpCachePolicy cachePolicy = context.Response.Cache; cachePolicy.SetCacheability(HttpCacheability.Public); cachePolicy.VaryByParams["d"] = true; cachePolicy.SetOmitVaryStar(true); cachePolicy.SetExpires(DateTime.Now + TimeSpan.FromDays(365)); cachePolicy.SetValidUntilExpires(true); Pair assemblyInfo = GetAssemblyInfo(assembly); cachePolicy.SetLastModified(new DateTime((long)assemblyInfo.Second)); StreamReader reader = null; try { if (resourceStream == null) { // null in the case that _webResourceCache had the item resourceStream = assembly.GetManifestResourceStream(resourceName); } if (resourceStream != null) { context.Response.ContentType = contentType; if (performSubstitution) { // reader = new StreamReader(resourceStream, true); string content = reader.ReadToEnd(); // Looking for something of the form: WebResource("resourcename") MatchCollection matches = webResourceRegex.Matches(content); int startIndex = 0; StringBuilder newContent = new StringBuilder(); foreach (Match match in matches) { newContent.Append(content.Substring(startIndex, match.Index - startIndex)); Group group = match.Groups["resourceName"]; if (group != null) { string embeddedResourceName = group.ToString(); if (embeddedResourceName.Length > 0) { // if (String.Equals(embeddedResourceName, resourceName, StringComparison.Ordinal)) { throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_NoCircularReferences, resourceName)); } newContent.Append(GetWebResourceUrlInternal(assembly, embeddedResourceName, htmlEncoded: false, forSubstitution: true, scriptManager: null)); } } startIndex = match.Index + match.Length; } newContent.Append(content.Substring(startIndex, content.Length - startIndex)); StreamWriter writer = new StreamWriter(context.Response.OutputStream, reader.CurrentEncoding); writer.Write(newContent.ToString()); writer.Flush(); } else { byte[] buffer = new byte[1024]; Stream outputStream = context.Response.OutputStream; int count = 1; while (count > 0) { count = resourceStream.Read(buffer, 0, 1024); outputStream.Write(buffer, 0, count); } outputStream.Flush(); } } } finally { if (reader != null) reader.Close(); if (resourceStream != null) resourceStream.Close(); } } } catch(Exception e) { exception = e; // MSRC 10405: ---- all errors in the event of failure. In particular, we don't want to // bubble the inner exceptions up in the YSOD, as they might contain sensitive cryptographic // information. Setting 'resourceStream' to null will cause an appropriate exception to // be thrown. resourceStream = null; } // Dev10 Bugs 602949: 404 if the assembly is not found or if the resource does not exist if (resourceStream == null) { if (resourceIdentifierPresent) { LogWebResourceFailure(decryptedData, exception); } throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest)); } context.Response.IgnoreFurtherWrites(); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace applicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for VirtualNetworksOperations. /// </summary> public static partial class VirtualNetworksOperationsExtensions { /// <summary> /// Deletes the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> public static void Delete(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName) { operations.DeleteAsync(resourceGroupName, virtualNetworkName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the specified virtual network by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> public static VirtualNetwork Get(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, string expand = default(string)) { return operations.GetAsync(resourceGroupName, virtualNetworkName, expand).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified virtual network by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetwork> GetAsync(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a virtual network in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network operation /// </param> public static VirtualNetwork CreateOrUpdate(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, virtualNetworkName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a virtual network in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetwork> CreateOrUpdateAsync(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all virtual networks in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<VirtualNetwork> ListAll(this IVirtualNetworksOperations operations) { return operations.ListAllAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all virtual networks in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetwork>> ListAllAsync(this IVirtualNetworksOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all virtual networks in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<VirtualNetwork> List(this IVirtualNetworksOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets all virtual networks in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetwork>> ListAsync(this IVirtualNetworksOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Checks whether a private IP address is available for use. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='ipAddress'> /// The private IP address to be verified. /// </param> public static IPAddressAvailabilityResult CheckIPAddressAvailability(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, string ipAddress = default(string)) { return operations.CheckIPAddressAvailabilityAsync(resourceGroupName, virtualNetworkName, ipAddress).GetAwaiter().GetResult(); } /// <summary> /// Checks whether a private IP address is available for use. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='ipAddress'> /// The private IP address to be verified. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPAddressAvailabilityResult> CheckIPAddressAvailabilityAsync(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, string ipAddress = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CheckIPAddressAvailabilityWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, ipAddress, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> public static void BeginDelete(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName) { operations.BeginDeleteAsync(resourceGroupName, virtualNetworkName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Creates or updates a virtual network in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network operation /// </param> public static VirtualNetwork BeginCreateOrUpdate(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a virtual network in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetwork> BeginCreateOrUpdateAsync(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all virtual networks in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<VirtualNetwork> ListAllNext(this IVirtualNetworksOperations operations, string nextPageLink) { return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all virtual networks in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetwork>> ListAllNextAsync(this IVirtualNetworksOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all virtual networks in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<VirtualNetwork> ListNext(this IVirtualNetworksOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all virtual networks in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetwork>> ListNextAsync(this IVirtualNetworksOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// // PlayerEngine.cs // // Author: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2010 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Mono.Unix; using Gst; using Gst.BasePlugins; using Hyena; using Hyena.Data; using Banshee.Base; using Banshee.Streaming; using Banshee.MediaEngine; using Banshee.ServiceStack; using Banshee.Configuration; using Banshee.Preferences; namespace Banshee.GStreamerSharp { public class PlayerEngine : Banshee.MediaEngine.PlayerEngine { Pipeline pipeline; PlayBin2 playbin; uint iterate_timeout_id = 0; public PlayerEngine () { Log.InformationFormat ("GStreamer# {0} Initializing; {1}.{2}", typeof (Gst.Version).Assembly.GetName ().Version, Gst.Version.Description, Gst.Version.Nano); // Setup the gst plugins/registry paths if running Windows if (PlatformDetection.IsWindows) { var gst_paths = new string [] { Hyena.Paths.Combine (Hyena.Paths.InstalledApplicationPrefix, "gst-plugins") }; Environment.SetEnvironmentVariable ("GST_PLUGIN_PATH", String.Join (";", gst_paths)); Environment.SetEnvironmentVariable ("GST_PLUGIN_SYSTEM_PATH", ""); Environment.SetEnvironmentVariable ("GST_DEBUG", "1"); string registry = Hyena.Paths.Combine (Hyena.Paths.ApplicationData, "registry.bin"); if (!System.IO.File.Exists (registry)) { System.IO.File.Create (registry).Close (); } Environment.SetEnvironmentVariable ("GST_REGISTRY", registry); //System.Environment.SetEnvironmentVariable ("GST_REGISTRY_FORK", "no"); Log.DebugFormat ("GST_PLUGIN_PATH = {0}", Environment.GetEnvironmentVariable ("GST_PLUGIN_PATH")); } Gst.Application.Init (); pipeline = new Pipeline (); playbin = new PlayBin2 (); pipeline.Add (playbin); // Remember the volume from last time Volume = (ushort)PlayerEngineService.VolumeSchema.Get (); playbin.AddNotification ("volume", OnVolumeChanged); pipeline.Bus.AddWatch (OnBusMessage); OnStateChanged (PlayerState.Ready); } private bool OnBusMessage (Bus bus, Message msg) { switch (msg.Type) { case MessageType.Eos: StopIterating (); Close (false); OnEventChanged (PlayerEvent.EndOfStream); OnEventChanged (PlayerEvent.RequestNextTrack); break; case MessageType.StateChanged: State old_state, new_state, pending_state; msg.ParseStateChanged (out old_state, out new_state, out pending_state); HandleStateChange (old_state, new_state, pending_state); break; case MessageType.Buffering: int buffer_percent; msg.ParseBuffering (out buffer_percent); HandleBuffering (buffer_percent); break; case MessageType.Tag: Pad pad; TagList tag_list; msg.ParseTag (out pad, out tag_list); HandleTag (pad, tag_list); break; case MessageType.Error: Enum error_type; string err_msg, debug; msg.ParseError (out error_type, out err_msg, out debug); HandleError (error_type, err_msg, debug); break; } return true; } private void OnVolumeChanged (object o, Gst.GLib.NotifyArgs args) { OnEventChanged (PlayerEvent.Volume); } private void HandleError (Enum domain, string error_message, string debug) { Close (true); error_message = error_message ?? Catalog.GetString ("Unknown Error"); if (domain is ResourceError) { ResourceError domain_code = (ResourceError)domain; if (CurrentTrack != null) { switch (domain_code) { case ResourceError.NotFound: CurrentTrack.SavePlaybackError (StreamPlaybackError.ResourceNotFound); break; default: break; } } Log.Error (String.Format ("GStreamer resource error: {0}", domain_code), false); } else if (domain is StreamError) { StreamError domain_code = (StreamError)domain; if (CurrentTrack != null) { switch (domain_code) { case StreamError.CodecNotFound: CurrentTrack.SavePlaybackError (StreamPlaybackError.CodecNotFound); break; default: break; } } Log.Error (String.Format ("GStreamer stream error: {0}", domain_code), false); } else if (domain is CoreError) { CoreError domain_code = (CoreError)domain; if (CurrentTrack != null) { switch (domain_code) { case CoreError.MissingPlugin: CurrentTrack.SavePlaybackError (StreamPlaybackError.CodecNotFound); break; default: break; } } if (domain_code != CoreError.MissingPlugin) { Log.Error (String.Format ("GStreamer core error: {0}", (CoreError)domain), false); } } else if (domain is LibraryError) { Log.Error (String.Format ("GStreamer library error: {0}", (LibraryError)domain), false); } OnEventChanged (new PlayerEventErrorArgs (error_message)); } private void HandleBuffering (int buffer_percent) { OnEventChanged (new PlayerEventBufferingArgs (buffer_percent / 100.0)); } private void HandleStateChange (State old_state, State new_state, State pending_state) { StopIterating (); if (CurrentState != PlayerState.Loaded && old_state == State.Ready && new_state == State.Paused && pending_state == State.Playing) { OnStateChanged (PlayerState.Loaded); } else if (old_state == State.Paused && new_state == State.Playing && pending_state == State.VoidPending) { if (CurrentState == PlayerState.Loaded) { OnEventChanged (PlayerEvent.StartOfStream); } OnStateChanged (PlayerState.Playing); StartIterating (); } else if (CurrentState == PlayerState.Playing && old_state == State.Playing && new_state == State.Paused) { OnStateChanged (PlayerState.Paused); } } private void HandleTag (Pad pad, TagList tag_list) { foreach (string tag in tag_list.Tags) { if (String.IsNullOrEmpty (tag)) { continue; } if (tag_list.GetTagSize (tag) < 1) { continue; } List tags = tag_list.GetTag (tag); foreach (object o in tags) { OnTagFound (new StreamTag () { Name = tag, Value = o }); } } } private bool OnIterate () { // Actual iteration. OnEventChanged (PlayerEvent.Iterate); // Run forever until we are stopped return true; } private void StartIterating () { if (iterate_timeout_id > 0) { GLib.Source.Remove (iterate_timeout_id); iterate_timeout_id = 0; } iterate_timeout_id = GLib.Timeout.Add (200, OnIterate); } private void StopIterating () { if (iterate_timeout_id > 0) { GLib.Source.Remove (iterate_timeout_id); iterate_timeout_id = 0; } } protected override void OpenUri (SafeUri uri, bool maybeVideo) { if (pipeline.CurrentState == State.Playing || pipeline.CurrentState == State.Paused) { pipeline.SetState (Gst.State.Ready); } playbin.Uri = uri.AbsoluteUri; } public override void Play () { // HACK, I think that directsoundsink has a bug that resets its volume to 1.0 every time // This seems to fix bgo#641427 Volume = Volume; pipeline.SetState (Gst.State.Playing); OnStateChanged (PlayerState.Playing); } public override void Pause () { pipeline.SetState (Gst.State.Paused); OnStateChanged (PlayerState.Paused); } public override void Close (bool fullShutdown) { pipeline.SetState (State.Null); base.Close (fullShutdown); } public override string GetSubtitleDescription (int index) { return playbin.GetTextTags (index) .GetTag (Gst.Tag.LanguageCode) .Cast<string> () .FirstOrDefault (t => t != null); } public override ushort Volume { get { return (ushort) Math.Round (playbin.Volume * 100.0); } set { double volume = Math.Min (1.0, Math.Max (0, value / 100.0)); playbin.Volume = volume; PlayerEngineService.VolumeSchema.Set (value); } } public override bool CanSeek { get { return true; } } private static Format query_format = Format.Time; public override uint Position { get { long pos; playbin.QueryPosition (ref query_format, out pos); return (uint) ((ulong)pos / Gst.Clock.MSecond); } set { playbin.Seek (Format.Time, SeekFlags.Accurate, (long)(value * Gst.Clock.MSecond)); } } public override uint Length { get { long duration; playbin.QueryDuration (ref query_format, out duration); return (uint) ((ulong)duration / Gst.Clock.MSecond); } } private static string [] source_capabilities = { "file", "http", "cdda" }; public override IEnumerable SourceCapabilities { get { return source_capabilities; } } private static string [] decoder_capabilities = { "ogg", "wma", "asf", "flac", "mp3", "" }; public override IEnumerable ExplicitDecoderCapabilities { get { return decoder_capabilities; } } public override string Id { get { return "gstreamer-sharp"; } } public override string Name { get { return Catalog.GetString ("GStreamer# 0.10"); } } public override bool SupportsEqualizer { get { return false; } } public override VideoDisplayContextType VideoDisplayContextType { get { return VideoDisplayContextType.Unsupported; } } public override int SubtitleCount { get { return playbin.NText; } } public override int SubtitleIndex { set { if (value >= 0 && value < SubtitleCount) { playbin.CurrentText = value; } } } public override SafeUri SubtitleUri { set { playbin.Suburi = value.AbsoluteUri; } get { return new SafeUri (playbin.Suburi); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using Xunit; using Tests.HashSet_HashSetTestSupport; using Tests.HashSet_SetCollectionRelationshipTests; using Tests.HashSet_HashSet_SymmetricExceptWithTests; using Tests.HashSet_SetCollectionComparerTests; using Tests.HashSet_SetCollectionDuplicateItemTests; namespace Tests { namespace HashSet_HashSet_SymmetricExceptWithTests { public class HashSet_UnionWithTests { #region Set/Collection Relationship Tests (tests 1-42) //Test 1: other is null [Fact] public static void SymmetricExceptWith_Test1() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest1(out hashSet, out other); Assert.Throws<ArgumentNullException>(() => hashSet.SymmetricExceptWith(other)); //"ArgumentNullException expected." } //Test 2: other is empty and set is empty [Fact] public static void SymmetricExceptWith_Test2() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest2(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer); } //Test 3: Set/Collection Relationship Test 3: other is empty and set is single-item [Fact] public static void SymmetricExceptWith_Test3() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest3(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(1) }, hashSet.Comparer); } //Test 4: Set/Collection Relationship Test 4: other is empty and set is multi-item [Fact] public static void SymmetricExceptWith_Test4() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest4(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(1), new Item(3), new Item(-23) }, hashSet.Comparer); } //Test 5: Set/Collection Relationship Test 5: other is single-item and set is empty [Fact] public static void SymmetricExceptWith_Test5() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest5(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-23) }, hashSet.Comparer); } //Test 6: Set/Collection Relationship Test 6: other is single-item and set is single-item with a different item [Fact] public static void SymmetricExceptWith_Test6() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest6(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-23), new Item(34) }, hashSet.Comparer); } //Test 7: Set/Collection Relationship Test 7: other is single-item and set is single-item with the same item [Fact] public static void SymmetricExceptWith_Test7() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest7(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer); } //Test 8: Set/Collection Relationship Test 8: other is single-item and set is multi-item where set and other are disjoint [Fact] public static void SymmetricExceptWith_Test8() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest8(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-23), new Item(0), new Item(233), new Item(234) }, hashSet.Comparer); } //Test 9: Set/Collection Relationship Test 9: other is single-item and set is multi-item where set contains other [Fact] public static void SymmetricExceptWith_Test9() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest9(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-23), new Item(0) }, hashSet.Comparer); } //Test 10: Set/Collection Relationship Test 10: other is multi-item and set is empty [Fact] public static void SymmetricExceptWith_Test10() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest10(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-23), new Item(0), new Item(234) }, hashSet.Comparer); } //Test 11: Set/Collection Relationship Test 11: other is multi-item and set is single-item and set and other are disjoint [Fact] public static void SymmetricExceptWith_Test11() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest11(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-23), new Item(0), new Item(234), new Item(-222) }, hashSet.Comparer); } //Test 12: Set/Collection Relationship Test 12: other is multi-item and set is single-item and other contains set [Fact] public static void SymmetricExceptWith_Test12() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest12(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-23), new Item(234) }, hashSet.Comparer); } //Test 13: Set/Collection Relationship Test 13: other is multi-item and set is multi-item and set and other disjoint [Fact] public static void SymmetricExceptWith_Test13() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest13(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-23), new Item(0), new Item(23), new Item(222), new Item(234), new Item(322) }, hashSet.Comparer); } //Test 14: Set/Collection Relationship Test 14: other is multi-item and set is multi-item and set and other overlap but are non-comparable [Fact] public static void SymmetricExceptWith_Test14() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest14(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(0), new Item(23), new Item(222) }, hashSet.Comparer); } //Test 15: Set/Collection Relationship Test 15: other is multi-item and set is multi-item and other is a proper subset of set [Fact] public static void SymmetricExceptWith_Test15() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest15(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(23), new Item(222) }, hashSet.Comparer); } //Test 16: Set/Collection Relationship Test 16: other is multi-item and set is multi-item and set is a proper subset of other [Fact] public static void SymmetricExceptWith_Test16() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest16(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-23), new Item(234) }, hashSet.Comparer); } //Test 17: Set/Collection Relationship Test 17: other is multi-item and set is multi-item and set and other are equal [Fact] public static void SymmetricExceptWith_Test17() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest17(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer); } //Test 18: Set/Collection Relationship Test 18: other is set and set is empty [Fact] public static void SymmetricExceptWith_Test18() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest18(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer); } //Test 19: Set/Collection Relationship Test 19: other is set and set is single-item and set contains set [Fact] public static void SymmetricExceptWith_Test19() { HashSet<IEnumerable> hashSet; IEnumerable<IEnumerable> other; SetCollectionRelationshipTests.SetupTest19(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[0], hashSet.Comparer); } //Test 20: Set/Collection Relationship Test 20: other is set and set is single-item and set does not contain set [Fact] public static void SymmetricExceptWith_Test20() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest20(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer); } //Test 21: Set/Collection Relationship Test 21: other is set and set is multi-item and set contains set [Fact] public static void SymmetricExceptWith_Test21() { HashSet<IEnumerable> hashSet; IEnumerable<IEnumerable> other; SetCollectionRelationshipTests.SetupTest21(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[0], hashSet.Comparer); } //Test 22: Set/Collection Relationship Test 22: other is set and set is multi-item and set does not contain set [Fact] public static void SymmetricExceptWith_Test22() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest22(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer); } //Test 23: Set/Collection Relationship Test 23: item is only item in other: Item is the set and item is in the set [Fact] public static void SymmetricExceptWith_Test23() { List<int> item1 = new List<int>(new int[] { 1, 2 }); List<int> item2 = new List<int>(new int[] { 2, -1 }); HashSet<IEnumerable> hashSet; IEnumerable<IEnumerable> other; SetCollectionRelationshipTests.SetupTest23(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[] { item1, item2 }, hashSet.Comparer); } //Test 24: Set/Collection Relationship Test 24: item is only item in other: Item is the set and item is not in the set [Fact] public static void SymmetricExceptWith_Test24() { List<int> item1 = new List<int>(new int[] { 1, 2 }); List<int> item2 = new List<int>(new int[] { 2, -1 }); HashSet<IEnumerable> hashSet; IEnumerable<IEnumerable> other; SetCollectionRelationshipTests.SetupTest24(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[] { hashSet, item1, item2 }, hashSet.Comparer); } //Test 25: Set/Collection Relationship Test 25: item is only item in other: Item is Default<T> and in set. T is a numeric type [Fact] public static void SymmetricExceptWith_Test25() { HashSet<int> hashSet; IEnumerable<int> other; SetCollectionRelationshipTests.SetupTest25(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 4, 6, 7 }, hashSet.Comparer); } //Test 26: Set/Collection Relationship Test 26: item is only item in other: Item is Default<T> and in set. T is a reference type [Fact] public static void SymmetricExceptWith_Test26() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest26(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-3), new Item(3) }, hashSet.Comparer); } //Test 27: Set/Collection Relationship Test 27: item is only item in other: Item is Default<T> and not in set. T is a numeric type [Fact] public static void SymmetricExceptWith_Test27() { HashSet<int> hashSet; IEnumerable<int> other; SetCollectionRelationshipTests.SetupTest27(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 4, 0, 6, 7, 5 }, hashSet.Comparer); } //Test 28: Set/Collection Relationship Test 28: item is only item in other: Item is Default<T> and not in set. T is a reference type [Fact] public static void SymmetricExceptWith_Test28() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest28(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-3), new Item(3), null }, hashSet.Comparer); } //Test 29: Set/Collection Relationship Test 29: item is only item in other: Item is equal to an item in set but different. [Fact] public static void SymmetricExceptWith_Test29() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest29(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(3), new Item(2) }, hashSet.Comparer); } //Test 30: Set/Collection Relationship Test 30: item is only item in other: Item shares hash value with unequal item in set [Fact] public static void SymmetricExceptWith_Test30() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest30(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(1), new Item(3), new Item(2), new Item(-1) }, hashSet.Comparer); } //Test 31: Set/Collection Relationship Test 31: item is only item in other: Item was previously in set but not currently [Fact] public static void SymmetricExceptWith_Test31() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest31(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(1), new Item(3), new Item(2) }, hashSet.Comparer); } //Test 32: Set/Collection Relationship Test 32: item is only item in other: Item was previously removed from set but in it currently [Fact] public static void SymmetricExceptWith_Test32() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest32(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(3), new Item(2) }, hashSet.Comparer); } //Test 33: Set/Collection Relationship Test 33: item is one of the items in other: Item is the set and item is in the set [Fact] public static void SymmetricExceptWith_Test33() { List<int> item1 = new List<int>(new int[] { 1, 2 }); List<int> item2 = new List<int>(new int[] { 2, -1 }); IEnumerable item3 = new List<int>(new int[] { 1, 4, 5, 6, 8 }); IEnumerable item4 = new List<int>(new int[] { -1, 4, -5, 6, -8 }); HashSet<IEnumerable> hashSet; IEnumerable<IEnumerable> other; SetCollectionRelationshipTests.SetupTest33(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[] { item1, item2, item3, item4 }, hashSet.Comparer); } //Test 34: Set/Collection Relationship Test 34: item is one of the items in other: Item is the set and item is not in the set [Fact] public static void SymmetricExceptWith_Test34() { List<int> item1 = new List<int>(new int[] { 1, 2 }); List<int> item2 = new List<int>(new int[] { 2, -1 }); IEnumerable item3 = new List<int>(new int[] { 1, 4, 5, 6, 8 }); IEnumerable item4 = new List<int>(new int[] { -1, 4, -5, 6, -8 }); HashSet<IEnumerable> hashSet; IEnumerable<IEnumerable> other; SetCollectionRelationshipTests.SetupTest34(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[] { hashSet, item1, item2, item3, item4 }, hashSet.Comparer); } //Test 35: Set/Collection Relationship Test 35: item is one of the items in other: Item is Default<T> and in set. T is a numeric type [Fact] public static void SymmetricExceptWith_Test35() { HashSet<int> hashSet; IEnumerable<int> other; SetCollectionRelationshipTests.SetupTest35(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 4, 6, 7, 111, -111 }, hashSet.Comparer); } //Test 36: Set/Collection Relationship Test 36: item is one of the items in other: Item is Default<T> and in set. T is a reference type [Fact] public static void SymmetricExceptWith_Test36() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest36(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-3), new Item(3), new Item(292), new Item(-222) }, hashSet.Comparer); } //Test 37: Set/Collection Relationship Test 37: item is one of the items in other: Item is Default<T> and not in set. T is a numeric type [Fact] public static void SymmetricExceptWith_Test37() { HashSet<int> hashSet; IEnumerable<int> other; SetCollectionRelationshipTests.SetupTest37(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 4, 0, 6, 7, 5, 111, -111 }, hashSet.Comparer); } //Test 38: Set/Collection Relationship Test 38: item is one of the items in other: Item is Default<T> and not in set. T is a reference type [Fact] public static void SymmetricExceptWith_Test38() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest38(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-3), new Item(3), null, new Item(292), new Item(-222) }, hashSet.Comparer); } //Test 39: Set/Collection Relationship Test 39: item is one of the items in other: Item is equal to an item in set but different. [Fact] public static void SymmetricExceptWith_Test39() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest39(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(2), new Item(3), new Item(292), new Item(-222) }, hashSet.Comparer); } //Test 40: Set/Collection Relationship Test 40: item is one of the items in other: Item shares hash value with unequal item in set [Fact] public static void SymmetricExceptWith_Test40() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest40(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-1), new Item(1), new Item(2), new Item(3), new Item(292), new Item(-222) }, hashSet.Comparer); } //Test 41: Set/Collection Relationship Test 41: item is one of the items in other: Item was previously in set but not currently [Fact] public static void SymmetricExceptWith_Test41() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest41(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(1), new Item(2), new Item(3), new Item(292), new Item(-222) }, hashSet.Comparer); } //Test 42: Set/Collection Relationship Test 42: item is one of the items in other: Item was previously removed from set but in it currently [Fact] public static void SymmetricExceptWith_Test42() { HashSet<Item> hashSet; IEnumerable<Item> other; SetCollectionRelationshipTests.SetupTest42(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(2), new Item(3), new Item(292), new Item(-222) }, hashSet.Comparer); } #endregion #region Set/Collection Comparer Tests (tests 43-57) //Test 43: Set/Collection Comparer Test 1: Item is in collection: item same as element in set by default comparer, different by sets comparer - set contains item that is equal by sets comparer [Fact] public static void SymmetricExceptWith_Test43() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(34, -5); ValueItem item2 = new ValueItem(4, 4); ValueItem itemo1 = new ValueItem(134, -15); ValueItem itemo2 = new ValueItem(14, 14); ValueItem itemo3 = new ValueItem(19999, -12); SetCollectionComparerTests.SetupTest1(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, itemo1, itemo2, itemo3 }, hashSet.Comparer); } //Test 44: Set/Collection Comparer Test 2: Item is in collection: item same as element in set by default comparer, different by sets comparer - set does not contain item that is equal by sets comparer [Fact] public static void SymmetricExceptWith_Test44() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(34, -5); ValueItem item2 = new ValueItem(4, 4); ValueItem item3 = new ValueItem(9999, -20); ValueItem itemo1 = new ValueItem(134, -15); ValueItem itemo2 = new ValueItem(14, 14); ValueItem itemo3 = new ValueItem(19999, -12); ValueItem item = new ValueItem(34, -2); SetCollectionComparerTests.SetupTest2(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, item3, itemo1, itemo2, itemo3, item }, hashSet.Comparer); } //Test 45: Set/Collection Comparer Test 3: Item is in collection: item same as element in set by sets comparer, different by default comparer - set contains item that is equal by default comparer [Fact] public static void SymmetricExceptWith_Test45() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(34, -5); ValueItem item2 = new ValueItem(4, 4); ValueItem itemo1 = new ValueItem(134, -15); ValueItem itemo2 = new ValueItem(14, 14); ValueItem itemo3 = new ValueItem(19999, -12); SetCollectionComparerTests.SetupTest3(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, itemo1, itemo2, itemo3 }, hashSet.Comparer); } //Test 46: Set/Collection Comparer Test 4: Item is in collection: item same as element in set by sets comparer, different by default comparer - set does not contain item that is equal by default comparer [Fact] public static void SymmetricExceptWith_Test46() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(340, -5); ValueItem item2 = new ValueItem(4, 4); ValueItem itemo1 = new ValueItem(134, -15); ValueItem itemo2 = new ValueItem(14, 14); ValueItem itemo3 = new ValueItem(19999, -12); SetCollectionComparerTests.SetupTest4(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, itemo1, itemo2, itemo3 }, hashSet.Comparer); } //Test 48: Set/Collection Comparer Test 6: Item is only item in collection: item same as element in set by default comparer, different by sets comparer - set contains item that is equal by sets comparer [Fact] public static void SymmetricExceptWith_Test48() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(34, -5); ValueItem item2 = new ValueItem(4, 4); SetCollectionComparerTests.SetupTest6(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer); } //Test 49: Set/Collection Comparer Test 7: Item is only item in collection: item same as element in set by default comparer, different by sets comparer - set does not contain item that is equal by sets comparer [Fact] public static void SymmetricExceptWith_Test49() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(34, -5); ValueItem item2 = new ValueItem(4, 4); ValueItem item3 = new ValueItem(9999, -20); ValueItem item = new ValueItem(34, -2); SetCollectionComparerTests.SetupTest7(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, item3, item }, hashSet.Comparer); } //Test 50: Set/Collection Comparer Test 8: Item is only item in collection: item same as element in set by sets comparer, different by default comparer - set contains item that is equal by default comparer [Fact] public static void SymmetricExceptWith_Test50() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(34, -5); ValueItem item2 = new ValueItem(4, 4); SetCollectionComparerTests.SetupTest8(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer); } //Test 51: Set/Collection Comparer Test 9: Item is only item in collection: item same as element in set by sets comparer, different by default comparer - set does not contain item that is equal by default comparer [Fact] public static void SymmetricExceptWith_Test51() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(340, -5); ValueItem item2 = new ValueItem(4, 4); SetCollectionComparerTests.SetupTest9(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer); } //Test 52: Set/Collection Comparer Test 10: Item is only item in collection: item contains set and item in set with GetSetComparer<T> as comparer [Fact] public static void SymmetricExceptWith_Test52() { ValueItem itemn4 = new ValueItem(-4, -4); ValueItem itemn3 = new ValueItem(-3, -3); ValueItem itemn2 = new ValueItem(-2, -2); ValueItem itemn1 = new ValueItem(-1, -1); ValueItem item1 = new ValueItem(1, 1); ValueItem item2 = new ValueItem(2, 2); ValueItem item3 = new ValueItem(3, 3); ValueItem item4 = new ValueItem(4, 4); HashSet<IEnumerable> itemhs1 = new HashSet<IEnumerable>(new ValueItem[] { item1, item2, item3, item4 }); HashSet<IEnumerable> itemhs2 = new HashSet<IEnumerable>(new ValueItem[] { itemn1, itemn2, itemn3, itemn4 }); HashSet<HashSet<IEnumerable>> hashSet; IEnumerable<HashSet<IEnumerable>> other; SetCollectionComparerTests.SetupTest10(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSet<IEnumerable>[] expected = new HashSet<IEnumerable>[] { itemhs1, itemhs2 }; HashSet<IEnumerable>[] actual = new HashSet<IEnumerable>[2]; hashSet.CopyTo(actual, 0, 2); Assert.Equal(2, hashSet.Count); //"Should be equal" HashSetTestSupport.HashSetContains(actual, expected); } //Test 53: Set/Collection Comparer Test 11: Item is collection: item same as element in set by default comparer, different by sets comparer - set contains item that is equal by sets comparer [Fact] public static void SymmetricExceptWith_Test53() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(34, -5); ValueItem item2 = new ValueItem(4, 4); SetCollectionComparerTests.SetupTest11(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer); } //Test 54: Set/Collection Comparer Test 12: Item is collection: item same as element in set by default comparer, different by sets comparer - set does not contain item that is equal by sets comparer [Fact] public static void SymmetricExceptWith_Test54() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(34, -5); ValueItem item2 = new ValueItem(4, 4); ValueItem item3 = new ValueItem(9999, -20); ValueItem item = new ValueItem(34, -2); SetCollectionComparerTests.SetupTest12(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, item3, item }, hashSet.Comparer); } //Test 55: Set/Collection Comparer Test 13: Item is collection: item same as element in set by sets comparer, different by default comparer - set contains item that is equal by default comparer [Fact] public static void SymmetricExceptWith_Test55() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(34, -5); ValueItem item2 = new ValueItem(4, 4); SetCollectionComparerTests.SetupTest13(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer); } //Test 56: Set/Collection Comparer Test 14: Item is collection: item same as element in set by sets comparer, different by default comparer - set does not contain item that is equal by default comparer [Fact] public static void SymmetricExceptWith_Test56() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(340, -5); ValueItem item2 = new ValueItem(4, 4); SetCollectionComparerTests.SetupTest14(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer); } //Test 57: Set/Collection Comparer Test 15: Item is collection: item contains set and item in set with GetSetComparer<T> as comparer [Fact] public static void SymmetricExceptWith_Test57() { HashSet<HashSet<IEnumerable>> hashSet; IEnumerable<HashSet<IEnumerable>> other; SetCollectionComparerTests.SetupTest15(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<HashSet<IEnumerable>>.VerifyHashSet(hashSet, new HashSet<IEnumerable>[0], hashSet.Comparer); } #endregion #region Set/Collection Duplicate Item Tests (tests 58-73) //Test 58: Set/Collection Duplicate Item Test 1: other collection is multi-item with duplicates, set is empty [Fact] public static void SymmetricExceptWith_Test58() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(34, -5); ValueItem item2 = new ValueItem(4, 4); ValueItem item3 = new ValueItem(9999, -2); ValueItem item4 = new ValueItem(99, -2); SetCollectionDuplicateItemTests.SetupTest1(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, item3, item4 }, hashSet.Comparer); } //Test 59: Set/Collection Duplicate Item Test 2: other collection is multi-item with duplicates, set contains a single item not in other [Fact] public static void SymmetricExceptWith_Test59() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(34, -5); ValueItem item2 = new ValueItem(4, 4); ValueItem item3 = new ValueItem(9999, -2); ValueItem item4 = new ValueItem(99, -2); ValueItem item5 = new ValueItem(101, 101); SetCollectionDuplicateItemTests.SetupTest2(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, item3, item4, item5 }, hashSet.Comparer); } //Test 60: Set/Collection Duplicate Item Test 3: other collection is multi-item with duplicates, set contains a single item that is in other but not a duplicate in other [Fact] public static void SymmetricExceptWith_Test60() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(34, -5); ValueItem item2 = new ValueItem(4, 4); ValueItem item4 = new ValueItem(99, -2); SetCollectionDuplicateItemTests.SetupTest3(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, item4 }, hashSet.Comparer); } //Test 61: Set/Collection Duplicate Item Test 4: other collection is multi-item with duplicates, set contains a single item that is a duplicate in other [Fact] public static void SymmetricExceptWith_Test61() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem item1 = new ValueItem(34, -5); ValueItem item3 = new ValueItem(9999, -2); ValueItem item4 = new ValueItem(99, -2); SetCollectionDuplicateItemTests.SetupTest4(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item3, item4 }, hashSet.Comparer); } //Test 62: Set/Collection Duplicate Item Test 5: other collection is multi-item with duplicates, set is multi-item as well, set and other are disjoint [Fact] public static void SymmetricExceptWith_Test62() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem itemo1 = new ValueItem(34, -5); ValueItem itemo2 = new ValueItem(4, 4); ValueItem itemo3 = new ValueItem(9999, -2); ValueItem itemo4 = new ValueItem(99, -2); ValueItem items1 = new ValueItem(-34, 5); ValueItem items2 = new ValueItem(-4, -4); ValueItem items3 = new ValueItem(-9999, 2); ValueItem items4 = new ValueItem(-99, 2); SetCollectionDuplicateItemTests.SetupTest5(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items2, items3, items4, itemo1, itemo2, itemo3, itemo4 }, hashSet.Comparer); } //Test 63: Set/Collection Duplicate Item Test 6: other collection is multi-item with duplicates, set is multi-item as well, set and other overlap but are non-comparable, the overlap contains duplicate items from other [Fact] public static void SymmetricExceptWith_Test63() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem itemo1 = new ValueItem(34, -5); ValueItem items1 = new ValueItem(-34, 5); ValueItem items3 = new ValueItem(-9999, 2); SetCollectionDuplicateItemTests.SetupTest6(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items3, itemo1 }, hashSet.Comparer); } //Test 64: Set/Collection Duplicate Item Test 7: other collection is multi-item with duplicates, set is multi-item as well, set and other overlap but are non-comparable, the overlap does not contain duplicate items from other [Fact] public static void SymmetricExceptWith_Test64() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem itemo1 = new ValueItem(34, -5); ValueItem itemo2 = new ValueItem(4, 4); ValueItem itemo4 = new ValueItem(99, -2); ValueItem items1 = new ValueItem(-34, 5); ValueItem items3 = new ValueItem(-9999, 2); SetCollectionDuplicateItemTests.SetupTest7(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items3, itemo1, itemo2, itemo4 }, hashSet.Comparer); } //Test 65: Set/Collection Duplicate Item Test 8: other collection is multi-item with duplicates, set is multi-item as well, other is a proper subset of set [Fact] public static void SymmetricExceptWith_Test65() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem items1 = new ValueItem(-34, 5); ValueItem items2 = new ValueItem(-4, -4); ValueItem items3 = new ValueItem(-9999, 2); ValueItem items4 = new ValueItem(-99, 2); SetCollectionDuplicateItemTests.SetupTest8(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items2, items3, items4 }, hashSet.Comparer); } //Test 66: Set/Collection Duplicate Item Test 9: other collection is multi-item with duplicates, set is multi-item as well, set is a proper subset of other, set contains duplicate items from other [Fact] public static void SymmetricExceptWith_Test66() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem itemo1 = new ValueItem(34, -5); ValueItem itemo2 = new ValueItem(4, 4); ValueItem itemo3 = new ValueItem(9999, -2); ValueItem itemo4 = new ValueItem(99, -2); SetCollectionDuplicateItemTests.SetupTest9(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { itemo1, itemo2, itemo3, itemo4 }, hashSet.Comparer); } //Test 67: Set/Collection Duplicate Item Test 10: other collection is multi-item with duplicates, set is multi-item as well, set is a proper subset of other, set does not contain duplicate items from other [Fact] public static void SymmetricExceptWith_Test67() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem itemo1 = new ValueItem(34, -5); ValueItem itemo2 = new ValueItem(4, 4); ValueItem itemo3 = new ValueItem(9999, -2); ValueItem itemo4 = new ValueItem(99, -2); SetCollectionDuplicateItemTests.SetupTest10(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { itemo1, itemo2, itemo3, itemo4 }, hashSet.Comparer); } //Test 68: Set/Collection Duplicate Item Test 11: other collection is multi-item with duplicates, set is multi-item as well, set and other are equal [Fact] public static void SymmetricExceptWith_Test68() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; SetCollectionDuplicateItemTests.SetupTest11(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[0], hashSet.Comparer); } //Test 69: Set/Collection Duplicate Item Test 12: other contains duplicates by sets comparer but not by default comparer [Fact] public static void SymmetricExceptWith_Test69() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem itemo1 = new ValueItem(34, -5); ValueItem itemo3 = new ValueItem(9999, -12); ValueItem items1 = new ValueItem(-34, 5); ValueItem items3 = new ValueItem(-9999, 2); ValueItem items4 = new ValueItem(-99, -2); SetCollectionDuplicateItemTests.SetupTest12(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items3, items4, itemo1, itemo3 }, hashSet.Comparer); } //Test 70: Set/Collection Duplicate Item Test 13: other contains duplicates by default comparer but not by sets comparer [Fact] public static void SymmetricExceptWith_Test70() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem itemo1 = new ValueItem(34, -5); ValueItem itemo2 = new ValueItem(4, 4); ValueItem itemo3 = new ValueItem(-9999, -12); ValueItem itemo4 = new ValueItem(34, 12); ValueItem items1 = new ValueItem(-34, 5); ValueItem items2 = new ValueItem(-4, -4); ValueItem items3 = new ValueItem(-9999, 2); ValueItem items4 = new ValueItem(-99, -2); SetCollectionDuplicateItemTests.SetupTest13(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items2, items3, items4, itemo1, itemo2, itemo3, itemo4 }, hashSet.Comparer); } //Test 71: Set/Collection Duplicate Item Test 14: set contains duplicate items by default comparer, those items also in other [Fact] public static void SymmetricExceptWith_Test71() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem itemo1 = new ValueItem(-34, -5); ValueItem itemo2 = new ValueItem(4, 4); ValueItem itemo3 = new ValueItem(9999, -12); ValueItem itemo4 = new ValueItem(-99, 12); ValueItem items1 = new ValueItem(-34, 5); ValueItem items2 = new ValueItem(-99, -4); ValueItem items3 = new ValueItem(-34, 2); ValueItem items4 = new ValueItem(-99, -2); SetCollectionDuplicateItemTests.SetupTest14(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items2, items3, items4, itemo1, itemo2, itemo3, itemo4 }, hashSet.Comparer); } //Test 72: Set/Collection Duplicate Item Test 15: set contains duplicate items by default comparer, one of those items also in other [Fact] public static void SymmetricExceptWith_Test72() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem itemo1 = new ValueItem(34, -5); ValueItem itemo2 = new ValueItem(4, 4); ValueItem itemo3 = new ValueItem(9999, -12); ValueItem itemo4 = new ValueItem(-99, 12); ValueItem items1 = new ValueItem(-34, 5); ValueItem items2 = new ValueItem(-99, -4); ValueItem items3 = new ValueItem(-34, 2); ValueItem items4 = new ValueItem(-99, -2); SetCollectionDuplicateItemTests.SetupTest15(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items2, items3, items4, itemo1, itemo2, itemo3, itemo4 }, hashSet.Comparer); } //Test 73: Set/Collection Duplicate Item Test 16: set contains duplicate items by default comparer, those items not in other [Fact] public static void SymmetricExceptWith_Test73() { HashSet<ValueItem> hashSet; IEnumerable<ValueItem> other; ValueItem itemo1 = new ValueItem(34, -5); ValueItem itemo2 = new ValueItem(4, 4); ValueItem itemo3 = new ValueItem(9999, -12); ValueItem itemo4 = new ValueItem(99, 12); ValueItem items1 = new ValueItem(-34, 5); ValueItem items2 = new ValueItem(-99, -4); ValueItem items3 = new ValueItem(-34, 2); ValueItem items4 = new ValueItem(-99, -2); SetCollectionDuplicateItemTests.SetupTest16(out hashSet, out other); hashSet.SymmetricExceptWith(other); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items2, items3, items4, itemo1, itemo2, itemo3, itemo4 }, hashSet.Comparer); } #endregion } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace QuantConnect.Data.Market { /// <summary> /// Represents a bar sectioned not by time, but by some amount of movement in a value (for example, Closing price moving in $10 bar sizes) /// </summary> public class RenkoBar : BaseData { /// <summary> /// Gets the kind of the bar /// </summary> public RenkoType Type { get; private set; } /// <summary> /// Gets the height of the bar /// </summary> public decimal BrickSize { get; private set; } /// <summary> /// Gets the opening value that started this bar. /// </summary> public decimal Open { get; private set; } /// <summary> /// Gets the closing value or the current value if the bar has not yet closed. /// </summary> public decimal Close { get { return Value; } private set { Value = value; } } /// <summary> /// Gets the highest value encountered during this bar /// </summary> public decimal High { get; private set; } /// <summary> /// Gets the lowest value encountered during this bar /// </summary> public decimal Low { get; private set; } /// <summary> /// Gets the volume of trades during the bar. /// </summary> public decimal Volume { get; private set; } /// <summary> /// Gets the end time of this renko bar or the most recent update time if it <see cref="IsClosed"/> /// </summary> public override DateTime EndTime { get; set; } /// <summary> /// Gets the end time of this renko bar or the most recent update time if it <see cref="IsClosed"/> /// </summary> [Obsolete("RenkoBar.End is obsolete. Please use RenkoBar.EndTime property instead.")] public DateTime End { get { return EndTime; } set { EndTime = value; } } /// <summary> /// Gets the time this bar started /// </summary> public DateTime Start { get { return Time; } private set { Time = value; } } /// <summary> /// Gets whether or not this bar is considered closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// The trend of the bar (i.e. Rising, Falling or NoDelta) /// </summary> public BarDirection Direction { get { if (Open < Close) return BarDirection.Rising; else if (Open > Close) return BarDirection.Falling; else return BarDirection.NoDelta; } } /// <summary> /// The "spread" of the bar /// </summary> public decimal Spread { get { return Math.Abs(Close - Open); } } /// <summary> /// Initializes a new default instance of the <see cref="RenkoBar"/> class. /// </summary> public RenkoBar() { } /// <summary> /// Initializes a new instance of the <see cref="RenkoBar"/> class with the specified values /// </summary> /// <param name="symbol">The symbol of this data</param> /// <param name="time">The start time of the bar</param> /// <param name="brickSize">The size of each renko brick</param> /// <param name="open">The opening price for the new bar</param> /// <param name="volume">Any initial volume associated with the data</param> public RenkoBar(Symbol symbol, DateTime time, decimal brickSize, decimal open, decimal volume) { Type = RenkoType.Classic; Symbol = symbol; Start = time; EndTime = time; BrickSize = brickSize; Open = open; Close = open; Volume = volume; High = open; Low = open; } /// <summary> /// Initializes a new instance of the <see cref="RenkoBar"/> class with the specified values /// </summary> /// <param name="symbol">The symbol of this data</param> /// <param name="start">The start time of the bar</param> /// <param name="endTime">The end time of the bar</param> /// <param name="brickSize">The size of each wicko brick</param> /// <param name="open">The opening price for the new bar</param> /// <param name="high">The high price for the new bar</param> /// <param name="low">The low price for the new bar</param> /// <param name="close">The closing price for the new bar</param> public RenkoBar(Symbol symbol, DateTime start, DateTime endTime, decimal brickSize, decimal open, decimal high, decimal low, decimal close) { Type = RenkoType.Wicked; Symbol = symbol; Start = start; EndTime = endTime; BrickSize = brickSize; Open = open; Close = close; Volume = 0; High = high; Low = low; } /// <summary> /// Updates this <see cref="RenkoBar"/> with the specified values and returns whether or not this bar is closed /// </summary> /// <param name="time">The current time</param> /// <param name="currentValue">The current value</param> /// <param name="volumeSinceLastUpdate">The volume since the last update called on this instance</param> /// <returns>True if this bar <see cref="IsClosed"/></returns> public bool Update(DateTime time, decimal currentValue, decimal volumeSinceLastUpdate) { if (Type == RenkoType.Wicked) throw new InvalidOperationException("A \"Wicked\" RenkoBar cannot be updated!"); // can't update a closed renko bar if (IsClosed) return true; if (Start == DateTime.MinValue) Start = time; EndTime = time; // compute the min/max closes this renko bar can have decimal lowClose = Open - BrickSize; decimal highClose = Open + BrickSize; Close = Math.Min(highClose, Math.Max(lowClose, currentValue)); Volume += volumeSinceLastUpdate; // determine if this data caused the bar to close if (currentValue <= lowClose || currentValue >= highClose) { IsClosed = true; } if (Close > High) High = Close; if (Close < Low) Low = Close; return IsClosed; } /// <summary> /// Reader Method :: using set of arguements we specify read out type. Enumerate /// until the end of the data stream or file. E.g. Read CSV file line by line and convert /// into data types. /// </summary> /// <returns>BaseData type set by Subscription Method.</returns> /// <param name="config">Config.</param> /// <param name="line">Line.</param> /// <param name="date">Date.</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode) { throw new NotSupportedException("RenkoBar does not support the Reader function. This function should never be called on this type."); } /// <summary> /// Return the URL string source of the file. This will be converted to a stream /// </summary> /// <param name="config">Configuration object</param> /// <param name="date">Date of this source file</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>String URL of source file.</returns> public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode) { throw new NotSupportedException("RenkoBar does not support the GetSource function. This function should never be called on this type."); } /// <summary> /// Return a new instance clone of this object, used in fill forward /// </summary> /// <remarks> /// This base implementation uses reflection to copy all public fields and properties /// </remarks> /// <returns>A clone of the current object</returns> public override BaseData Clone() { return new RenkoBar { Type = Type, BrickSize = BrickSize, Open = Open, Volume = Volume, Close = Close, EndTime = EndTime, High = High, IsClosed = IsClosed, Low = Low, Time = Time, Value = Value, Symbol = Symbol, DataType = DataType }; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Configuration; using System.Net; using System.Reflection; using System.Threading; using ASC.Common.Utils; using ASC.Core; using ASC.Core.Common.Contracts; using ASC.Core.Configuration; using ASC.Core.Notify; using ASC.Core.Notify.Jabber; using ASC.CRM.Core; using ASC.CRM.Core.Dao; using ASC.CRM.Core.Entities; using ASC.ElasticSearch; using ASC.Feed.Aggregator.Config; using ASC.Feed.Data; using ASC.HealthCheck.Classes; using ASC.HealthCheck.Resources; using ASC.Notify.Messages; using ASC.Web.CRM.Core; using Autofac; using log4net; namespace ASC.HealthCheck.Models { public abstract class Service : ICloneable { public int Attempt { get; set; } public ServiceEnum ServiceName { get; set; } public string Status { get; set; } public string Message { get; set; } public abstract string Title { get; } protected ILog log; protected readonly string fakeUserId = HealthCheckRunner.FakeUserId; protected readonly string hubUrl = ConfigurationManager.AppSettings["web.hub"] ?? "http://localhost:9899/"; protected const int StateOnline = 1; protected Service(ServiceEnum serviceName) { ServiceName = serviceName; Message = string.Empty; Status = ServiceStatus.Running.GetStringStatus(); log = LogManager.GetLogger(typeof(Service)); } public abstract string Check(int tenantId); public object Clone() { return MemberwiseClone(); } public static Service CreateNewService(ServiceEnum serviceEnum) { switch (serviceEnum) { case ServiceEnum.OnlyofficeJabber: return new OnlyofficeJabberService(); case ServiceEnum.OnlyofficeSignalR: return new OnlyofficeSignalRService(); case ServiceEnum.OnlyofficeNotify: return new OnlyofficeNotifyService(); case ServiceEnum.OnlyofficeBackup: return new OnlyofficeBackupService(); case ServiceEnum.OnlyofficeFeed: return new OnlyofficeFeedService(); case ServiceEnum.OnlyofficeMailAggregator: return new OnlyofficeMailAggregatorService(); case ServiceEnum.OnlyofficeMailWatchdog: return new OnlyofficeMailWatchdogService(); case ServiceEnum.OnlyofficeAutoreply: return new OnlyofficeAutoreplyService(); case ServiceEnum.OnlyofficeIndex: return new OnlyofficeIndexService(); case ServiceEnum.EditorsFileConverter: return new EditorsFileConverterService(); case ServiceEnum.EditorsCoAuthoring: return new EditorsCoAuthoringService(); case ServiceEnum.EditorsSpellChecker: return new EditorsSpellCheckerService(); case ServiceEnum.MiniChat: return new MiniChatService(); } return null; } } public class OnlyofficeJabberService : Service { public OnlyofficeJabberService() : base(ServiceEnum.OnlyofficeJabber) { } public override string Title { get { return HealthCheckResource.JabberServiceTitle; } } public override string Check(int tenantId) { try { log.Debug("CheckJabberState"); using (var jabberServiceClient = new JabberServiceClientWcf()) { jabberServiceClient.Open(); var userGuid = new Guid(fakeUserId); var user = CoreContext.UserManager.GetUsers(userGuid); var status = jabberServiceClient.HealthCheck(user.UserName, tenantId); if (status == string.Empty) { log.Debug("Jabber is OK!"); return string.Empty; } log.ErrorFormat("Jabber is failed! {0}", status); return status; } } catch (Exception ex) { log.ErrorFormat("Jabber is failed! {0} {1} {2}", ex.Message, ex.StackTrace, ex.InnerException != null ? ex.InnerException.Message : string.Empty); return HealthCheckResource.ServiceCheckFailed; } } } public class OnlyofficeSignalRService : Service { public OnlyofficeSignalRService() : base(ServiceEnum.OnlyofficeSignalR) { } public override string Title { get { return HealthCheckResource.SignalRServiceTitle; } } public override string Check(int tenantId) { return ""; //HubConnection hubConnection = null; //try //{ // log.Debug("CheckMiniChatState"); // IDictionary<string, string> queryString = new Dictionary<string, string>(); // var fakeTenant = CoreContext.TenantManager.GetTenant(tenantId); // queryString["token"] = // Signature.Create(string.Join(",", fakeTenant.TenantId, fakeUserId, fakeTenant.TenantAlias)); // hubConnection = new HubConnection(hubUrl, queryString); // var hubProxy = hubConnection.CreateHubProxy("c"); // Chat // ServicePointManager.DefaultConnectionLimit = 10; // hubConnection.Start(new LongPollingTransport()).Wait(); // // initDataRetrieved // hubProxy.On<string, string, UserClass[], int, string>("idr", // (uName, displayUserName, users, userTenant, domain) => hubConnection.Stop()); // hubProxy.Invoke("cu", StateOnline).Wait(); // ConnectUser // // hubProxy.Invoke("gid").Wait(); // GetInitData // log.Debug("MiniChat is OK!"); // return string.Empty; //} //catch (Exception ex) //{ // log.ErrorFormat("SignalR is failed! {0} {1} {2}", ex.Message, ex.StackTrace, // ex.InnerException != null ? ex.InnerException.Message : string.Empty); // return HealthCheckResource.ServiceCheckFailed; //} //finally //{ // if (hubConnection != null) // { // hubConnection.Stop(); // } //} } } public class OnlyofficeNotifyService : Service { public OnlyofficeNotifyService() : base(ServiceEnum.OnlyofficeNotify) { } public override string Title { get { return HealthCheckResource.NotifyServiceTitle; } } public override string Check(int tenantId) { try { log.Debug("CheckNotifyState"); using (var notifyServiceClient = new NotifyServiceClient()) { var userGuid = new Guid(fakeUserId); var user = CoreContext.UserManager.GetUsers(userGuid); notifyServiceClient.SendNotifyMessage(new NotifyMessage { To = user.UserName, Subject = "Subject", ContentType = "ContentType", Content = "Content", Sender = Constants.NotifyMessengerSenderSysName, CreationDate = DateTime.UtcNow }); } log.Debug("Notify is OK!"); return string.Empty; } catch (Exception ex) { log.ErrorFormat("Notify is failed! {0} {1} {2}", ex.Message, ex.StackTrace, ex.InnerException != null ? ex.InnerException.Message : string.Empty); return HealthCheckResource.ServiceCheckFailed; } } } public class OnlyofficeBackupService : Service { public OnlyofficeBackupService() : base(ServiceEnum.OnlyofficeBackup) { } public override string Title { get { return HealthCheckResource.BackupServiceTitle; } } public override string Check(int tenantId) { try { log.Debug("CheckBackupState"); using (var backupServiceClient = new BackupServiceClient()) { var status = backupServiceClient.StartBackup(new StartBackupRequest { TenantId = tenantId, StorageType = BackupStorageType.DataStore }); try { while (!status.IsCompleted) { Thread.Sleep(1000); status = backupServiceClient.GetBackupProgress(tenantId); } } catch (Exception ex) { log.ErrorFormat("Backup is failed! {0} {1} {2}", status.Error, ex.Message, ex.StackTrace); return HealthCheckResource.BackupServiceWorksIncorrectMsg; } log.Debug("Backup is OK!"); return string.Empty; } } catch (Exception ex) { log.ErrorFormat("Backup is failed! {0} {1} {2}", ex.Message, ex.StackTrace, ex.InnerException != null ? ex.InnerException.Message : string.Empty); return HealthCheckResource.BackupServiceWorksIncorrectMsg; } } } public class OnlyofficeFeedService : Service { public OnlyofficeFeedService() : base(ServiceEnum.OnlyofficeFeed) { } public override string Title { get { return HealthCheckResource.FeedServiceTitle; } } public override string Check(int tenantId) { try { log.Debug("CheckFeedState"); var userGuid = new Guid(fakeUserId); CoreContext.TenantManager.SetCurrentTenant(tenantId); SecurityContext.AuthenticateMe(userGuid); var person = new Person { FirstName = "Homer", LastName = "Simpson", JobTitle = "Software engineer", About = "Cool dude" }; int personId; using (var scope = DIHelper.Resolve(tenantId)) { var dao = scope.Resolve<DaoFactory>().ContactDao; personId = dao.SaveContact(person); CRMSecurity.SetAccessTo(person, new List<Guid> {userGuid}); // waiting while service is collecting news var feedCfg = FeedConfigurationSection.GetFeedSection(); Thread.Sleep(feedCfg.AggregatePeriod + TimeSpan.FromSeconds(30)); var feedItemId = string.Format("person_{0}", personId); var feedItem = FeedAggregateDataProvider.GetFeedItem(feedItemId); if (feedItem == null) { log.ErrorFormat("Error! Feed Item is null, feedItemId = {0}", feedItemId); dao.DeleteContact(personId); FeedAggregateDataProvider.RemoveFeedItem(feedItemId); return HealthCheckResource.FeedService_NewsGenerationError; } dao.DeleteContact(personId); FeedAggregateDataProvider.RemoveFeedItem(feedItemId); log.Debug("Feed is OK!"); return string.Empty; } } catch (Exception ex) { log.ErrorFormat("Feed is failed! {0}, innerException = {1}", ex, ex.InnerException != null ? ex.InnerException.Message : string.Empty); return HealthCheckResource.ServiceCheckFailed; } } } public class OnlyofficeMailAggregatorService : Service { public OnlyofficeMailAggregatorService() : base(ServiceEnum.OnlyofficeMailAggregator) { } public override string Title { get { return HealthCheckResource.MailAggregatorServiceTitle; } } public override string Check(int tenantId) { try { log.Debug("CheckMailAggregatorState"); /*var userGuid = new Guid(fakeUserId); var user = CoreContext.UserManager.GetUsers(userGuid); var asc_auth_key = SecurityContext.AuthenticateMe(userGuid); string portalUrl = "http://localhost/"; var client = new RestClient(portalUrl); var request = new RestRequest("/api/2.0/mail/messages/send.json", Method.PUT); request.AddCookie("asc_auth_key", asc_auth_key); request.AddParameter("id", 0, ParameterType.QueryString); request.AddParameter("from", user.Email, ParameterType.QueryString); request.AddParameter("to[]", "<" + user.Email + ">", ParameterType.QueryString); request.AddParameter("subject", "test-subject", ParameterType.QueryString); request.AddParameter("body", "<p>test-body</p>", ParameterType.QueryString); request.AddParameter("streamId", Guid.NewGuid().ToString("N").ToLower(), ParameterType.QueryString); request.AddParameter("mimeMessageId", string.Empty, ParameterType.QueryString); request.AddParameter("mimeReplyToId", string.Empty, ParameterType.QueryString); request.AddParameter("importance", false, ParameterType.QueryString); // execute the request var response = client.Execute(request); if (response.StatusCode != HttpStatusCode.OK) { throw new Exception("Can't send mail using API. Response code = " + response.StatusCode, response.ErrorException); } var jObject = JObject.Parse(response.Content); // waiting for the end of the MailAggregator service activity Thread.Sleep(TimeSpan.FromSeconds(30)); request = new RestRequest(string.Format("/api/2.0/mail/messages/{0}.json", jObject["response"]), Method.GET); request.AddCookie("asc_auth_key", asc_auth_key); response = client.Execute(request); if (response.StatusCode != HttpStatusCode.OK) { throw new Exception("Can't get mail information using API. Response code = " + response.StatusCode, response.ErrorException); } jObject = JObject.Parse(response.Content); var folderObject = jObject["response"]["folder"]; if (folderObject == null) { throw new Exception("Can't get mail information using API. Wrong Json content: " + response.Content); } var folder = folderObject.ToString(); if (folder != INBOX_FOLDER) { throw new Exception("Can't get mail information from inbox folder. Wrong Json content: " + response.Content); } log.Debug("MailAggregator is OK!");*/ return string.Empty; } catch (Exception ex) { log.ErrorFormat("MailAggregator is failed! {0} {1} {2}", ex.Message, ex.StackTrace, ex.InnerException != null ? ex.InnerException.Message : string.Empty); return HealthCheckResource.ServiceCheckFailed; } } } public class OnlyofficeMailWatchdogService : Service { public OnlyofficeMailWatchdogService() : base(ServiceEnum.OnlyofficeMailWatchdog) { } public override string Title { get { return HealthCheckResource.MailWatchdogServiceTitle; } } public override string Check(int tenantId) { return string.Empty; } } public class OnlyofficeAutoreplyService : Service { public OnlyofficeAutoreplyService() : base(ServiceEnum.OnlyofficeAutoreply) { } public override string Title { get { return HealthCheckResource.AutoreplyServiceTitle; } } public override string Check(int tenantId) { return ""; } } public class OnlyofficeIndexService : Service { public OnlyofficeIndexService() : base(ServiceEnum.OnlyofficeIndex) { } public override string Title { get { return HealthCheckResource.IndexServiceTitle; } } public override string Check(int tenantId) { try { return FactoryIndexer.CheckState() ? HealthCheckResource.FullTextIndexServiceWorksCorrectMsg : HealthCheckResource.FullTextIndexServiceWorksIncorrectMsg; } catch (Exception ex) { log.ErrorFormat("TextIndexer is failed! {0}, innerException = {1}", ex, ex.InnerException != null ? ex.InnerException.Message : string.Empty); ReflectionTypeLoadException reflectionTypeLoadException = ex as ReflectionTypeLoadException; if (reflectionTypeLoadException != null) { foreach (var loaderException in reflectionTypeLoadException.LoaderExceptions) { log.ErrorFormat("loaderException = {0}", loaderException.ToString()); } } return HealthCheckResource.FullTextIndexServiceWorksIncorrectMsg; } } } public class EditorsFileConverterService : Service { public EditorsFileConverterService() : base(ServiceEnum.EditorsFileConverter) { } public override string Title { get { return HealthCheckResource.FileConverterServiceTitle; } } public override string Check(int tenantId) { try { using (var client = new WebClient()) { var html = client.DownloadString(ConfigurationManager.AppSettings["editors-canvas-service-url"]); return !string.IsNullOrWhiteSpace(html) ? string.Empty : HealthCheckResource.EditorsFileConverter_AccessError; } } catch (WebException) { return HealthCheckResource.EditorsFileConverter_AccessError; } catch (Exception ex) { log.ErrorFormat("EditorsFileConverter is failed! {0} {1} {2}", ex.Message, ex.StackTrace, ex.InnerException != null ? ex.InnerException.Message : string.Empty); return HealthCheckResource.ServiceCheckFailed; } } } public class EditorsCoAuthoringService : Service { public EditorsCoAuthoringService() : base(ServiceEnum.EditorsCoAuthoring) { } public override string Title { get { return HealthCheckResource.CoAuthoringServiceTitle; } } public override string Check(int tenantId) { try { using (var client = new WebClient()) { var html = client.DownloadString(ConfigurationManager.AppSettings["editors-coauthoring-service-url"]); return html.IndexOf("Server is functioning normally", StringComparison.OrdinalIgnoreCase) > -1 ? string.Empty : HealthCheckResource.EditorsCoAuthoring_AccessError; } } catch (WebException) { return HealthCheckResource.EditorsCoAuthoring_AccessError; } catch (Exception ex) { log.ErrorFormat("EditorsCoAuthoring is failed! {0} {1} {2}", ex.Message, ex.StackTrace, ex.InnerException != null ? ex.InnerException.Message : string.Empty); return HealthCheckResource.ServiceCheckFailed; } } } public class EditorsSpellCheckerService : Service { public EditorsSpellCheckerService() : base(ServiceEnum.EditorsSpellChecker) { } public override string Title { get { return HealthCheckResource.SpellCheckerServiceTitle; } } public override string Check(int tenantId) { try { using (var client = new WebClient()) { var html = client.DownloadString(ConfigurationManager.AppSettings["editors-spellchecker-service-url"]); return html.IndexOf("Server is functioning normally", StringComparison.OrdinalIgnoreCase) > -1 ? string.Empty : HealthCheckResource.EditorsSpellchecker_AccessError; } } catch (WebException) { return HealthCheckResource.EditorsSpellchecker_AccessError; } catch (Exception ex) { log.ErrorFormat("EditorsSpellchecker is failed! {0} {1} {2}", ex.Message, ex.StackTrace, ex.InnerException != null ? ex.InnerException.Message : string.Empty); return HealthCheckResource.ServiceCheckFailed; } } } public class MiniChatService : Service { public MiniChatService() : base(ServiceEnum.MiniChat) { } public override string Title { get { return HealthCheckResource.MiniChatServiceTitle; } } public override string Check(int tenantId) { return new OnlyofficeSignalRService().Check(tenantId); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Text; using AutoRest.Core.ClientModel; namespace AutoRest.Core.Utilities { /// <summary> /// Provides useful extension methods to simplify common coding tasks. /// </summary> public static class Extensions { /// <summary> /// Maps an action with side effects over a sequence. /// </summary> /// <param name='sequence'>The sequence to map over.</param> /// <param name='action'>The action to map.</param> /// <typeparam name='T'>Type of elements in the sequence.</typeparam> public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action) { if (sequence == null) { throw new ArgumentNullException("sequence"); } if (action == null) { throw new ArgumentNullException("action"); } foreach (T element in sequence) { action(element); } } /// <summary> /// Returns a collection of the descendant elements for this collection. /// </summary> /// <typeparam name='T'>Type of elements in the sequence.</typeparam> /// <param name="items">Child collection</param> /// <param name="childSelector">Child selector</param> /// <returns>List of all items and descendants of each item</returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By design.")] public static IEnumerable<T> Descendants<T>(this IEnumerable<T> items, Func<T, IEnumerable<T>> childSelector) { foreach (var item in items) { foreach (var childResult in childSelector(item).Descendants(childSelector)) yield return childResult; yield return item; } } /// <summary> /// Determines whether a sequence is empty. /// </summary> /// <typeparam name='T'>Type of elements in the sequence.</typeparam> /// <param name='sequence'>The sequence.</param> /// <returns>True if the sequence is empty, false otherwise.</returns> public static bool IsNullOrEmpty<T>(this IEnumerable<T> sequence) { if (sequence == null || !sequence.Any()) { return true; } return false; } /// <summary> /// Word wrap a string of text to a given width. /// </summary> /// <param name='text'>The text to word wrap.</param> /// <param name='width'>Width available to wrap.</param> /// <returns>Lines of word wrapped text.</returns> public static IEnumerable<string> WordWrap(this string text, int width) { Debug.Assert(text != null, "text should not be null."); int start = 0; // Start of the current line int end = 0; // End of the current line char last = ' '; // Last character processed // Walk the entire string, processing line by line for (int i = 0; i < text.Length; i++) { // Support newlines inside the comment text. if (text[i] == '\n') { yield return text.Substring(start, i - start + 1).Trim(); start = i + 1; end = start; last = ' '; continue; } // If our current line is longer than the desired wrap width, // we'll stop the line here if (i - start >= width && start != end) { // Yield the current line yield return text.Substring(start, end - start + 1).Trim(); // Set things up for the next line start = end + 1; end = start; last = ' '; } // If the last character was a space, mark that spot as a // candidate for a potential line break if (!char.IsWhiteSpace(last) && char.IsWhiteSpace(text[i])) { end = i - 1; } last = text[i]; } // Don't forget to include the last line of text if (start < text.Length) { yield return text.Substring(start, text.Length - start).Trim(); } } /// <summary> /// Performs shallow copy of properties from source into destination. /// </summary> /// <typeparam name="TU">Destination type</typeparam> /// <typeparam name="TV">Source type</typeparam> /// <param name="destination">Destination object.</param> /// <param name="source">Source object.</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "U", Justification = "Common naming for generics.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "V", Justification = "Common naming for generics.")] public static TU LoadFrom<TU, TV>(this TU destination, TV source) where TU : class where TV : class { if (destination == null) { throw new ArgumentNullException("destination"); } if (source == null) { throw new ArgumentNullException("source"); } var propertyNames = typeof(TU).GetProperties().Select(p => p.Name); foreach (var propertyName in propertyNames) { var destinationProperty = typeof(TU).GetBaseProperty(propertyName); var sourceProperty = typeof(TV).GetBaseProperty(propertyName); if (destinationProperty != null && sourceProperty != null && sourceProperty.PropertyType == destinationProperty.PropertyType && sourceProperty.SetMethod != null) { if (destinationProperty.PropertyType.IsGenericType && sourceProperty.GetValue(source, null) is IEnumerable) { var ctor = destinationProperty.PropertyType.GetConstructor(new[] { destinationProperty.PropertyType }); if (ctor != null) { destinationProperty.SetValue(destination, ctor.Invoke(new[] { sourceProperty.GetValue(source, null) }), null); continue; } } destinationProperty.SetValue(destination, sourceProperty.GetValue(source, null), null); } } return destination; } private static PropertyInfo GetBaseProperty(this Type type, string propertyName) { if (type != null) { PropertyInfo propertyInfo = type.GetProperty(propertyName); if (propertyInfo != null) { if (propertyInfo.SetMethod != null) { return propertyInfo; } if (type.BaseType != null) { return type.BaseType.GetBaseProperty(propertyName); } } } return null; } /// <summary> /// Converts the specified string to a camel cased string. /// </summary> /// <param name="value">The string to convert.</param> /// <returns>The camel case string.</returns> public static string ToCamelCase(this string value) { return CodeNamer.CamelCase(value); } /// <summary> /// Converts the specified string to a pascal cased string. /// </summary> /// <param name="value">The string to convert.</param> /// <returns>The pascal case string.</returns> public static string ToPascalCase(this string value) { return CodeNamer.PascalCase(value); } /// <summary> /// Escape reserved characters in xml comments with their escaped representations /// </summary> /// <param name="comment">The xml comment to escape</param> /// <returns>The text appropriately escaped for inclusing in an xml comment</returns> public static string EscapeXmlComment(this string comment) { if (comment == null) { return null; } return new StringBuilder(comment) .Replace("&", "&amp;") .Replace("<", "&lt;") .Replace(">", "&gt;").ToString(); } /// <summary> /// Returns true if the type is a PrimaryType with KnownPrimaryType matching typeToMatch. /// </summary> /// <param name="type"></param> /// <param name="typeToMatch"></param> /// <returns></returns> public static bool IsPrimaryType(this IType type, KnownPrimaryType typeToMatch) { if (type == null) { return false; } PrimaryType primaryType = type as PrimaryType; if (primaryType != null) { return primaryType.Type == typeToMatch; } return false; } /// <summary> /// Returns true if the <paramref name="type"/> is a PrimaryType with KnownPrimaryType matching <paramref name="typeToMatch"/> /// or a DictionaryType with ValueType matching <paramref name="typeToMatch"/> or a SequenceType matching <paramref name="typeToMatch"/> /// </summary> /// <param name="type"></param> /// <param name="typeToMatch"></param> /// <returns></returns> public static bool IsOrContainsPrimaryType(this IType type, KnownPrimaryType typeToMatch) { if (type == null) { return false; } if (type.IsPrimaryType(typeToMatch) || type.IsDictionaryContainingType(typeToMatch) || type.IsSequenceContainingType(typeToMatch)) { return true; } return false; } /// <summary> /// Returns true if the <paramref name="type"/> is a DictionaryType with ValueType matching <paramref name="typeToMatch"/> /// </summary> /// <param name="type"></param> /// <param name="typeToMatch"></param> /// <returns></returns> public static bool IsDictionaryContainingType(this IType type, KnownPrimaryType typeToMatch) { DictionaryType dictionaryType = type as DictionaryType; PrimaryType dictionaryPrimaryType = dictionaryType?.ValueType as PrimaryType; return dictionaryPrimaryType != null && dictionaryPrimaryType.IsPrimaryType(typeToMatch); } /// <summary> /// Returns true if the <paramref name="type"/>is a SequenceType matching <paramref name="typeToMatch"/> /// </summary> /// <param name="type"></param> /// <param name="typeToMatch"></param> /// <returns></returns> public static bool IsSequenceContainingType(this IType type, KnownPrimaryType typeToMatch) { SequenceType sequenceType = type as SequenceType; PrimaryType sequencePrimaryType = sequenceType?.ElementType as PrimaryType; return sequencePrimaryType != null && sequencePrimaryType.IsPrimaryType(typeToMatch); } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using org.swyn.foundation.db; namespace tdbadmin { /// <summary> /// Summary description for Form1. /// </summary> public class Login : System.Windows.Forms.Form { private System.Windows.Forms.Label log_l_dbn; private System.Windows.Forms.Label log_l_user; private System.Windows.Forms.TextBox log_e_dbn; private System.Windows.Forms.TextBox log_e_user; private System.Windows.Forms.Button log_b_ok; private System.Windows.Forms.Button log_b_cancel; private System.Windows.Forms.TextBox log_e_pwd; private System.Windows.Forms.Label log_l_pwd; private System.Windows.Forms.Label log_l_host; private System.Windows.Forms.Label log_l_dbtype; private System.Windows.Forms.TextBox log_e_host; private System.Windows.Forms.ComboBox log_c_dbtype; private System.Windows.Forms.ToolTip toolTip1; private System.ComponentModel.IContainer components; public Login() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } 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(); this.log_l_dbn = new System.Windows.Forms.Label(); this.log_l_user = new System.Windows.Forms.Label(); this.log_e_dbn = new System.Windows.Forms.TextBox(); this.log_e_user = new System.Windows.Forms.TextBox(); this.log_b_ok = new System.Windows.Forms.Button(); this.log_b_cancel = new System.Windows.Forms.Button(); this.log_e_pwd = new System.Windows.Forms.TextBox(); this.log_l_pwd = new System.Windows.Forms.Label(); this.log_l_host = new System.Windows.Forms.Label(); this.log_l_dbtype = new System.Windows.Forms.Label(); this.log_e_host = new System.Windows.Forms.TextBox(); this.log_c_dbtype = new System.Windows.Forms.ComboBox(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.SuspendLayout(); // // log_l_dbn // this.log_l_dbn.Location = new System.Drawing.Point(0, 0); this.log_l_dbn.Name = "log_l_dbn"; this.log_l_dbn.TabIndex = 0; this.log_l_dbn.Text = "Database"; this.toolTip1.SetToolTip(this.log_l_dbn, "Enter the database name, if you use Sql use your catalog name, if you use ODBC/Ol" + "eDB use your DSN name, if you use Oracle use your SID"); // // log_l_user // this.log_l_user.Location = new System.Drawing.Point(0, 24); this.log_l_user.Name = "log_l_user"; this.log_l_user.TabIndex = 1; this.log_l_user.Text = "User"; this.toolTip1.SetToolTip(this.log_l_user, "Enter the database user"); // // log_e_dbn // this.log_e_dbn.Location = new System.Drawing.Point(104, 0); this.log_e_dbn.Name = "log_e_dbn"; this.log_e_dbn.Size = new System.Drawing.Size(184, 20); this.log_e_dbn.TabIndex = 1; this.log_e_dbn.Text = "traveldb"; this.toolTip1.SetToolTip(this.log_e_dbn, "Default database called traveldb"); // // log_e_user // this.log_e_user.Location = new System.Drawing.Point(104, 24); this.log_e_user.Name = "log_e_user"; this.log_e_user.Size = new System.Drawing.Size(184, 20); this.log_e_user.TabIndex = 2; this.log_e_user.Text = ""; // // log_b_ok // this.log_b_ok.DialogResult = System.Windows.Forms.DialogResult.OK; this.log_b_ok.Location = new System.Drawing.Point(40, 144); this.log_b_ok.Name = "log_b_ok"; this.log_b_ok.Size = new System.Drawing.Size(64, 24); this.log_b_ok.TabIndex = 6; this.log_b_ok.Text = "OK"; this.log_b_ok.Click += new System.EventHandler(this.log_b_ok_Click); // // log_b_cancel // this.log_b_cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.log_b_cancel.Location = new System.Drawing.Point(184, 144); this.log_b_cancel.Name = "log_b_cancel"; this.log_b_cancel.Size = new System.Drawing.Size(64, 24); this.log_b_cancel.TabIndex = 7; this.log_b_cancel.Text = "Cancel"; this.log_b_cancel.Click += new System.EventHandler(this.log_b_cancel_Click); // // log_e_pwd // this.log_e_pwd.Location = new System.Drawing.Point(104, 48); this.log_e_pwd.Name = "log_e_pwd"; this.log_e_pwd.PasswordChar = '*'; this.log_e_pwd.Size = new System.Drawing.Size(184, 20); this.log_e_pwd.TabIndex = 3; this.log_e_pwd.Text = ""; // // log_l_pwd // this.log_l_pwd.Location = new System.Drawing.Point(0, 48); this.log_l_pwd.Name = "log_l_pwd"; this.log_l_pwd.TabIndex = 7; this.log_l_pwd.Text = "Password"; // // log_l_host // this.log_l_host.Location = new System.Drawing.Point(0, 72); this.log_l_host.Name = "log_l_host"; this.log_l_host.TabIndex = 8; this.log_l_host.Text = "Hostname"; this.toolTip1.SetToolTip(this.log_l_host, "Enter the hostname of the database server"); // // log_l_dbtype // this.log_l_dbtype.Location = new System.Drawing.Point(0, 96); this.log_l_dbtype.Name = "log_l_dbtype"; this.log_l_dbtype.TabIndex = 9; this.log_l_dbtype.Text = "DB Type"; this.toolTip1.SetToolTip(this.log_l_dbtype, "Choose your server database type"); // // log_e_host // this.log_e_host.Location = new System.Drawing.Point(104, 72); this.log_e_host.Name = "log_e_host"; this.log_e_host.Size = new System.Drawing.Size(184, 20); this.log_e_host.TabIndex = 4; this.log_e_host.Text = ""; // // log_c_dbtype // this.log_c_dbtype.Items.AddRange(new object[] { "SqlServer", "Oracle", "MySQL", "Odbc", "OleDb"}); this.log_c_dbtype.Location = new System.Drawing.Point(104, 96); this.log_c_dbtype.Name = "log_c_dbtype"; this.log_c_dbtype.Size = new System.Drawing.Size(184, 21); this.log_c_dbtype.TabIndex = 5; this.log_c_dbtype.Text = "SqlServer"; // // Login // this.AcceptButton = this.log_b_ok; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.log_b_cancel; this.ClientSize = new System.Drawing.Size(288, 197); this.Controls.Add(this.log_c_dbtype); this.Controls.Add(this.log_e_host); this.Controls.Add(this.log_e_pwd); this.Controls.Add(this.log_e_user); this.Controls.Add(this.log_e_dbn); this.Controls.Add(this.log_l_dbtype); this.Controls.Add(this.log_l_host); this.Controls.Add(this.log_l_pwd); this.Controls.Add(this.log_b_cancel); this.Controls.Add(this.log_b_ok); this.Controls.Add(this.log_l_user); this.Controls.Add(this.log_l_dbn); this.Name = "Login"; this.Text = "TravelDB Login"; this.ResumeLayout(false); } #endregion private void log_b_cancel_Click(object sender, System.EventArgs e) { // exit this.DialogResult = DialogResult.Cancel; Close(); } private void log_b_ok_Click(object sender, System.EventArgs e) { // load and set profile and open database try { tdb.User prof = new tdb.User(); prof.SetLogin(this.log_e_user.Text, this.log_e_pwd.Text, this.log_e_dbn.Text, this.log_c_dbtype.Text, this.log_e_host.Text); prof.LoadProfile(this.log_e_user.Text); this.DialogResult = DialogResult.OK; } catch (System.Data.SqlClient.SqlException) { this.DialogResult = DialogResult.Cancel; MessageBox.Show("travelDB error: Could not open the database"); } Close(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using VaultAtlas.DataModel; using VaultAtlas.DataModel.FlacAtlas; using VaultAtlas.DataModel.ModelUI; using System.Data; using System.Threading; using System.Windows.Forms; using VaultAtlas.DataModel.sqlite; namespace VaultAtlas.FlacAtlas { public class RecursiveImporter { public RecursiveImporter(IFileSystemDirectory rootDirectory) { _rootDirectory = rootDirectory; } private readonly IFileSystemDirectory _rootDirectory; private IProgressCallback _callback; /// <summary> /// Defines the target path for importing a sparse structure. Only the hierarchy leading to this path will be imported. /// </summary> private string _targetPath; public DiscDirectoryInfo TargetDirectoryInfo { get; private set; } private void RecursiveImport(DiscDirectoryInfo parentDir, IFileSystemDirectory sourceDir, Disc disc, bool importAllSub) { var targetDir = parentDir == null ? disc.GetRootDir() : new DiscDirectoryInfo(GetOrCreateDirectoryRow(parentDir, sourceDir, disc)); var subDirAdapter = targetDir.GetSubDirAdapter(); var filesAdapter = targetDir.GetFilesAdapter(); try { if (_targetPath != null && targetDir.GetLocalDirectoryPath().Equals(_targetPath)) { TargetDirectoryInfo = targetDir; importAllSub = true; } foreach (var subdir in sourceDir.GetSubDirectories()) { // support sparse structure if (!importAllSub && (_targetPath != null && !_targetPath.StartsWith(subdir.GetLocalDirectoryPath()))) { continue; } RecursiveImport(targetDir, subdir, disc, importAllSub); } foreach (var file in sourceDir.GetFiles()) { ImportFile(file, filesAdapter, targetDir.UID); } subDirAdapter.Update(); filesAdapter.Update(); } catch { } } private static DataRow GetOrCreateDirectoryRow(DiscDirectoryInfo parentDir, IFileSystemDirectory dir, Disc disc) { var parentDirAdapter = parentDir.GetSubDirAdapter(); var existingRows = parentDirAdapter.Table.Select("Name = '" + Util.MakeSelectSafe(dir.Name) + "'"); if (existingRows.Length > 0) return existingRows[0]; var newRow = parentDirAdapter.Table.NewRow(); newRow["UID"] = Guid.NewGuid().ToString(); newRow["Name"] = dir.Name; newRow["ParentUID"] = parentDir.UID; newRow["DiscNumber"] = disc.DiscNumber; newRow.Table.Rows.Add(newRow); return newRow; } private void ImportFile(IFileSystemFile file, AdapterBase filesAdapter, string directoryUid) { var fileName = file.Name; _callback.SetText(fileName); var newFileInfo = new DiscFileInfo(GetOrCreateFileRow(filesAdapter, fileName)); var size = file.Size; if (size <= 10000) { newFileInfo.FileContent = file.FileContent; } newFileInfo.UidDirectory = directoryUid; newFileInfo.Size = size; newFileInfo.LastModifiedDate = file.LastModifiedDate; var mediaprovider = MediaFileInfoProvider.GetMetaInfoProvider(file.Name); if (mediaprovider != null) { var formatInfo = mediaprovider.GetMediaFormatInfo(file.Name); newFileInfo.BitRate = formatInfo.BitRate; newFileInfo.SampleRate = formatInfo.SampleRate; newFileInfo.Bps = formatInfo.BitsPerSample; newFileInfo.NrChannels = formatInfo.NumberChannels; newFileInfo.FormatIdentifier = formatInfo.FormatIdentifier; newFileInfo.Length = formatInfo.LengthSeconds; } } private static DataRow GetOrCreateFileRow(AdapterBase filesAdapter, string fileName) { var existingRows = filesAdapter.Table.Select("Name = '" + Util.MakeSelectSafe(fileName) + "'"); if (existingRows.Length > 0) return existingRows[0]; var newFileInfo = filesAdapter.Table.NewRow(); newFileInfo["Name"] = fileName; newFileInfo["UID"] = Guid.NewGuid().ToString(); newFileInfo.Table.Rows.Add(newFileInfo); return newFileInfo; } public async Task<Disc> ImportDisc(IProgressCallback status, string discNumber, string volumeName, string serialNumber) { try { var presentBySerialNumber = DataManager.Get().Discs.Table.Select("SerialNumber = '" + DataManager.SafeSelect(serialNumber) + "'"); if (presentBySerialNumber.Length > 0) { var result = MessageBox.Show(string.Format(resources.AskAlreadyPresentVolumeIDOverwrite, presentBySerialNumber[0]["DiscNumber"], serialNumber), Constants.ApplicationName, MessageBoxButtons.YesNoCancel); if (result == DialogResult.Cancel) return null; if (result == DialogResult.Yes) { discNumber = presentBySerialNumber[0]["DiscNumber"].ToString(); // TODO QUANTUM this.manager.DeleteRecursive(this.manager.RootName + this.discNumber, false); } } var newRow = DataManager.Get().Discs.Table.NewRow(); newRow["DiscNumber"] = discNumber; newRow["VolumeID"] = volumeName; newRow["SerialNumber"] = serialNumber; newRow.Table.Rows.Add(newRow); var newDisc = new Disc(newRow); var rootDir = newDisc.GetRootDir(); await Task.Factory.StartNew(() => RecursiveImport(rootDir, _rootDirectory, newDisc, true)).ConfigureAwait(false); rootDir.GetSubDirAdapter().Update(); rootDir.UpdateFullPath(); return newDisc; } catch (ThreadAbortException) { // We want to exit gracefully here (if we're lucky) } catch (ThreadInterruptedException) { // And here, if we can } finally { if (_callback != null) _callback.End(); } return null; } public async Task<DiscDirectoryInfo> ImportPartialStructure(IProgressCallback status, DiscDirectoryInfo rootDir, string targetPath, Disc targetDisc) { try { _targetPath = targetPath; _callback = status; await Task.Factory.StartNew(() => RecursiveImport(null, _rootDirectory, targetDisc, false)).ConfigureAwait(false); rootDir.GetSubDirAdapter().Update(); rootDir.UpdateFullPath(); return TargetDirectoryInfo; } finally { if (_callback != null) _callback.End(); } } } }
/** * Copyright (c) 2015, GruntTheDivine All rights reserved. * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT ,STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. **/ using System.Threading; namespace Iodine.Runtime { [IodineBuiltinModule ("threading")] public class ThreadingModule : IodineModule { class IodineThread : IodineObject { sealed class ThreadTypeDefinition : IodineTypeDefinition { public ThreadTypeDefinition () : base ("Thread") { BindAttributes (this); SetDocumentation ( "Creates and controls a thread.", "@param func The function to invoke when this thread is created." ); } public override IodineObject BindAttributes (IodineObject obj) { obj.SetAttribute ("start", new BuiltinMethodCallback (Start, obj)); obj.SetAttribute ("abort", new BuiltinMethodCallback (Abort, obj)); obj.SetAttribute ("alive", new BuiltinMethodCallback (Alive, obj)); obj.SetAttribute ("join", new BuiltinMethodCallback (Join, obj)); return obj; } public override IodineObject Invoke (VirtualMachine vm, IodineObject [] args) { if (args.Length <= 0) { vm.RaiseException (new IodineArgumentException (1)); return null; } var func = args [0]; var newVm = new VirtualMachine (vm.Context); var threadStart = new ManualResetEvent (false); var t = new Thread (() => { try { threadStart.Set (); func.Invoke (newVm, new IodineObject [] { }); } catch (UnhandledIodineExceptionException ex) { vm.RaiseException (ex.OriginalException); } }); return new IodineThread (threadStart, t); } [BuiltinDocString ( "Starts the thread." )] static IodineObject Start (VirtualMachine vm, IodineObject self, IodineObject [] args) { var thread = self as IodineThread; if (thread == null) { vm.RaiseException (new IodineTypeException (TypeDefinition.Name)); return null; } thread.Start (); return null; } [BuiltinDocString ( "Terminates the thread." )] static IodineObject Abort (VirtualMachine vm, IodineObject self, IodineObject [] args) { var thread = self as IodineThread; if (thread == null) { vm.RaiseException (new IodineTypeException (TypeDefinition.Name)); return null; } thread.Value.Abort (); return null; } [BuiltinDocString ( "Returns true if this thread is alive, false if it is not." )] static IodineObject Alive (VirtualMachine vm, IodineObject self, IodineObject [] args) { var thread = self as IodineThread; if (thread == null) { vm.RaiseException (new IodineTypeException (TypeDefinition.Name)); return null; } return IodineBool.Create (thread.Value.IsAlive); } [BuiltinDocString ( "Joins this thread with the calling thread" )] static IodineObject Join (VirtualMachine vm, IodineObject self, IodineObject [] args) { var thread = self as IodineThread; if (thread == null) { vm.RaiseException (new IodineTypeException (TypeDefinition.Name)); return null; } thread.Value.Join (); return null; } } public static readonly IodineTypeDefinition TypeDefinition = new ThreadTypeDefinition (); public readonly Thread Value; readonly ManualResetEvent startEvent; public IodineThread (ManualResetEvent startEvent, Thread t) : base (TypeDefinition) { Value = t; this.startEvent = startEvent; } public void Start () { Value.Start (); startEvent.WaitOne (); } } class IodineConditionVariable : IodineObject { public static readonly IodineTypeDefinition TypeDefinition = new ConditionVariableTypeDefinition (); sealed class ConditionVariableTypeDefinition : IodineTypeDefinition { public ConditionVariableTypeDefinition () : base ("ConditionVariable") { BindAttributes (this); } public override IodineObject BindAttributes (IodineObject obj) { obj.SetAttribute ("wait", new BuiltinMethodCallback (Wait, obj)); obj.SetAttribute ("signal", new BuiltinMethodCallback (Signal, obj)); return obj; } public override IodineObject Invoke (VirtualMachine vm, IodineObject [] args) { return new IodineConditionVariable (); } [BuiltinDocString ( "Waits the condition variable to be signaled and releases the ", "supplied mutex.", "@param mutex The mutex" )] static IodineObject Wait (VirtualMachine vm, IodineObject self, IodineObject [] args) { var cv = self as IodineConditionVariable; if (cv == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } if (args.Length == 0) { vm.RaiseException (new IodineArgumentException (1)); return null; } var mutex = args [0] as IodineMutex; if (mutex == null) { vm.RaiseException (new IodineTypeException ("Mutex")); return null; } mutex.Release (); cv.Wait (); mutex.Acquire (); return null; } [BuiltinDocString ( "Signals the first thread waiting for this condition variable." )] static IodineObject Signal (VirtualMachine vm, IodineObject self, IodineObject [] args) { var cv = self as IodineConditionVariable; if (cv == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } cv.Signal (); return null; } } readonly ManualResetEvent resetEvent = new ManualResetEvent (false); public IodineConditionVariable () : base (TypeDefinition) { } public void Wait () { resetEvent.WaitOne (); } public void Signal () { resetEvent.Set (); } } class IodineMutex : IodineObject { public static readonly IodineTypeDefinition TypeDefinition = new MutexTypeDefinition (); sealed class MutexTypeDefinition : IodineTypeDefinition { public MutexTypeDefinition () : base ("Mutex") { BindAttributes (this); SetDocumentation ( "A simple mutual exclusion lock." ); } public override IodineObject BindAttributes (IodineObject obj) { obj.SetAttribute ("acquire", new BuiltinMethodCallback (Acquire, obj)); obj.SetAttribute ("release", new BuiltinMethodCallback (Release, obj)); obj.SetAttribute ("synchronize", new BuiltinMethodCallback (Synchronize, obj)); return obj; } public override IodineObject Invoke (VirtualMachine vm, IodineObject [] args) { return new IodineMutex (); } [BuiltinDocString ( "Enters the critical section, blocking all threads until release the lock is released." )] static IodineObject Acquire (VirtualMachine vm, IodineObject self, IodineObject [] args) { var spinlock = self as IodineMutex; if (spinlock == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } spinlock.Acquire (); return null; } [BuiltinDocString ( "Releases the mutex, allowing any threads blocked by this lock to continue." )] static IodineObject Release (VirtualMachine vm, IodineObject self, IodineObject [] args) { var spinlock = self as IodineMutex; if (spinlock == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } spinlock.Release (); return null; } [BuiltinDocString ( "Acquires a lock, then executes the supplied argument before releasing the lock.", "@param callable The function to synchronize" )] static IodineObject Synchronize (VirtualMachine vm, IodineObject self, IodineObject [] args) { var mutex = self as IodineMutex; if (mutex == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } if (args.Length == 0) { vm.RaiseException (new IodineArgumentException (1)); return null; } var func = args [0]; mutex.Acquire (); func.Invoke (vm, new IodineObject [] { }); mutex.Release (); return null; } } readonly Mutex mutex; public IodineMutex () : base (TypeDefinition) { mutex = new Mutex (); } public void Acquire () { mutex.WaitOne (); } public void Release () { mutex.ReleaseMutex (); } } public ThreadingModule () : base ("threading") { SetAttribute ("Thread", IodineThread.TypeDefinition); SetAttribute ("Mutex", IodineMutex.TypeDefinition); SetAttribute ("ConditionVariable", IodineConditionVariable.TypeDefinition); SetAttribute ("sleep", new BuiltinMethodCallback (Sleep, this)); } [BuiltinDocString ( "Suspends the current thread for t milliseconds.", "@param t How many milliseconds to suspend the thread for" )] IodineObject Sleep (VirtualMachine vm, IodineObject self, IodineObject [] args) { if (args.Length <= 0) { vm.RaiseException (new IodineArgumentException (1)); } var time = args [0] as IodineInteger; Thread.Sleep ((int)time.Value); return null; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Avalonia.Collections; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.Data; using Avalonia.Input; using Avalonia.LogicalTree; using Avalonia.Markup.Data; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Controls.UnitTests { public class TreeViewTests { [Fact] public void Items_Should_Be_Created() { var target = new TreeView { Template = CreateTreeViewTemplate(), Items = CreateTestTreeData(), }; CreateNodeDataTemplate(target); ApplyTemplates(target); Assert.Equal(new[] { "Root" }, ExtractItemHeader(target, 0)); Assert.Equal(new[] { "Child1", "Child2", "Child3" }, ExtractItemHeader(target, 1)); Assert.Equal(new[] { "Grandchild2a" }, ExtractItemHeader(target, 2)); } [Fact] public void Items_Should_Be_Created_Using_ItemTemplate_If_Present() { TreeView target; var root = new TestRoot { Child = target = new TreeView { Template = CreateTreeViewTemplate(), Items = CreateTestTreeData(), ItemTemplate = new FuncTreeDataTemplate<Node>( _ => new Canvas(), x => x.Children), } }; ApplyTemplates(target); var items = target.ItemContainerGenerator.Index.Items .OfType<TreeViewItem>() .ToList(); Assert.Equal(5, items.Count); Assert.All(items, x => Assert.IsType<Canvas>(x.HeaderPresenter.Child)); } [Fact] public void Root_ItemContainerGenerator_Containers_Should_Be_Root_Containers() { var target = new TreeView { Template = CreateTreeViewTemplate(), Items = CreateTestTreeData(), }; CreateNodeDataTemplate(target); ApplyTemplates(target); var container = (TreeViewItem)target.ItemContainerGenerator.Containers.Single().ContainerControl; var header = (TextBlock)container.Header; Assert.Equal("Root", header.Text); } [Fact] public void Root_TreeContainerFromItem_Should_Return_Descendant_Item() { var tree = CreateTestTreeData(); var target = new TreeView { Template = CreateTreeViewTemplate(), Items = tree, }; // For TreeViewItem to find its parent TreeView, OnAttachedToLogicalTree needs // to be called, which requires an IStyleRoot. var root = new TestRoot(); root.Child = target; CreateNodeDataTemplate(target); ApplyTemplates(target); var container = target.ItemContainerGenerator.Index.ContainerFromItem( tree[0].Children[1].Children[0]); Assert.NotNull(container); var header = ((TreeViewItem)container).Header; var headerContent = ((TextBlock)header).Text; Assert.Equal("Grandchild2a", headerContent); } [Fact] public void Clicking_Item_Should_Select_It() { var tree = CreateTestTreeData(); var target = new TreeView { Template = CreateTreeViewTemplate(), Items = tree, }; var visualRoot = new TestRoot(); visualRoot.Child = target; CreateNodeDataTemplate(target); ApplyTemplates(target); var item = tree[0].Children[1].Children[0]; var container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item); Assert.NotNull(container); container.RaiseEvent(new PointerPressedEventArgs { RoutedEvent = InputElement.PointerPressedEvent, MouseButton = MouseButton.Left, }); Assert.Equal(item, target.SelectedItem); Assert.True(container.IsSelected); } [Fact] public void Setting_SelectedItem_Should_Set_Container_Selected() { var tree = CreateTestTreeData(); var target = new TreeView { Template = CreateTreeViewTemplate(), Items = tree, }; var visualRoot = new TestRoot(); visualRoot.Child = target; CreateNodeDataTemplate(target); ApplyTemplates(target); var item = tree[0].Children[1].Children[0]; var container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item); Assert.NotNull(container); target.SelectedItem = item; Assert.True(container.IsSelected); } [Fact] public void LogicalChildren_Should_Be_Set() { var target = new TreeView { Template = CreateTreeViewTemplate(), Items = new[] { "Foo", "Bar", "Baz " }, }; ApplyTemplates(target); var result = target.GetLogicalChildren() .OfType<TreeViewItem>() .Select(x => x.Header) .OfType<TextBlock>() .Select(x => x.Text) .ToList(); Assert.Equal(new[] { "Foo", "Bar", "Baz " }, result); } [Fact] public void Removing_Item_Should_Remove_Itself_And_Children_From_Index() { var tree = CreateTestTreeData(); var target = new TreeView { Template = CreateTreeViewTemplate(), Items = tree, }; var root = new TestRoot(); root.Child = target; CreateNodeDataTemplate(target); ApplyTemplates(target); Assert.Equal(5, target.ItemContainerGenerator.Index.Items.Count()); tree[0].Children.RemoveAt(1); Assert.Equal(3, target.ItemContainerGenerator.Index.Items.Count()); } [Fact] public void DataContexts_Should_Be_Correctly_Set() { var items = new object[] { "Foo", new Node { Value = "Bar" }, new TextBlock { Text = "Baz" }, new TreeViewItem { Header = "Qux" }, }; var target = new TreeView { Template = CreateTreeViewTemplate(), DataContext = "Base", DataTemplates = { new FuncDataTemplate<Node>(x => new Button { Content = x }) }, Items = items, }; ApplyTemplates(target); var dataContexts = target.Presenter.Panel.Children .Cast<Control>() .Select(x => x.DataContext) .ToList(); Assert.Equal( new object[] { items[0], items[1], "Base", "Base" }, dataContexts); } [Fact] public void Control_Item_Should_Not_Be_NameScope() { var items = new object[] { new TreeViewItem(), }; var target = new TreeView { Template = CreateTreeViewTemplate(), Items = items, }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var item = target.Presenter.Panel.LogicalChildren[0]; Assert.Null(NameScope.GetNameScope((TreeViewItem)item)); } [Fact] public void DataTemplate_Created_Item_Should_Be_NameScope() { var items = new object[] { "foo", }; var target = new TreeView { Template = CreateTreeViewTemplate(), Items = items, }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var item = target.Presenter.Panel.LogicalChildren[0]; Assert.NotNull(NameScope.GetNameScope((TreeViewItem)item)); } [Fact] public void Should_React_To_Children_Changing() { var data = CreateTestTreeData(); var target = new TreeView { Template = CreateTreeViewTemplate(), Items = data, }; CreateNodeDataTemplate(target); ApplyTemplates(target); Assert.Equal(new[] { "Root" }, ExtractItemHeader(target, 0)); Assert.Equal(new[] { "Child1", "Child2", "Child3" }, ExtractItemHeader(target, 1)); Assert.Equal(new[] { "Grandchild2a" }, ExtractItemHeader(target, 2)); // Make sure that the binding to Node.Children does not get collected. GC.Collect(); data[0].Children = new AvaloniaList<Node> { new Node { Value = "NewChild1", } }; Assert.Equal(new[] { "Root" }, ExtractItemHeader(target, 0)); Assert.Equal(new[] { "NewChild1" }, ExtractItemHeader(target, 1)); } [Fact] public void Keyboard_Navigation_Should_Move_To_Last_Selected_Node() { using (UnitTestApplication.Start(TestServices.RealFocus)) { var focus = FocusManager.Instance; var navigation = AvaloniaLocator.Current.GetService<IKeyboardNavigationHandler>(); var data = CreateTestTreeData(); var target = new TreeView { Template = CreateTreeViewTemplate(), Items = data, }; var button = new Button(); var root = new TestRoot { Child = new StackPanel { Children = { target, button }, } }; CreateNodeDataTemplate(target); ApplyTemplates(target); var item = data[0].Children[0]; var node = target.ItemContainerGenerator.Index.ContainerFromItem(item); Assert.NotNull(node); target.SelectedItem = item; node.Focus(); Assert.Same(node, focus.Current); navigation.Move(focus.Current, NavigationDirection.Next); Assert.Same(button, focus.Current); navigation.Move(focus.Current, NavigationDirection.Next); Assert.Same(node, focus.Current); } } private void ApplyTemplates(TreeView tree) { tree.ApplyTemplate(); tree.Presenter.ApplyTemplate(); ApplyTemplates(tree.Presenter.Panel.Children); } private void ApplyTemplates(IEnumerable<IControl> controls) { foreach (TreeViewItem control in controls) { control.Template = CreateTreeViewItemTemplate(); control.ApplyTemplate(); control.Presenter.ApplyTemplate(); control.HeaderPresenter.ApplyTemplate(); ApplyTemplates(control.Presenter.Panel.Children); } } private IList<Node> CreateTestTreeData() { return new AvaloniaList<Node> { new Node { Value = "Root", Children = new AvaloniaList<Node> { new Node { Value = "Child1", }, new Node { Value = "Child2", Children = new AvaloniaList<Node> { new Node { Value = "Grandchild2a", }, }, }, new Node { Value = "Child3", }, } } }; } private void CreateNodeDataTemplate(IControl control) { control.DataTemplates.Add(new TestTreeDataTemplate()); } private IControlTemplate CreateTreeViewTemplate() { return new FuncControlTemplate<TreeView>(parent => new ItemsPresenter { Name = "PART_ItemsPresenter", [~ItemsPresenter.ItemsProperty] = parent[~ItemsControl.ItemsProperty], }); } private IControlTemplate CreateTreeViewItemTemplate() { return new FuncControlTemplate<TreeViewItem>(parent => new Panel { Children = { new ContentPresenter { Name = "PART_HeaderPresenter", [~ContentPresenter.ContentProperty] = parent[~TreeViewItem.HeaderProperty], }, new ItemsPresenter { Name = "PART_ItemsPresenter", [~ItemsPresenter.ItemsProperty] = parent[~ItemsControl.ItemsProperty], } } }); } private List<string> ExtractItemHeader(TreeView tree, int level) { return ExtractItemContent(tree.Presenter.Panel, 0, level) .Select(x => x.Header) .OfType<TextBlock>() .Select(x => x.Text) .ToList(); } private IEnumerable<TreeViewItem> ExtractItemContent(IPanel panel, int currentLevel, int level) { foreach (TreeViewItem container in panel.Children) { if (container.Template == null) { container.Template = CreateTreeViewItemTemplate(); container.ApplyTemplate(); } if (currentLevel == level) { yield return container; } else { foreach (var child in ExtractItemContent(container.Presenter.Panel, currentLevel + 1, level)) { yield return child; } } } } private class Node : NotifyingBase { private IAvaloniaList<Node> _children; public string Value { get; set; } public IAvaloniaList<Node> Children { get { return _children; } set { _children = value; RaisePropertyChanged(nameof(Children)); } } } private class TestTreeDataTemplate : ITreeDataTemplate { public IControl Build(object param) { var node = (Node)param; return new TextBlock { Text = node.Value }; } public bool SupportsRecycling => false; public InstancedBinding ItemsSelector(object item) { var obs = new ExpressionObserver(item, nameof(Node.Children)); return InstancedBinding.OneWay(obs); } public bool Match(object data) { return data is Node; } } } }
using System; using Microsoft.AspNetCore.Authentication.OAuth; using Microsoft.AspNetCore.Authentication.Twitter; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using MusicStoreB2C.Components; using MusicStoreB2C.Mocks.Common; using MusicStoreB2C.Mocks.Facebook; using MusicStoreB2C.Mocks.Google; using MusicStoreB2C.Mocks.MicrosoftAccount; using MusicStoreB2C.Mocks.Twitter; using MusicStoreB2C.Models; namespace MusicStoreB2C { public class StartupSocialTesting { private readonly Platform _platform; public StartupSocialTesting(IHostingEnvironment hostingEnvironment) { //Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, //then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely. var builder = new ConfigurationBuilder() .SetBasePath(hostingEnvironment.ContentRootPath) .AddJsonFile("config.json") .AddEnvironmentVariables() //All environment variables in the process's context flow in as configuration values. .AddJsonFile("configoverride.json", optional: true); // Used to override some configuration parameters that cannot be overridden by environment. Configuration = builder.Build(); _platform = new Platform(); } public IConfiguration Configuration { get; private set; } public void ConfigureServices(IServiceCollection services) { services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); // Add EF services to the services container if (_platform.UseInMemoryStore) { services.AddDbContext<MusicStoreContext>(options => options.UseInMemoryDatabase()); } else { services.AddDbContext<MusicStoreContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); } // Add Identity services to the services container services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Home/AccessDenied"); }) .AddEntityFrameworkStores<MusicStoreContext>() .AddDefaultTokenProviders(); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => { builder.WithOrigins("http://example.com"); }); }); // Add MVC services to the services container services.AddMvc(); //Add InMemoryCache services.AddSingleton<IMemoryCache, MemoryCache>(); // Add session related services. services.AddMemoryCache(); services.AddDistributedMemoryCache(); services.AddSession(); // Add the system clock service services.AddSingleton<ISystemClock, SystemClock>(); // Configure Auth services.AddAuthorization(options => { options.AddPolicy("ManageStore", new AuthorizationPolicyBuilder().RequireClaim("ManageStore", "Allowed").Build()); }); } public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(minLevel: LogLevel.Warning); app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage"); // Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the request pipeline. // Note: Not recommended for production. app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); // Configure Session. app.UseSession(); // Add static files to the request pipeline app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline app.UseIdentity(); app.UseFacebookAuthentication(new FacebookOptions { AppId = "[AppId]", AppSecret = "[AppSecret]", Events = new OAuthEvents() { OnCreatingTicket = TestFacebookEvents.OnCreatingTicket, OnTicketReceived = TestFacebookEvents.OnTicketReceived, OnRedirectToAuthorizationEndpoint = TestFacebookEvents.RedirectToAuthorizationEndpoint }, BackchannelHttpHandler = new FacebookMockBackChannelHttpHandler(), StateDataFormat = new CustomStateDataFormat(), Scope = { "email", "read_friendlists", "user_checkins" } }); app.UseGoogleAuthentication(new GoogleOptions { ClientId = "[ClientId]", ClientSecret = "[ClientSecret]", AccessType = "offline", Events = new OAuthEvents() { OnCreatingTicket = TestGoogleEvents.OnCreatingTicket, OnTicketReceived = TestGoogleEvents.OnTicketReceived, OnRedirectToAuthorizationEndpoint = TestGoogleEvents.RedirectToAuthorizationEndpoint }, StateDataFormat = new CustomStateDataFormat(), BackchannelHttpHandler = new GoogleMockBackChannelHttpHandler() }); app.UseTwitterAuthentication(new TwitterOptions { ConsumerKey = "[ConsumerKey]", ConsumerSecret = "[ConsumerSecret]", Events = new TwitterEvents() { OnCreatingTicket = TestTwitterEvents.OnCreatingTicket, OnTicketReceived = TestTwitterEvents.OnTicketReceived, OnRedirectToAuthorizationEndpoint = TestTwitterEvents.RedirectToAuthorizationEndpoint }, StateDataFormat = new CustomTwitterStateDataFormat(), BackchannelHttpHandler = new TwitterMockBackChannelHttpHandler() }); app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions { DisplayName = "MicrosoftAccount - Requires project changes", ClientId = "[ClientId]", ClientSecret = "[ClientSecret]", Events = new OAuthEvents() { OnCreatingTicket = TestMicrosoftAccountEvents.OnCreatingTicket, OnTicketReceived = TestMicrosoftAccountEvents.OnTicketReceived, OnRedirectToAuthorizationEndpoint = TestMicrosoftAccountEvents.RedirectToAuthorizationEndpoint }, BackchannelHttpHandler = new MicrosoftAccountMockBackChannelHandler(), StateDataFormat = new CustomStateDataFormat(), Scope = { "wl.basic", "wl.signin" } }); // Add MVC to the request pipeline app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller}/{action}", defaults: new { action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "api", template: "{controller}/{id?}"); }); //Populates the MusicStore sample data SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Reflection; using Microsoft.CSharp.RuntimeBinder.Semantics; namespace Microsoft.CSharp.RuntimeBinder { internal sealed class ExpressionTreeCallRewriter : ExprVisitorBase { ///////////////////////////////////////////////////////////////////////////////// // Members private sealed class ExpressionExpr : Expr { public readonly Expression Expression; public ExpressionExpr(Expression e) : base(0) { Expression = e; } } private readonly Dictionary<ExprCall, Expression> _DictionaryOfParameters; private readonly Expression[] _ListOfParameters; private readonly TypeManager _typeManager; // Counts how many EXPRSAVEs we've encountered so we know which index into the // parameter list we should be taking. private int _currentParameterIndex; ///////////////////////////////////////////////////////////////////////////////// private ExpressionTreeCallRewriter(TypeManager typeManager, Expression[] listOfParameters) { _typeManager = typeManager; _DictionaryOfParameters = new Dictionary<ExprCall, Expression>(); _ListOfParameters = listOfParameters; } ///////////////////////////////////////////////////////////////////////////////// public static Expression Rewrite(TypeManager typeManager, Expr pExpr, Expression[] listOfParameters) { ExpressionTreeCallRewriter rewriter = new ExpressionTreeCallRewriter(typeManager, listOfParameters); // We should have a EXPRBINOP thats an EK_SEQUENCE. The RHS of our sequence // should be a call to PM_EXPRESSION_LAMBDA. The LHS of our sequence is the // set of declarations for the parameters that we'll need. // Assert all of these first, and then unwrap them. Debug.Assert(pExpr != null); Debug.Assert(pExpr.Kind == ExpressionKind.Sequence); ExprBinOp binOp = (ExprBinOp)pExpr; Debug.Assert(binOp != null); Debug.Assert(binOp.OptionalRightChild is ExprCall); Debug.Assert(((ExprCall)binOp.OptionalRightChild).PredefinedMethod == PREDEFMETH.PM_EXPRESSION_LAMBDA); Debug.Assert(binOp.OptionalLeftChild != null); // Visit the left to generate the parameter construction. rewriter.Visit(binOp.OptionalLeftChild); ExprCall call = (ExprCall)binOp.OptionalRightChild; ExpressionExpr e = rewriter.Visit(call) as ExpressionExpr; return e.Expression; } ///////////////////////////////////////////////////////////////////////////////// protected override Expr VisitSAVE(ExprBinOp pExpr) { // Saves should have a LHS that is a CALL to PM_EXPRESSION_PARAMETER // and a RHS that is a WRAP of that call. ExprCall call = (ExprCall)pExpr.OptionalLeftChild; Debug.Assert(call?.PredefinedMethod == PREDEFMETH.PM_EXPRESSION_PARAMETER); Debug.Assert(pExpr.OptionalRightChild is ExprWrap); Expression parameter = _ListOfParameters[_currentParameterIndex++]; _DictionaryOfParameters.Add(call, parameter); return null; } ///////////////////////////////////////////////////////////////////////////////// protected override Expr VisitCALL(ExprCall pExpr) { if (pExpr.PredefinedMethod == PREDEFMETH.PM_FIRST) { return pExpr; } Expression exp; switch (pExpr.PredefinedMethod) { case PREDEFMETH.PM_EXPRESSION_LAMBDA: return GenerateLambda(pExpr); case PREDEFMETH.PM_EXPRESSION_CALL: exp = GenerateCall(pExpr); break; case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX: case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2: exp = GenerateArrayIndex(pExpr); break; case PREDEFMETH.PM_EXPRESSION_CONVERT: case PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED: case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED: exp = GenerateConvert(pExpr); break; case PREDEFMETH.PM_EXPRESSION_PROPERTY: exp = GenerateProperty(pExpr); break; case PREDEFMETH.PM_EXPRESSION_FIELD: exp = GenerateField(pExpr); break; case PREDEFMETH.PM_EXPRESSION_INVOKE: exp = GenerateInvoke(pExpr); break; case PREDEFMETH.PM_EXPRESSION_NEW: exp = GenerateNew(pExpr); break; case PREDEFMETH.PM_EXPRESSION_ADD: case PREDEFMETH.PM_EXPRESSION_AND: case PREDEFMETH.PM_EXPRESSION_DIVIDE: case PREDEFMETH.PM_EXPRESSION_EQUAL: case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR: case PREDEFMETH.PM_EXPRESSION_GREATERTHAN: case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL: case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT: case PREDEFMETH.PM_EXPRESSION_LESSTHAN: case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL: case PREDEFMETH.PM_EXPRESSION_MODULO: case PREDEFMETH.PM_EXPRESSION_MULTIPLY: case PREDEFMETH.PM_EXPRESSION_NOTEQUAL: case PREDEFMETH.PM_EXPRESSION_OR: case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT: case PREDEFMETH.PM_EXPRESSION_SUBTRACT: case PREDEFMETH.PM_EXPRESSION_ORELSE: case PREDEFMETH.PM_EXPRESSION_ANDALSO: // Checked case PREDEFMETH.PM_EXPRESSION_ADDCHECKED: case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED: case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED: exp = GenerateBinaryOperator(pExpr); break; case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED: // Checked case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED: exp = GenerateUserDefinedBinaryOperator(pExpr); break; case PREDEFMETH.PM_EXPRESSION_NEGATE: case PREDEFMETH.PM_EXPRESSION_NOT: case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED: exp = GenerateUnaryOperator(pExpr); break; case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED: exp = GenerateUserDefinedUnaryOperator(pExpr); break; case PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE: exp = GenerateConstantType(pExpr); break; case PREDEFMETH.PM_EXPRESSION_ASSIGN: exp = GenerateAssignment(pExpr); break; default: Debug.Assert(false, "Invalid Predefined Method in VisitCALL"); throw Error.InternalCompilerError(); } return new ExpressionExpr(exp); } #region Generators ///////////////////////////////////////////////////////////////////////////////// private Expr GenerateLambda(ExprCall pExpr) { // We always call Lambda(body, arrayinit) where the arrayinit // is the initialization of the parameters. return Visit(((ExprList)pExpr.OptionalArguments).OptionalElement); /* * // Do we need to do this? Expression e = (body as ExpressionExpr).Expression; if (e.Type.IsValueType) { // If we have a value type, convert it to object so that boxing // can happen. e = Expression.Convert(body.Expression, typeof(object)); } * */ } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateCall(ExprCall pExpr) { // Our arguments are: object, methodinfo, parameters. // The object is either an EXPRWRAP of a CALL, or a CALL that is a PM_CONVERT, whose // argument is the WRAP of a CALL. Deal with that first. ExprMethodInfo methinfo; ExprArrayInit arrinit; ExprList list = (ExprList)pExpr.OptionalArguments; if (list.OptionalNextListNode is ExprList next) { methinfo = (ExprMethodInfo)next.OptionalElement; arrinit = (ExprArrayInit)next.OptionalNextListNode; } else { methinfo = (ExprMethodInfo)list.OptionalNextListNode; arrinit = null; } Expression obj = null; MethodInfo m = GetMethodInfoFromExpr(methinfo); Expression[] arguments = GetArgumentsFromArrayInit(arrinit); if (m == null) { Debug.Assert(false, "How did we get a call that doesn't have a methodinfo?"); throw Error.InternalCompilerError(); } // The DLR is expecting the instance for a static invocation to be null. If we have // an instance method, fetch the object. if (!m.IsStatic) { obj = GetExpression(((ExprList)pExpr.OptionalArguments).OptionalElement); } return Expression.Call(obj, m, arguments); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateArrayIndex(ExprCall pExpr) { // We have two possibilities here - we're either a single index array, in which // case we'll be PM_EXPRESSION_ARRAYINDEX, or we have multiple dimensions, // in which case we are PM_EXPRESSION_ARRAYINDEX2. // // Our arguments then, are: object, index or object, indices. ExprList list = (ExprList)pExpr.OptionalArguments; Debug.Assert(list != null); Expression obj = GetExpression(list.OptionalElement); Expression[] indices; if (pExpr.PredefinedMethod == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX) { indices = new[] { GetExpression(list.OptionalNextListNode) }; } else { Debug.Assert(pExpr.PredefinedMethod == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2); indices = GetArgumentsFromArrayInit((ExprArrayInit)list.OptionalNextListNode); } return Expression.ArrayAccess(obj, indices); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateConvert(ExprCall pExpr) { PREDEFMETH pm = pExpr.PredefinedMethod; Expression e; Type t; if (pm == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED) { // If we have a user defined conversion, then we'll have the object // as the first element, and another list as a second element. This list // contains a TYPEOF as the first element, and the METHODINFO for the call // as the second. ExprList list = (ExprList)pExpr.OptionalArguments; ExprList list2 = (ExprList)list.OptionalNextListNode; e = GetExpression(list.OptionalElement); t = ((ExprTypeOf)list2.OptionalElement).SourceType.Type.AssociatedSystemType; if (e.Type.MakeByRefType() == t) { // We're trying to convert from a type to its by ref type. Don't do that. return e; } Debug.Assert((pExpr.Flags & EXPRFLAG.EXF_UNBOXRUNTIME) == 0); MethodInfo m = GetMethodInfoFromExpr((ExprMethodInfo)list2.OptionalNextListNode); if (pm == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED) { return Expression.Convert(e, t, m); } return Expression.ConvertChecked(e, t, m); } else { Debug.Assert(pm == PREDEFMETH.PM_EXPRESSION_CONVERT || pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED); // If we have a standard conversion, then we'll have some object as // the first list element (ie a WRAP or a CALL), and then a TYPEOF // as the second list element. ExprList list = (ExprList)pExpr.OptionalArguments; e = GetExpression(list.OptionalElement); t = ((ExprTypeOf)list.OptionalNextListNode).SourceType.Type.AssociatedSystemType; if (e.Type.MakeByRefType() == t) { // We're trying to convert from a type to its by ref type. Don't do that. return e; } if ((pExpr.Flags & EXPRFLAG.EXF_UNBOXRUNTIME) != 0) { // If we want to unbox this thing, return that instead of the convert. return Expression.Unbox(e, t); } if (pm == PREDEFMETH.PM_EXPRESSION_CONVERT) { return Expression.Convert(e, t); } return Expression.ConvertChecked(e, t); } } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateProperty(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; Expr instance = list.OptionalElement; Expr nextNode = list.OptionalNextListNode; ExprPropertyInfo propinfo; ExprArrayInit arguments; if (nextNode is ExprList nextList) { propinfo = nextList.OptionalElement as ExprPropertyInfo; arguments = nextList.OptionalNextListNode as ExprArrayInit; } else { propinfo = nextNode as ExprPropertyInfo; arguments = null; } PropertyInfo p = GetPropertyInfoFromExpr(propinfo); if (p == null) { Debug.Assert(false, "How did we get a prop that doesn't have a propinfo?"); throw Error.InternalCompilerError(); } if (arguments == null) { return Expression.Property(GetExpression(instance), p); } return Expression.Property(GetExpression(instance), p, GetArgumentsFromArrayInit(arguments)); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateField(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; ExprFieldInfo fieldInfo = (ExprFieldInfo)list.OptionalNextListNode; Debug.Assert(fieldInfo != null); Type t = fieldInfo.FieldType.AssociatedSystemType; FieldInfo f = fieldInfo.Field.AssociatedFieldInfo; // This is to ensure that for embedded nopia types, we have the // appropriate local type from the member itself; this is possible // because nopia types are not generic or nested. if (!t.IsGenericType && !t.IsNested) { t = f.DeclaringType; } // Now find the generic'ed one if we're generic. if (t.IsGenericType) { f = t.GetField(f.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); } return Expression.Field(GetExpression(list.OptionalElement), f); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateInvoke(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; return Expression.Invoke( GetExpression(list.OptionalElement), GetArgumentsFromArrayInit(list.OptionalNextListNode as ExprArrayInit)); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateNew(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; var constructor = GetConstructorInfoFromExpr(list.OptionalElement as ExprMethodInfo); var arguments = GetArgumentsFromArrayInit(list.OptionalNextListNode as ExprArrayInit); return Expression.New(constructor, arguments); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateConstantType(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; return Expression.Constant( GetObject(list.OptionalElement), ((ExprTypeOf)list.OptionalNextListNode).SourceType.Type.AssociatedSystemType); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateAssignment(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; return Expression.Assign( GetExpression(list.OptionalElement), GetExpression(list.OptionalNextListNode)); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateBinaryOperator(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; Debug.Assert(list != null); Expression arg1 = GetExpression(list.OptionalElement); Expression arg2 = GetExpression(list.OptionalNextListNode); switch (pExpr.PredefinedMethod) { case PREDEFMETH.PM_EXPRESSION_ADD: return Expression.Add(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_AND: return Expression.And(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_DIVIDE: return Expression.Divide(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_EQUAL: return Expression.Equal(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR: return Expression.ExclusiveOr(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_GREATERTHAN: return Expression.GreaterThan(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL: return Expression.GreaterThanOrEqual(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT: return Expression.LeftShift(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_LESSTHAN: return Expression.LessThan(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL: return Expression.LessThanOrEqual(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_MODULO: return Expression.Modulo(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_MULTIPLY: return Expression.Multiply(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_NOTEQUAL: return Expression.NotEqual(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_OR: return Expression.Or(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT: return Expression.RightShift(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_SUBTRACT: return Expression.Subtract(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_ORELSE: return Expression.OrElse(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_ANDALSO: return Expression.AndAlso(arg1, arg2); // Checked case PREDEFMETH.PM_EXPRESSION_ADDCHECKED: return Expression.AddChecked(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED: return Expression.MultiplyChecked(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED: return Expression.SubtractChecked(arg1, arg2); default: Debug.Assert(false, "Invalid Predefined Method in GenerateBinaryOperator"); throw Error.InternalCompilerError(); } } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateUserDefinedBinaryOperator(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; Expression arg1 = GetExpression(list.OptionalElement); Expression arg2 = GetExpression(((ExprList)list.OptionalNextListNode).OptionalElement); list = (ExprList)list.OptionalNextListNode; MethodInfo methodInfo; bool bIsLifted = false; if (list.OptionalNextListNode is ExprList next) { ExprConstant isLifted = (ExprConstant)next.OptionalElement; Debug.Assert(isLifted != null); bIsLifted = isLifted.Val.Int32Val == 1; methodInfo = GetMethodInfoFromExpr((ExprMethodInfo)next.OptionalNextListNode); } else { methodInfo = GetMethodInfoFromExpr((ExprMethodInfo)list.OptionalNextListNode); } switch (pExpr.PredefinedMethod) { case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED: return Expression.Add(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED: return Expression.And(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED: return Expression.Divide(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED: return Expression.Equal(arg1, arg2, bIsLifted, methodInfo); case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED: return Expression.ExclusiveOr(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED: return Expression.GreaterThan(arg1, arg2, bIsLifted, methodInfo); case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED: return Expression.GreaterThanOrEqual(arg1, arg2, bIsLifted, methodInfo); case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED: return Expression.LeftShift(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED: return Expression.LessThan(arg1, arg2, bIsLifted, methodInfo); case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED: return Expression.LessThanOrEqual(arg1, arg2, bIsLifted, methodInfo); case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED: return Expression.Modulo(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED: return Expression.Multiply(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED: return Expression.NotEqual(arg1, arg2, bIsLifted, methodInfo); case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED: return Expression.Or(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED: return Expression.RightShift(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED: return Expression.Subtract(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED: return Expression.OrElse(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED: return Expression.AndAlso(arg1, arg2, methodInfo); // Checked case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED: return Expression.AddChecked(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED: return Expression.MultiplyChecked(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED: return Expression.SubtractChecked(arg1, arg2, methodInfo); default: Debug.Assert(false, "Invalid Predefined Method in GenerateUserDefinedBinaryOperator"); throw Error.InternalCompilerError(); } } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateUnaryOperator(ExprCall pExpr) { PREDEFMETH pm = pExpr.PredefinedMethod; Expression arg = GetExpression(pExpr.OptionalArguments); switch (pm) { case PREDEFMETH.PM_EXPRESSION_NOT: return Expression.Not(arg); case PREDEFMETH.PM_EXPRESSION_NEGATE: return Expression.Negate(arg); case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED: return Expression.NegateChecked(arg); default: Debug.Assert(false, "Invalid Predefined Method in GenerateUnaryOperator"); throw Error.InternalCompilerError(); } } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateUserDefinedUnaryOperator(ExprCall pExpr) { PREDEFMETH pm = pExpr.PredefinedMethod; ExprList list = (ExprList)pExpr.OptionalArguments; Expression arg = GetExpression(list.OptionalElement); MethodInfo methodInfo = GetMethodInfoFromExpr((ExprMethodInfo)list.OptionalNextListNode); switch (pm) { case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED: return Expression.Not(arg, methodInfo); case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED: return Expression.Negate(arg, methodInfo); case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED: return Expression.UnaryPlus(arg, methodInfo); case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED: return Expression.NegateChecked(arg, methodInfo); default: Debug.Assert(false, "Invalid Predefined Method in GenerateUserDefinedUnaryOperator"); throw Error.InternalCompilerError(); } } #endregion #region Helpers ///////////////////////////////////////////////////////////////////////////////// private Expression GetExpression(Expr pExpr) { if (pExpr is ExprWrap wrap) { return _DictionaryOfParameters[(ExprCall)wrap.OptionalExpression]; } else if (pExpr is ExprConstant) { Debug.Assert(pExpr.Type.IsNullType()); return null; } else { // We can have a convert node or a call of a user defined conversion. ExprCall call = (ExprCall)pExpr; Debug.Assert(call != null); PREDEFMETH pm = call.PredefinedMethod; Debug.Assert(pm == PREDEFMETH.PM_EXPRESSION_CONVERT || pm == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT || pm == PREDEFMETH.PM_EXPRESSION_CALL || pm == PREDEFMETH.PM_EXPRESSION_PROPERTY || pm == PREDEFMETH.PM_EXPRESSION_FIELD || pm == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX || pm == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2 || pm == PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE || pm == PREDEFMETH.PM_EXPRESSION_NEW || // Binary operators. pm == PREDEFMETH.PM_EXPRESSION_ASSIGN || pm == PREDEFMETH.PM_EXPRESSION_ADD || pm == PREDEFMETH.PM_EXPRESSION_AND || pm == PREDEFMETH.PM_EXPRESSION_DIVIDE || pm == PREDEFMETH.PM_EXPRESSION_EQUAL || pm == PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR || pm == PREDEFMETH.PM_EXPRESSION_GREATERTHAN || pm == PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL || pm == PREDEFMETH.PM_EXPRESSION_LEFTSHIFT || pm == PREDEFMETH.PM_EXPRESSION_LESSTHAN || pm == PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL || pm == PREDEFMETH.PM_EXPRESSION_MODULO || pm == PREDEFMETH.PM_EXPRESSION_MULTIPLY || pm == PREDEFMETH.PM_EXPRESSION_NOTEQUAL || pm == PREDEFMETH.PM_EXPRESSION_OR || pm == PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT || pm == PREDEFMETH.PM_EXPRESSION_SUBTRACT || pm == PREDEFMETH.PM_EXPRESSION_ORELSE || pm == PREDEFMETH.PM_EXPRESSION_ANDALSO || pm == PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED || // Checked binary pm == PREDEFMETH.PM_EXPRESSION_ADDCHECKED || pm == PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED || pm == PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED || pm == PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED || // Unary operators. pm == PREDEFMETH.PM_EXPRESSION_NOT || pm == PREDEFMETH.PM_EXPRESSION_NEGATE || pm == PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED || // Checked unary pm == PREDEFMETH.PM_EXPRESSION_NEGATECHECKED || pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED || pm == PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED ); switch (pm) { case PREDEFMETH.PM_EXPRESSION_CALL: return GenerateCall(call); case PREDEFMETH.PM_EXPRESSION_CONVERT: case PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED: case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED: return GenerateConvert(call); case PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT: { ExprList list = (ExprList)call.OptionalArguments; return Expression.NewArrayInit( ((ExprTypeOf)list.OptionalElement).SourceType.Type.AssociatedSystemType, GetArgumentsFromArrayInit((ExprArrayInit)list.OptionalNextListNode)); } case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX: case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2: return GenerateArrayIndex(call); case PREDEFMETH.PM_EXPRESSION_NEW: return GenerateNew(call); case PREDEFMETH.PM_EXPRESSION_PROPERTY: return GenerateProperty(call); case PREDEFMETH.PM_EXPRESSION_FIELD: return GenerateField(call); case PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE: return GenerateConstantType(call); case PREDEFMETH.PM_EXPRESSION_ASSIGN: return GenerateAssignment(call); case PREDEFMETH.PM_EXPRESSION_ADD: case PREDEFMETH.PM_EXPRESSION_AND: case PREDEFMETH.PM_EXPRESSION_DIVIDE: case PREDEFMETH.PM_EXPRESSION_EQUAL: case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR: case PREDEFMETH.PM_EXPRESSION_GREATERTHAN: case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL: case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT: case PREDEFMETH.PM_EXPRESSION_LESSTHAN: case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL: case PREDEFMETH.PM_EXPRESSION_MODULO: case PREDEFMETH.PM_EXPRESSION_MULTIPLY: case PREDEFMETH.PM_EXPRESSION_NOTEQUAL: case PREDEFMETH.PM_EXPRESSION_OR: case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT: case PREDEFMETH.PM_EXPRESSION_SUBTRACT: case PREDEFMETH.PM_EXPRESSION_ORELSE: case PREDEFMETH.PM_EXPRESSION_ANDALSO: // Checked case PREDEFMETH.PM_EXPRESSION_ADDCHECKED: case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED: case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED: return GenerateBinaryOperator(call); case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED: // Checked case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED: return GenerateUserDefinedBinaryOperator(call); case PREDEFMETH.PM_EXPRESSION_NOT: case PREDEFMETH.PM_EXPRESSION_NEGATE: case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED: return GenerateUnaryOperator(call); case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED: return GenerateUserDefinedUnaryOperator(call); default: Debug.Assert(false, "Invalid Predefined Method in GetExpression"); throw Error.InternalCompilerError(); } } } ///////////////////////////////////////////////////////////////////////////////// private object GetObject(Expr pExpr) { for (;;) { if (pExpr is ExprCast cast) { pExpr = cast.Argument; } else if (pExpr is ExprTypeOf typeOf) { return typeOf.SourceType.Type.AssociatedSystemType; } else if (pExpr is ExprMethodInfo methodInfo) { return GetMethodInfoFromExpr(methodInfo); } else if (pExpr is ExprConstant constant) { ConstVal val = constant.Val; CType underlyingType = pExpr.Type; object objval; if (pExpr.Type.IsNullType()) { return null; } if (pExpr.Type.isEnumType()) { underlyingType = underlyingType.getAggregate().GetUnderlyingType(); } switch (Type.GetTypeCode(underlyingType.AssociatedSystemType)) { case TypeCode.Boolean: objval = val.BooleanVal; break; case TypeCode.SByte: objval = val.SByteVal; break; case TypeCode.Byte: objval = val.ByteVal; break; case TypeCode.Int16: objval = val.Int16Val; break; case TypeCode.UInt16: objval = val.UInt16Val; break; case TypeCode.Int32: objval = val.Int32Val; break; case TypeCode.UInt32: objval = val.UInt32Val; break; case TypeCode.Int64: objval = val.Int64Val; break; case TypeCode.UInt64: objval = val.UInt64Val; break; case TypeCode.Single: objval = val.SingleVal; break; case TypeCode.Double: objval = val.DoubleVal; break; case TypeCode.Decimal: objval = val.DecimalVal; break; case TypeCode.Char: objval = val.CharVal; break; case TypeCode.String: objval = val.StringVal; break; default: objval = val.ObjectVal; break; } return pExpr.Type.isEnumType() ? Enum.ToObject(pExpr.Type.AssociatedSystemType, objval) : objval; } else if (pExpr is ExprZeroInit zeroInit) { if ((pExpr = zeroInit.OptionalArgument) == null) { return Activator.CreateInstance(zeroInit.Type.AssociatedSystemType); } } else { Debug.Assert(false, "Invalid Expr in GetObject"); throw Error.InternalCompilerError(); } } } ///////////////////////////////////////////////////////////////////////////////// private Expression[] GetArgumentsFromArrayInit(ExprArrayInit arrinit) { List<Expression> expressions = new List<Expression>(); if (arrinit != null) { Expr list = arrinit.OptionalArguments; Expr p = list; while (list != null) { if (list is ExprList pList) { p = pList.OptionalElement; list = pList.OptionalNextListNode; } else { p = list; list = null; } expressions.Add(GetExpression(p)); } Debug.Assert(expressions.Count == arrinit.DimensionSizes[0]); } return expressions.ToArray(); } ///////////////////////////////////////////////////////////////////////////////// private MethodInfo GetMethodInfoFromExpr(ExprMethodInfo methinfo) { // To do this, we need to construct a type array of the parameter types, // get the parent constructed type, and get the method from it. AggregateType aggType = methinfo.Method.Ats; MethodSymbol methSym = methinfo.Method.Meth(); TypeArray genericParams = _typeManager.SubstTypeArray(methSym.Params, aggType, methSym.typeVars); CType genericReturn = _typeManager.SubstType(methSym.RetType, aggType, methSym.typeVars); Type type = aggType.AssociatedSystemType; MethodInfo methodInfo = methSym.AssociatedMemberInfo as MethodInfo; // This is to ensure that for embedded nopia types, we have the // appropriate local type from the member itself; this is possible // because nopia types are not generic or nested. if (!type.IsGenericType && !type.IsNested) { type = methodInfo.DeclaringType; } // We need to find the associated methodinfo on the instantiated type. foreach (MethodInfo m in type.GetRuntimeMethods()) { #if UNSUPPORTEDAPI if ((m.MetadataToken != methodInfo.MetadataToken) || (m.Module != methodInfo.Module)) #else if (!m.HasSameMetadataDefinitionAs(methodInfo)) #endif { continue; } Debug.Assert((m.Name == methodInfo.Name) && (m.GetParameters().Length == genericParams.Count) && (TypesAreEqual(m.ReturnType, genericReturn.AssociatedSystemType))); bool bMatch = true; ParameterInfo[] parameters = m.GetParameters(); for (int i = 0; i < genericParams.Count; i++) { if (!TypesAreEqual(parameters[i].ParameterType, genericParams[i].AssociatedSystemType)) { bMatch = false; break; } } if (bMatch) { if (m.IsGenericMethod) { int size = methinfo.Method.TypeArgs?.Count ?? 0; Type[] typeArgs = new Type[size]; if (size > 0) { for (int i = 0; i < methinfo.Method.TypeArgs.Count; i++) { typeArgs[i] = methinfo.Method.TypeArgs[i].AssociatedSystemType; } } return m.MakeGenericMethod(typeArgs); } return m; } } Debug.Assert(false, "Could not find matching method"); throw Error.InternalCompilerError(); } ///////////////////////////////////////////////////////////////////////////////// private ConstructorInfo GetConstructorInfoFromExpr(ExprMethodInfo methinfo) { // To do this, we need to construct a type array of the parameter types, // get the parent constructed type, and get the method from it. AggregateType aggType = methinfo.Method.Ats; MethodSymbol methSym = methinfo.Method.Meth(); TypeArray genericInstanceParams = _typeManager.SubstTypeArray(methSym.Params, aggType); Type type = aggType.AssociatedSystemType; ConstructorInfo ctorInfo = (ConstructorInfo)methSym.AssociatedMemberInfo; // This is to ensure that for embedded nopia types, we have the // appropriate local type from the member itself; this is possible // because nopia types are not generic or nested. if (!type.IsGenericType && !type.IsNested) { type = ctorInfo.DeclaringType; } foreach (ConstructorInfo c in type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) { #if UNSUPPORTEDAPI if ((c.MetadataToken != ctorInfo.MetadataToken) || (c.Module != ctorInfo.Module)) #else if (!c.HasSameMetadataDefinitionAs(ctorInfo)) #endif { continue; } Debug.Assert(c.GetParameters() == null || c.GetParameters().Length == genericInstanceParams.Count); bool bMatch = true; ParameterInfo[] parameters = c.GetParameters(); for (int i = 0; i < genericInstanceParams.Count; i++) { if (!TypesAreEqual(parameters[i].ParameterType, genericInstanceParams[i].AssociatedSystemType)) { bMatch = false; break; } } if (bMatch) { return c; } } Debug.Assert(false, "Could not find matching constructor"); throw Error.InternalCompilerError(); } ///////////////////////////////////////////////////////////////////////////////// private PropertyInfo GetPropertyInfoFromExpr(ExprPropertyInfo propinfo) { // To do this, we need to construct a type array of the parameter types, // get the parent constructed type, and get the property from it. AggregateType aggType = propinfo.Property.Ats; PropertySymbol propSym = propinfo.Property.Prop(); TypeArray genericInstanceParams = _typeManager.SubstTypeArray(propSym.Params, aggType, null); CType genericInstanceReturn = _typeManager.SubstType(propSym.RetType, aggType, null); Type type = aggType.AssociatedSystemType; PropertyInfo propertyInfo = propSym.AssociatedPropertyInfo; // This is to ensure that for embedded nopia types, we have the // appropriate local type from the member itself; this is possible // because nopia types are not generic or nested. if (!type.IsGenericType && !type.IsNested) { type = propertyInfo.DeclaringType; } foreach (PropertyInfo p in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) { #if UNSUPPORTEDAPI if ((p.MetadataToken != propertyInfo.MetadataToken) || (p.Module != propertyInfo.Module)) #else if (!p.HasSameMetadataDefinitionAs(propertyInfo)) { #endif continue; } Debug.Assert((p.Name == propertyInfo.Name) && (p.GetIndexParameters() == null || p.GetIndexParameters().Length == genericInstanceParams.Count)); bool bMatch = true; ParameterInfo[] parameters = p.GetSetMethod(true) != null ? p.GetSetMethod(true).GetParameters() : p.GetGetMethod(true).GetParameters(); for (int i = 0; i < genericInstanceParams.Count; i++) { if (!TypesAreEqual(parameters[i].ParameterType, genericInstanceParams[i].AssociatedSystemType)) { bMatch = false; break; } } if (bMatch) { return p; } } Debug.Assert(false, "Could not find matching property"); throw Error.InternalCompilerError(); } ///////////////////////////////////////////////////////////////////////////////// private bool TypesAreEqual(Type t1, Type t2) { if (t1 == t2) { return true; } return t1.IsEquivalentTo(t2); } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.RecoveryServices; using Microsoft.WindowsAzure.Management.RecoveryServices.Models; namespace Microsoft.WindowsAzure.Management.RecoveryServices { /// <summary> /// Definition of cloud service operations for the Recovery services /// extension. /// </summary> internal partial class CloudServiceOperations : IServiceOperations<RecoveryServicesManagementClient>, Microsoft.WindowsAzure.Management.RecoveryServices.ICloudServiceOperations { /// <summary> /// Initializes a new instance of the CloudServiceOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal CloudServiceOperations(RecoveryServicesManagementClient client) { this._client = client; } private RecoveryServicesManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.RecoveryServices.RecoveryServicesManagementClient. /// </summary> public RecoveryServicesManagementClient Client { get { return this._client; } } /// <summary> /// Retrieve a list of Cloud services /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list cloud service operation. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.RecoveryServices.Models.CloudServiceListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/cloudservices?"; url = url + "api-version=2014-10-27"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result CloudServiceListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new CloudServiceListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement cloudServicesSequenceElement = responseDoc.Element(XName.Get("CloudServices", "http://schemas.microsoft.com/windowsazure")); if (cloudServicesSequenceElement != null) { foreach (XElement cloudServicesElement in cloudServicesSequenceElement.Elements(XName.Get("CloudService", "http://schemas.microsoft.com/windowsazure"))) { CloudService cloudServiceInstance = new CloudService(); result.CloudServices.Add(cloudServiceInstance); XElement descriptionElement = cloudServicesElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; cloudServiceInstance.Description = descriptionInstance; } XElement geoRegionElement = cloudServicesElement.Element(XName.Get("GeoRegion", "http://schemas.microsoft.com/windowsazure")); if (geoRegionElement != null) { string geoRegionInstance = geoRegionElement.Value; cloudServiceInstance.GeoRegion = geoRegionInstance; } XElement labelElement = cloudServicesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = labelElement.Value; cloudServiceInstance.Label = labelInstance; } XElement nameElement = cloudServicesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; cloudServiceInstance.Name = nameInstance; } XElement resourcesSequenceElement = cloudServicesElement.Element(XName.Get("Resources", "http://schemas.microsoft.com/windowsazure")); if (resourcesSequenceElement != null) { foreach (XElement resourcesElement in resourcesSequenceElement.Elements(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"))) { Vault resourceInstance = new Vault(); cloudServiceInstance.Resources.Add(resourceInstance); XElement resourceProviderNamespaceElement = resourcesElement.Element(XName.Get("ResourceProviderNamespace", "http://schemas.microsoft.com/windowsazure")); if (resourceProviderNamespaceElement != null) { string resourceProviderNamespaceInstance = resourceProviderNamespaceElement.Value; resourceInstance.ResourceProviderNamespace = resourceProviderNamespaceInstance; } XElement eTagElement = resourcesElement.Element(XName.Get("ETag", "http://schemas.microsoft.com/windowsazure")); if (eTagElement != null) { string eTagInstance = eTagElement.Value; resourceInstance.ETag = eTagInstance; } XElement labelElement2 = resourcesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement2 != null) { string labelInstance2 = labelElement2.Value; resourceInstance.Label = labelInstance2; } XElement nameElement2 = resourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement2 != null) { string nameInstance2 = nameElement2.Value; resourceInstance.Name = nameInstance2; } XElement operationStatusElement = resourcesElement.Element(XName.Get("OperationStatus", "http://schemas.microsoft.com/windowsazure")); if (operationStatusElement != null) { ResourceOperationStatus operationStatusInstance = new ResourceOperationStatus(); resourceInstance.OperationStatus = operationStatusInstance; XElement resultElement = operationStatusElement.Element(XName.Get("Result", "http://schemas.microsoft.com/windowsazure")); if (resultElement != null) { string resultInstance = resultElement.Value; operationStatusInstance.Result = resultInstance; } XElement typeElement = operationStatusElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement != null) { string typeInstance = typeElement.Value; operationStatusInstance.Type = typeInstance; } } XElement outputItemsSequenceElement = resourcesElement.Element(XName.Get("OutputItems", "http://schemas.microsoft.com/windowsazure")); if (outputItemsSequenceElement != null) { foreach (XElement outputItemsElement in outputItemsSequenceElement.Elements(XName.Get("OutputItem", "http://schemas.microsoft.com/windowsazure"))) { OutputItem outputItemInstance = new OutputItem(); resourceInstance.OutputItems.Add(outputItemInstance); XElement keyElement = outputItemsElement.Element(XName.Get("Key", "http://schemas.microsoft.com/windowsazure")); if (keyElement != null) { string keyInstance = keyElement.Value; outputItemInstance.Key = keyInstance; } XElement valueElement = outputItemsElement.Element(XName.Get("Value", "http://schemas.microsoft.com/windowsazure")); if (valueElement != null) { string valueInstance = valueElement.Value; outputItemInstance.Value = valueInstance; } } } XElement planElement = resourcesElement.Element(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure")); if (planElement != null) { string planInstance = planElement.Value; resourceInstance.Plan = planInstance; } XElement schemaVersionElement = resourcesElement.Element(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure")); if (schemaVersionElement != null) { string schemaVersionInstance = schemaVersionElement.Value; resourceInstance.SchemaVersion = schemaVersionInstance; } XElement stateElement = resourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; resourceInstance.State = stateInstance; } XElement subStateElement = resourcesElement.Element(XName.Get("SubState", "http://schemas.microsoft.com/windowsazure")); if (subStateElement != null) { string subStateInstance = subStateElement.Value; resourceInstance.SubState = subStateInstance; } XElement typeElement2 = resourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement2 != null) { string typeInstance2 = typeElement2.Value; resourceInstance.Type = typeInstance2; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.ServiceModel.Syndication { using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; // sealed because the ctor results in a call to the virtual InsertItem method public sealed class SyndicationElementExtensionCollection : Collection<SyndicationElementExtension> { private XmlBuffer _buffer; private bool _initialized; internal SyndicationElementExtensionCollection() : this((XmlBuffer)null) { } internal SyndicationElementExtensionCollection(XmlBuffer buffer) : base() { _buffer = buffer; if (_buffer != null) { PopulateElements(); } _initialized = true; } internal SyndicationElementExtensionCollection(SyndicationElementExtensionCollection source) : base() { _buffer = source._buffer; for (int i = 0; i < source.Items.Count; ++i) { base.Add(source.Items[i]); } _initialized = true; } public void Add(object extension) { if (extension is SyndicationElementExtension) { base.Add((SyndicationElementExtension)extension); } else { Add(extension, (DataContractSerializer)null); } } public void Add(string outerName, string outerNamespace, object dataContractExtension) { Add(outerName, outerNamespace, dataContractExtension, null); } public void Add(object dataContractExtension, DataContractSerializer serializer) { Add(null, null, dataContractExtension, serializer); } public void Add(string outerName, string outerNamespace, object dataContractExtension, XmlObjectSerializer dataContractSerializer) { if (dataContractExtension == null) { throw new ArgumentNullException(nameof(dataContractExtension)); } if (dataContractSerializer == null) { dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType()); } base.Add(new SyndicationElementExtension(outerName, outerNamespace, dataContractExtension, dataContractSerializer)); } public void Add(object xmlSerializerExtension, XmlSerializer serializer) { if (xmlSerializerExtension == null) { throw new ArgumentNullException(nameof(xmlSerializerExtension)); } if (serializer == null) { serializer = new XmlSerializer(xmlSerializerExtension.GetType()); } base.Add(new SyndicationElementExtension(xmlSerializerExtension, serializer)); } public void Add(XmlReader xmlReader) { if (xmlReader == null) { throw new ArgumentNullException(nameof(xmlReader)); } base.Add(new SyndicationElementExtension(xmlReader)); } public XmlReader GetReaderAtElementExtensions() { return GetReaderAtElementExtensionsAsync().GetAwaiter().GetResult(); } public Collection<TExtension> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace) { return ReadElementExtensions<TExtension>(extensionName, extensionNamespace, new DataContractSerializer(typeof(TExtension))); } public Collection<TExtension> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace, XmlObjectSerializer serializer) { return ReadElementExtensionsAsync<TExtension>(extensionName, extensionNamespace, serializer).GetAwaiter().GetResult(); } public Collection<TExtension> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace, XmlSerializer serializer) { return ReadElementExtensionsAsync<TExtension>(extensionName, extensionNamespace, serializer).GetAwaiter().GetResult(); } public async Task<XmlReader> GetReaderAtElementExtensionsAsync() { XmlBuffer extensionsBuffer = await GetOrCreateBufferOverExtensions(); XmlReader reader = extensionsBuffer.GetReader(0); reader.ReadStartElement(); return reader; } public Task<Collection<TExtension>> ReadElementExtensionsAsync<TExtension>(string extensionName, string extensionNamespace) { return ReadElementExtensionsAsync<TExtension>(extensionName, extensionNamespace, new DataContractSerializer(typeof(TExtension))); } public Task<Collection<TExtension>> ReadElementExtensionsAsync<TExtension>(string extensionName, string extensionNamespace, XmlObjectSerializer serializer) { if (serializer == null) { throw new ArgumentNullException(nameof(serializer)); } return ReadExtensions<TExtension>(extensionName, extensionNamespace, serializer, null); } public Task<Collection<TExtension>> ReadElementExtensionsAsync<TExtension>(string extensionName, string extensionNamespace, XmlSerializer serializer) { if (serializer == null) { throw new ArgumentNullException(nameof(serializer)); } return ReadExtensions<TExtension>(extensionName, extensionNamespace, null, serializer); } internal async Task WriteToAsync(XmlWriter writer) { if (_buffer != null) { using (XmlDictionaryReader reader = _buffer.GetReader(0)) { reader.ReadStartElement(); while (reader.IsStartElement()) { await writer.WriteNodeAsync(reader, false); } } } else { for (int i = 0; i < Items.Count; ++i) { await Items[i].WriteToAsync(writer); } } } protected override void ClearItems() { base.ClearItems(); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) { _buffer = null; } } protected override void InsertItem(int index, SyndicationElementExtension item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } base.InsertItem(index, item); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) { _buffer = null; } } protected override void RemoveItem(int index) { base.RemoveItem(index); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) { _buffer = null; } } protected override void SetItem(int index, SyndicationElementExtension item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } base.SetItem(index, item); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) { _buffer = null; } } private async Task<XmlBuffer> GetOrCreateBufferOverExtensions() { if (_buffer != null) { return _buffer; } XmlBuffer newBuffer = new XmlBuffer(int.MaxValue); using (XmlWriter writer = newBuffer.OpenSection(XmlDictionaryReaderQuotas.Max)) { writer.WriteStartElement(Rss20Constants.ExtensionWrapperTag); for (int i = 0; i < Count; ++i) { await this[i].WriteToAsync(writer); } writer.WriteEndElement(); } newBuffer.CloseSection(); newBuffer.Close(); _buffer = newBuffer; return newBuffer; } private void PopulateElements() { using (XmlDictionaryReader reader = _buffer.GetReader(0)) { reader.ReadStartElement(); int index = 0; while (reader.IsStartElement()) { base.Add(new SyndicationElementExtension(_buffer, index, reader.LocalName, reader.NamespaceURI)); reader.Skip(); ++index; } } } private async Task<Collection<TExtension>> ReadExtensions<TExtension>(string extensionName, string extensionNamespace, XmlObjectSerializer dcSerializer, XmlSerializer xmlSerializer) { if (string.IsNullOrEmpty(extensionName)) { throw new ArgumentNullException(SR.ExtensionNameNotSpecified); } Debug.Assert((dcSerializer == null) != (xmlSerializer == null), "exactly one serializer should be supplied"); // normalize the null and empty namespace if (extensionNamespace == null) { extensionNamespace = string.Empty; } Collection<TExtension> results = new Collection<TExtension>(); for (int i = 0; i < Count; ++i) { if (extensionName != this[i].OuterName || extensionNamespace != this[i].OuterNamespace) { continue; } if (dcSerializer != null) { results.Add(await this[i].GetObjectAsync<TExtension>(dcSerializer)); } else { results.Add(await this[i].GetObjectAsync<TExtension>(xmlSerializer)); } } return results; } } }
// ReSharper disable PossibleMultipleEnumeration using System; using System.Collections.Generic; using System.Linq; using Affecto.Authentication.Claims; using Affecto.Mapping; using Microsoft.VisualStudio.TestTools.UnitTesting; using NSubstitute; using ServiceRegister.Application.User; using ServiceRegister.Common.User; using ServiceRegister.UserManagement.Mapping; using ServiceRegister.UserManagement.Model; using IdentityManagement = Affecto.IdentityManagement.Interfaces; namespace ServiceRegister.UserManagement.Tests { [TestClass] public class UserServiceTests { private UserService sut; private IdentityManagement.IIdentityManagementService identityManagementService; private MapperFactory mapperFactory; private IAuthenticatedUserContext userContext; private static readonly Guid ExpectedRoleId = Guid.NewGuid(); private static readonly Guid ExpectedOrganizationId = Guid.NewGuid(); private static readonly string ExpectedEmailAddress = "foo@bar.com"; private static readonly string ExpectedPassword = "PaSS"; private static readonly string ExpectedLastName = "Clarkson"; private static readonly string ExpectedFirstName = "Jeremy"; private static readonly string ExpectedPhoneNumber = "5562423422-234"; [TestInitialize] public void Setup() { identityManagementService = Substitute.For<IdentityManagement.IIdentityManagementService>(); mapperFactory = Substitute.For<MapperFactory>(); userContext = Substitute.For<IAuthenticatedUserContext>(); sut = new UserService(identityManagementService, mapperFactory, userContext); var role = Substitute.For<IdentityManagement.Model.IRole>(); role.Id.Returns(ExpectedRoleId); role.Name.Returns(Roles.Administrator); identityManagementService.GetRoles().Returns(new List<IdentityManagement.Model.IRole> { role }); } [TestMethod] public void RolesAreReturned() { var returnedRoles = new List<IdentityManagement.Model.IRole> { Substitute.For<IdentityManagement.Model.IRole>(), Substitute.For<IdentityManagement.Model.IRole>() }; var expectedRoles = new List<Role> { new Role { Id = Guid.NewGuid(), Name = "Admin" }, new Role { Id = Guid.NewGuid(), Name = "Basic" } }; var mapper = Substitute.For<IMapper<IdentityManagement.Model.IRole, Role>>(); mapper.Map(returnedRoles[0]).Returns(expectedRoles[0]); mapper.Map(returnedRoles[1]).Returns(expectedRoles[1]); mapperFactory.CreateRoleMapper().Returns(mapper); identityManagementService.GetRoles().Returns(returnedRoles); IEnumerable<IRole> result = sut.GetRoles(); Assert.AreEqual(2, result.Count()); Assert.AreSame(expectedRoles[0], result.First()); Assert.AreSame(expectedRoles[1], result.Last()); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void RoleIdCannotBeEmptyWhenAddingUser() { sut.AddUser(Guid.Empty, ExpectedOrganizationId, ExpectedEmailAddress, ExpectedPassword, ExpectedLastName, ExpectedFirstName, ExpectedPhoneNumber); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void OrganizationIdCannotBeEmptyWhenAddingUser() { sut.AddUser(ExpectedRoleId, Guid.Empty, ExpectedEmailAddress, ExpectedPassword, ExpectedLastName, ExpectedFirstName, ExpectedPhoneNumber); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void EmailAddressCannotBeNullWhenAddingUser() { sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, null, ExpectedPassword, ExpectedLastName, ExpectedFirstName, ExpectedPhoneNumber); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void EmailAddressCannotBeEmptyWhenAddingUser() { sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, "", ExpectedPassword, ExpectedLastName, ExpectedFirstName, ExpectedPhoneNumber); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void EmailAddressCannotBeWhitespaceWhenAddingUser() { sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, " ", ExpectedPassword, ExpectedLastName, ExpectedFirstName, ExpectedPhoneNumber); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void PasswordCannotBeNullWhenAddingUser() { sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, ExpectedEmailAddress, null, ExpectedLastName, ExpectedFirstName, ExpectedPhoneNumber); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void PasswordCannotBeEmptyWhenAddingUser() { sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, ExpectedEmailAddress, "", ExpectedLastName, ExpectedFirstName, ExpectedPhoneNumber); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void PasswordCannotBeWhitespaceWhenAddingUser() { sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, ExpectedEmailAddress, " ", ExpectedLastName, ExpectedFirstName, ExpectedPhoneNumber); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void LastNameCannotBeNullWhenAddingUser() { sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, ExpectedEmailAddress, ExpectedPassword, null, ExpectedFirstName, ExpectedPhoneNumber); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void LastNameCannotBeEmptyWhenAddingUser() { sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, ExpectedEmailAddress, ExpectedPassword, "", ExpectedFirstName, ExpectedPhoneNumber); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void LastNameCannotBeWhitespaceWhenAddingUser() { sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, ExpectedEmailAddress, ExpectedPassword, " ", ExpectedFirstName, ExpectedPhoneNumber); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void FirstNameCannotBeNullWhenAddingUser() { sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, ExpectedEmailAddress, ExpectedPassword, ExpectedLastName, null, ExpectedPhoneNumber); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void FirstNameCannotBeEmptyWhenAddingUser() { sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, ExpectedEmailAddress, ExpectedPassword, ExpectedLastName, "", ExpectedPhoneNumber); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void FirstNameCannotBeWhitespaceWhenAddingUser() { sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, ExpectedEmailAddress, ExpectedPassword, ExpectedLastName, " ", ExpectedPhoneNumber); } [TestMethod] public void DisplayNameIsGeneratedWhenAddingUser() { sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, ExpectedEmailAddress, ExpectedPassword, ExpectedLastName, ExpectedFirstName, ExpectedPhoneNumber); identityManagementService.Received(1).CreateUser($"{ExpectedLastName} {ExpectedFirstName}", Arg.Any<IEnumerable<KeyValuePair<string, string>>>()); } [TestMethod] public void CustomPropertiesAreSavedWhenAddingUser() { IEnumerable<KeyValuePair<string, string>> customProperties = null; identityManagementService .When(s => s.CreateUser(Arg.Any<string>(), Arg.Any<IEnumerable<KeyValuePair<string, string>>>())) .Do(callInfo => customProperties = callInfo.Arg<IEnumerable<KeyValuePair<string, string>>>()); sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, ExpectedEmailAddress, ExpectedPassword, ExpectedLastName, ExpectedFirstName, ExpectedPhoneNumber); identityManagementService.Received(1).CreateUser(Arg.Any<string>(), Arg.Any<IEnumerable<KeyValuePair<string, string>>>()); Assert.IsNotNull(customProperties); Assert.AreEqual(5, customProperties.Count()); Assert.IsNotNull(customProperties.SingleOrDefault(p => p.Key == CustomPropertyName.LastName.ToString() && p.Value == ExpectedLastName)); Assert.IsNotNull(customProperties.SingleOrDefault(p => p.Key == CustomPropertyName.FirstName.ToString() && p.Value == ExpectedFirstName)); Assert.IsNotNull(customProperties.SingleOrDefault(p => p.Key == CustomPropertyName.EmailAddress.ToString() && p.Value == ExpectedEmailAddress)); Assert.IsNotNull(customProperties.SingleOrDefault(p => p.Key == CustomPropertyName.PhoneNumber.ToString() && p.Value == ExpectedPhoneNumber)); Assert.IsNotNull(customProperties.SingleOrDefault(p => p.Key == CustomPropertyName.OrganizationId.ToString() && p.Value == ExpectedOrganizationId.ToString())); } [TestMethod] public void UsersRoleIsSetWhenAddingUser() { var expectedUser = Substitute.For<IdentityManagement.Model.IUserListItem>(); expectedUser.Id.Returns(Guid.NewGuid()); identityManagementService .CreateUser(Arg.Any<string>(), Arg.Any<IEnumerable<KeyValuePair<string, string>>>()) .Returns(expectedUser); sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, ExpectedEmailAddress, ExpectedPassword, ExpectedLastName, ExpectedFirstName, ExpectedPhoneNumber); identityManagementService.Received(1).AddUserRole(expectedUser.Id, ExpectedRoleId); } [TestMethod] public void UserIdIsReturnedWhenAddingUser() { var expectedUser = Substitute.For<IdentityManagement.Model.IUserListItem>(); expectedUser.Id.Returns(Guid.NewGuid()); identityManagementService .CreateUser(Arg.Any<string>(), Arg.Any<IEnumerable<KeyValuePair<string, string>>>()) .Returns(expectedUser); Guid userId = sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, ExpectedEmailAddress, ExpectedPassword, ExpectedLastName, ExpectedFirstName, ExpectedPhoneNumber); Assert.AreEqual(expectedUser.Id, userId); } [TestMethod] [ExpectedException(typeof(InsufficientPermissionsException))] public void AdministratorUserCannotBeAddedWithoutPermission() { userContext .When(u => u.CheckPermission(Permissions.Users.ManageAdministratorUsers)) .Do(callInfo => { throw new InsufficientPermissionsException(Permissions.Users.ManageAdministratorUsers); }); sut.AddUser(ExpectedRoleId, ExpectedOrganizationId, ExpectedEmailAddress, ExpectedPassword, ExpectedLastName, ExpectedFirstName, ExpectedPhoneNumber); } [TestMethod] public void UsersAreReturnedForUsersOrganization() { Guid organizationId = Guid.NewGuid(); userContext.HasCustomProperty(CustomPropertyName.OrganizationId.ToString()).Returns(true); userContext.GetCustomPropertyValue(CustomPropertyName.OrganizationId.ToString()).Returns(organizationId.ToString("D")); userContext .When(u => u.CheckPermission(Permissions.Users.ViewAllUsers)) .Do(callInfo => { throw new InsufficientPermissionsException(Permissions.Users.ViewAllUsers); }); var returnedUsers = new List<IdentityManagement.Model.IUser> { Substitute.For<IdentityManagement.Model.IUser>(), Substitute.For<IdentityManagement.Model.IUser>() }; var expectedUsers = new List<UserListItem> { new UserListItem { Id = Guid.NewGuid() }, new UserListItem { Id = Guid.NewGuid() } }; var mapper = Substitute.For<IMapper<IdentityManagement.Model.IUser, UserListItem>>(); mapper.Map(returnedUsers[0]).Returns(expectedUsers[0]); mapper.Map(returnedUsers[1]).Returns(expectedUsers[1]); mapperFactory.CreateUserMapper().Returns(mapper); identityManagementService.GetUsers(CustomPropertyName.OrganizationId.ToString(), organizationId.ToString("D")).Returns(returnedUsers); IEnumerable<IUserListItem> result = sut.GetUsers(organizationId); Assert.AreEqual(2, result.Count()); Assert.AreSame(expectedUsers[0], result.First()); Assert.AreSame(expectedUsers[1], result.Last()); } [TestMethod] public void UsersAreReturnedForOtherOrganization() { Guid organizationId = Guid.NewGuid(); userContext.HasCustomProperty(CustomPropertyName.OrganizationId.ToString()).Returns(true); userContext.GetCustomPropertyValue(CustomPropertyName.OrganizationId.ToString()).Returns(Guid.NewGuid().ToString("D")); userContext .When(u => u.CheckPermission(Permissions.Users.ViewUserOrganizationUsers)) .Do(callInfo => { throw new InsufficientPermissionsException(Permissions.Users.ViewUserOrganizationUsers); }); var returnedUsers = new List<IdentityManagement.Model.IUser> { Substitute.For<IdentityManagement.Model.IUser>(), Substitute.For<IdentityManagement.Model.IUser>() }; var expectedUsers = new List<UserListItem> { new UserListItem { Id = Guid.NewGuid() }, new UserListItem { Id = Guid.NewGuid() } }; var mapper = Substitute.For<IMapper<IdentityManagement.Model.IUser, UserListItem>>(); mapper.Map(returnedUsers[0]).Returns(expectedUsers[0]); mapper.Map(returnedUsers[1]).Returns(expectedUsers[1]); mapperFactory.CreateUserMapper().Returns(mapper); identityManagementService.GetUsers(CustomPropertyName.OrganizationId.ToString(), organizationId.ToString("D")).Returns(returnedUsers); IEnumerable<IUserListItem> result = sut.GetUsers(organizationId); Assert.AreEqual(2, result.Count()); Assert.AreSame(expectedUsers[0], result.First()); Assert.AreSame(expectedUsers[1], result.Last()); } [TestMethod] [ExpectedException(typeof(InsufficientPermissionsException))] public void NoUsersAreReturnedIfNoPermissions() { Guid organizationId = Guid.NewGuid(); userContext.HasCustomProperty(CustomPropertyName.OrganizationId.ToString()).Returns(true); userContext.GetCustomPropertyValue(CustomPropertyName.OrganizationId.ToString()).Returns(Guid.NewGuid().ToString("D")); userContext .When(u => u.CheckPermission(Permissions.Users.ViewUserOrganizationUsers)) .Do(callInfo => { throw new InsufficientPermissionsException(Permissions.Users.ViewUserOrganizationUsers); }); userContext .When(u => u.CheckPermission(Permissions.Users.ViewAllUsers)) .Do(callInfo => { throw new InsufficientPermissionsException(Permissions.Users.ViewAllUsers); }); sut.GetUsers(organizationId); } [TestMethod] public void NullPasswordIsNotValid() { bool isValid = sut.ValidatePasswordStrength(null); Assert.IsFalse(isValid); } [TestMethod] public void EmptyPasswordIsNotValid() { bool isValid = sut.ValidatePasswordStrength(string.Empty); Assert.IsFalse(isValid); } [TestMethod] public void TooShortPasswordIsNotValid() { bool isValid = sut.ValidatePasswordStrength("aB1&"); Assert.IsFalse(isValid); } [TestMethod] public void PasswordWithoutEnoughCharacterClassesIsNotValid() { bool isValid = sut.ValidatePasswordStrength("aaaBBBcccDDD"); Assert.IsFalse(isValid); } [TestMethod] public void PasswordIsValid() { bool isValid = sut.ValidatePasswordStrength("aaaBBB333&#_"); Assert.IsTrue(isValid); } } }
using UnityEngine; using System.Collections.Generic; using Ecosim.SceneEditor; using Ecosim.SceneData; using Ecosim.SceneData.VegetationRules; namespace Ecosim.SceneEditor.Helpers { public class HandleVegetation : PanelHelper { private readonly MapsPanel parent; private Scene scene; private EditorCtrl ctrl; private GridTextureSettings gridSettings255 = new GridTextureSettings (false, 0, 16, "MapGrid255", true, "ActiveMapGrid255"); private int brushWidth; private float brushStrength = 1.0f; private enum EBrushMode { Area, Circle }; private EBrushMode brushMode; private EditData edit; private Data backupCopy; private GUIStyle tabNormal; private GUIStyle tabSelected; string[] successionNames; int selectedSuccession = -1; string[] vegetationNames; int selectedVegetation = -1; TileType[] tiles; int selectedTile = -1; public HandleVegetation (EditorCtrl ctrl, MapsPanel parent, Scene scene) { this.parent = parent; this.ctrl = ctrl; this.scene = parent.scene; tabNormal = ctrl.listItem; tabSelected = ctrl.listItemSelected; Setup (); } void Setup () { edit = EditData.CreateEditData ("vegetation", null, delegate(int x, int y, int currentVal, float strength, bool shift, bool ctrl) { if (!ctrl) { return shift ? 0 : (int)(100 * brushStrength); } else { strength = strength * brushStrength; return Mathf.RoundToInt ((shift ? 0 : (strength * 100)) + ((1 - strength) * currentVal)); } }, gridSettings255); edit.SetModeBrush (brushWidth); edit.AddRightMouseHandler (delegate(int x, int y, int v) { VegetationData data = scene.progression.vegetation; VegetationType vegType = data.GetVegetationType (x, y); SuccessionType succession = vegType.successionType; List<string> vegNameList = new List<string> (); vegNameList.Add ("<Any vegetation>"); foreach (VegetationType vt in succession.vegetations) { vegNameList.Add (vt.name); } vegetationNames = vegNameList.ToArray (); tiles = vegType.tiles; }); brushMode = EBrushMode.Circle; backupCopy = new VegetationData (scene); scene.progression.vegetation.CopyTo (backupCopy); List<string> successionNameList = new List<string> (); successionNameList.Add ("<Any succession>"); foreach (SuccessionType st in scene.successionTypes) { successionNameList.Add (st.name); } successionNames = successionNameList.ToArray (); } public bool Render (int mx, int my) { GUILayout.BeginHorizontal (); GUILayout.Label ("brush mode", GUILayout.Width (100)); if (GUILayout.Button ("Area select", (brushMode == EBrushMode.Area) ? tabSelected : tabNormal, GUILayout.Width (100))) { brushMode = EBrushMode.Area; edit.SetModeAreaSelect (); } if (GUILayout.Button ("Circle brush", (brushMode == EBrushMode.Circle) ? tabSelected : tabNormal, GUILayout.Width (100))) { brushMode = EBrushMode.Circle; edit.SetModeBrush (brushWidth); } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); GUILayout.BeginHorizontal (); GUILayout.Label ("Brush strength", GUILayout.Width (100)); float newBrushStrength = GUILayout.HorizontalSlider (brushStrength, 0f, 1f, GUILayout.Width (160f)); GUILayout.Label (brushStrength.ToString ()); if (newBrushStrength != brushStrength) { brushStrength = ((int)(newBrushStrength * 20)) / 20f; } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); if (brushMode == EBrushMode.Circle) { GUILayout.BeginHorizontal (); GUILayout.Label ("Brush width", GUILayout.Width (100)); int newBrushWidth = (int)GUILayout.HorizontalSlider (brushWidth, 0f, 10f, GUILayout.Width (160f)); GUILayout.Label (brushWidth.ToString ()); if (newBrushWidth != brushWidth) { brushWidth = newBrushWidth; edit.SetModeBrush (brushWidth); } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); } GUILayout.Space (16); GUILayout.BeginHorizontal (); GUILayout.Label ("Succession", GUILayout.Width (100)); if (GUILayout.Button (successionNames [selectedSuccession + 1], tabNormal, GUILayout.Width (280))) { ctrl.StartSelection (successionNames, selectedSuccession + 1, result => { selectedSuccession = result - 1; selectedVegetation = -1; selectedTile = -1; if (selectedSuccession >= 0) { SuccessionType succession = scene.successionTypes [selectedSuccession]; List<string> vegNameList = new List<string> (); vegNameList.Add ("<Any vegetation>"); foreach (VegetationType vt in succession.vegetations) { vegNameList.Add (vt.name); } vegetationNames = vegNameList.ToArray (); } }); } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); if (selectedSuccession >= 0) { GUILayout.BeginHorizontal (); GUILayout.Label ("Vegetation", GUILayout.Width (100)); if (GUILayout.Button (vegetationNames [selectedVegetation + 1], tabNormal, GUILayout.Width (280))) { ctrl.StartSelection (vegetationNames, selectedVegetation + 1, result => { selectedVegetation = result - 1; selectedTile = -1; if (selectedVegetation >= 0) { tiles = scene.successionTypes [selectedSuccession].vegetations [selectedVegetation].tiles; } }); } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); if (selectedVegetation >= 0) { GUILayout.BeginHorizontal (); GUILayout.Label ("Tile", GUILayout.Width (100)); if (GUILayout.Button (ctrl.questionMark, (selectedTile == -1) ? tabSelected : tabNormal, GUILayout.Width (52), GUILayout.Height (52))) { selectedTile = -1; } for (int i = 0; i < tiles.Length; i++) { if (((i + 1) % 5) == 0) { GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); GUILayout.BeginHorizontal (); GUILayout.Label ("", GUILayout.Width (100)); } if (GUILayout.Button (tiles [i].GetIcon (), (selectedTile == i) ? tabSelected : tabNormal, GUILayout.Width (52), GUILayout.Height (52))) { selectedTile = i; } } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); } } GUILayout.BeginHorizontal (); GUILayout.Label ("", GUILayout.Width (100)); if (GUILayout.Button ("Select", GUILayout.Width (60))) { BitMap8 data = new BitMap8 (scene); ushort[] vegetation = scene.progression.vegetation.data; int p = 0; for (int y = 0; y < scene.height; y++) { for (int x = 0; x < scene.width; x++) { int vegetationInt = vegetation [p]; int successionId = (vegetationInt >> VegetationData.SUCCESSION_SHIFT) & VegetationData.SUCCESSION_MASK; if ((successionId == selectedSuccession) || (selectedSuccession == -1)) { int vegetationId = (vegetationInt >> VegetationData.VEGETATION_SHIFT) & VegetationData.VEGETATION_MASK; if ((vegetationId == selectedVegetation) || (selectedVegetation == -1)) { int tileId = (vegetationInt >> VegetationData.TILE_SHIFT) & VegetationData.TILE_MASK; if ((tileId == selectedTile) || (selectedTile == -1)) { data.data [p] = 100; // found tile with correct vegetation, set edit value to 100% } } } p++; } } edit.SetData (data); } if (GUILayout.Button ("Set", GUILayout.Width (60))) { BitMap8 data = new BitMap8 (scene); edit.CopyData (data); byte[] bytes = data.data; ushort[] vegetation = scene.progression.vegetation.data; int p = 0; for (int y = 0; y < scene.height; y++) { for (int x = 0; x < scene.width; x++) { int chance = bytes [p]; // edit area is % chance we need to set the tile to new vegetation if ((chance > 0) && (Random.Range (0, 100) < chance)) { int successionId = (selectedSuccession >= 0) ? selectedSuccession : (Random.Range (0, scene.successionTypes.Length)); if (scene.successionTypes [successionId].vegetations.Length > 0) { int vegetationId = (selectedVegetation >= 0) ? selectedVegetation : (Random.Range (0, scene.successionTypes [successionId].vegetations.Length)); int tileId = selectedTile; if (tileId < 0) { // tile should be chosen random int tileLen = scene.successionTypes [successionId].vegetations [vegetationId].tiles.Length; if (tileLen == 0) { Debug.LogError ("No tiles defined for " + scene.successionTypes [successionId].vegetations [vegetationId].name); tileId = 0; vegetationId = 0; successionId = 0; } if (tileLen == 1) { tileId = 0; } else { // normally we don't randomly choose tile id 0, as it is special, but we need to have at least 2 tiles before // we can choose tile id != 0 int vegetationInt = vegetation [p]; int currentTileId = vegetationInt & 0x0f; // tile id 0 is special (empty variant), if current tile has id 0, we make new tile id 0 as well... tileId = (currentTileId == 0) ? 0 : Random.Range (1, tileLen); } } vegetation [p] = (ushort)((successionId << VegetationData.SUCCESSION_SHIFT) | (vegetationId << VegetationData.VEGETATION_SHIFT) | (tileId << VegetationData.TILE_SHIFT)); // We mark it as changed so if we change it during the game it saves the changes scene.progression.vegetation.hasChanged = true; } } p++; } } TerrainMgr.self.ForceRedraw (); } if (GUILayout.Button ("Clear", GUILayout.Width (60))) { edit.ClearData (); } if (GUILayout.Button ("Default", GUILayout.Width (60))) { Perlin perlin = new Perlin(1234); BitMap8 data = new BitMap8 (scene); edit.CopyData (data); byte[] bytes = data.data; VegetationData vegData = scene.progression.vegetation; int p = 0; float scale = SettingsPanel.perlinScale; for (int y = 0; y < scene.height; y++) { for (int x = 0; x < scene.width; x++) { int chance = bytes [p++]; // edit area is % chance we need to set the tile to new vegetation if ((chance > 0) && (Random.Range (0, 100) < chance)) { VegetationType v = vegData.GetVegetationType (x, y); foreach (ParameterChange pc in v.changes) { int offsetX = pc.data.GetHashCode() & 0xfff; int offsetY = (pc.data.GetHashCode() >> 12) & 0xfff; float noise = 0.5f + 0.5f * perlin.Noise (scale * x - 123.123f + offsetX, scale * y - 345.567f + offsetY); // Debug.Log ("pos " + x + ", " + y + " noise = " + noise); int val = Mathf.RoundToInt(noise * (pc.highRange - pc.lowRange) + pc.lowRange); pc.data.Set (x, y, Mathf.Clamp (val, pc.lowRange, pc.highRange)); } } } } } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); GUILayout.FlexibleSpace (); if (parent.texture != null) { GUILayout.BeginHorizontal (); GUILayout.Label ("selection from image", GUILayout.Width (100)); if (GUILayout.Button ("select")) { Data tmpData = new BitMap8 (scene); for (int y = 0; y < scene.height; y++) { for (int x = 0; x < scene.width; x++) { int v = (int)(100 * parent.GetFromImage (x, y)); tmpData.Set (x, y, v); } } edit.SetData (tmpData); } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); } parent.RenderLoadTexture (); return false; } public void Disable () { edit.Delete (); edit = null; } public void Update () { if ((CameraControl.MouseOverGUI) || Input.GetKey (KeyCode.LeftAlt) || Input.GetKey (KeyCode.RightAlt)) { return; } Vector3 mousePos = Input.mousePosition; if (Input.GetMouseButton (1)) { Vector3 hitPoint; if (TerrainMgr.TryScreenToTerrainCoord (mousePos, out hitPoint)) { int x = (int)(hitPoint.x / TerrainMgr.TERRAIN_SCALE); int y = (int)(hitPoint.z / TerrainMgr.TERRAIN_SCALE); if ((x >= 0) && (y >= 0) && (x < scene.width) && (y < scene.height)) { TileType tile = scene.progression.vegetation.GetTileType (x, y); selectedSuccession = tile.vegetationType.successionType.index; selectedVegetation = tile.vegetationType.index; selectedTile = tile.index; List<string> vegNameList = new List<string> (); vegNameList.Add ("<Any vegetation>"); foreach (VegetationType vt in tile.vegetationType.successionType.vegetations) { vegNameList.Add (vt.name); } vegetationNames = vegNameList.ToArray (); tiles = tile.vegetationType.tiles; } } } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Orders; using QuantConnect.Securities; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// This regression algorithm tests In The Money (ITM) future option expiry for puts. /// We expect 3 orders from the algorithm, which are: /// /// * Initial entry, buy ES Put Option (expiring ITM) (buy, qty 1) /// * Option exercise, receiving short ES future contracts (sell, qty -1) /// * Future contract liquidation, due to impending expiry (buy qty 1) /// /// Additionally, we test delistings for future options and assert that our /// portfolio holdings reflect the orders the algorithm has submitted. /// </summary> public class FutureOptionPutITMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private Symbol _es19m20; private Symbol _esOption; private Symbol _expectedContract; public override void Initialize() { SetStartDate(2020, 1, 5); SetEndDate(2020, 6, 30); _es19m20 = AddFutureContract( QuantConnect.Symbol.CreateFuture( Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)), Resolution.Minute).Symbol; // Select a future option expiring ITM, and adds it to the algorithm. _esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time) .Where(x => x.ID.StrikePrice >= 3300m && x.ID.OptionRight == OptionRight.Put) .OrderBy(x => x.ID.StrikePrice) .Take(1) .Single(), Resolution.Minute).Symbol; _expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Put, 3300m, new DateTime(2020, 6, 19)); if (_esOption != _expectedContract) { throw new Exception($"Contract {_expectedContract} was not found in the chain"); } Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () => { MarketOrder(_esOption, 1); }); } public override void OnData(Slice data) { // Assert delistings, so that we can make sure that we receive the delisting warnings at // the expected time. These assertions detect bug #4872 foreach (var delisting in data.Delistings.Values) { if (delisting.Type == DelistingType.Warning) { if (delisting.Time != new DateTime(2020, 6, 19)) { throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}"); } } if (delisting.Type == DelistingType.Delisted) { if (delisting.Time != new DateTime(2020, 6, 20)) { throw new Exception($"Delisting happened at unexpected date: {delisting.Time}"); } } } } public override void OnOrderEvent(OrderEvent orderEvent) { if (orderEvent.Status != OrderStatus.Filled) { // There's lots of noise with OnOrderEvent, but we're only interested in fills. return; } if (!Securities.ContainsKey(orderEvent.Symbol)) { throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}"); } var security = Securities[orderEvent.Symbol]; if (security.Symbol == _es19m20) { AssertFutureOptionOrderExercise(orderEvent, security, Securities[_expectedContract]); } else if (security.Symbol == _expectedContract) { AssertFutureOptionContractOrder(orderEvent, security); } else { throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}"); } Log($"{Time:yyyy-MM-dd HH:mm:ss} -- {orderEvent.Symbol} :: Price: {Securities[orderEvent.Symbol].Holdings.Price} Qty: {Securities[orderEvent.Symbol].Holdings.Quantity} Direction: {orderEvent.Direction} Msg: {orderEvent.Message}"); } private void AssertFutureOptionOrderExercise(OrderEvent orderEvent, Security future, Security optionContract) { var expectedLiquidationTimeUtc = new DateTime(2020, 6, 19, 20, 0, 0); if (orderEvent.Direction == OrderDirection.Buy && future.Holdings.Quantity != 0) { // We expect the contract to have been liquidated immediately throw new Exception($"Did not liquidate existing holdings for Symbol {future.Symbol}"); } if (orderEvent.Direction == OrderDirection.Buy && orderEvent.UtcTime != expectedLiquidationTimeUtc) { throw new Exception($"Liquidated future contract, but not at the expected time. Expected: {expectedLiquidationTimeUtc:yyyy-MM-dd HH:mm:ss} - found {orderEvent.UtcTime:yyyy-MM-dd HH:mm:ss}"); } // No way to detect option exercise orders or any other kind of special orders // other than matching strings, for now. if (orderEvent.Message.Contains("Option Exercise")) { if (orderEvent.FillPrice != 3300m) { throw new Exception("Option did not exercise at expected strike price (3300)"); } if (future.Holdings.Quantity != -1) { // Here, we expect to have some holdings in the underlying, but not in the future option anymore. throw new Exception($"Exercised option contract, but we have no holdings for Future {future.Symbol}"); } if (optionContract.Holdings.Quantity != 0) { throw new Exception($"Exercised option contract, but we have holdings for Option contract {optionContract.Symbol}"); } } } private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security option) { if (orderEvent.Direction == OrderDirection.Buy && option.Holdings.Quantity != 1) { throw new Exception($"No holdings were created for option contract {option.Symbol}"); } if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != 0) { throw new Exception($"Holdings were found after a filled option exercise"); } if (orderEvent.Message.Contains("Exercise") && option.Holdings.Quantity != 0) { throw new Exception($"Holdings were found after exercising option contract {option.Symbol}"); } } /// <summary> /// Ran at the end of the algorithm to ensure the algorithm has no holdings /// </summary> /// <exception cref="Exception">The algorithm has holdings</exception> public override void OnEndOfAlgorithm() { if (Portfolio.Invested) { throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}"); } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "3"}, {"Average Win", "4.15%"}, {"Average Loss", "-8.27%"}, {"Compounding Annual Return", "-8.944%"}, {"Drawdown", "4.500%"}, {"Expectancy", "-0.249"}, {"Net Profit", "-4.457%"}, {"Sharpe Ratio", "-1.381"}, {"Probabilistic Sharpe Ratio", "0.002%"}, {"Loss Rate", "50%"}, {"Win Rate", "50%"}, {"Profit-Loss Ratio", "0.50"}, {"Alpha", "-0.072"}, {"Beta", "0.003"}, {"Annual Standard Deviation", "0.052"}, {"Annual Variance", "0.003"}, {"Information Ratio", "-0.239"}, {"Tracking Error", "0.408"}, {"Treynor Ratio", "-28.523"}, {"Total Fees", "$7.40"}, {"Estimated Strategy Capacity", "$220000000.00"}, {"Lowest Capacity Asset", "ES XFH59UK0MYO1"}, {"Fitness Score", "0.008"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "-0.224"}, {"Return Over Maximum Drawdown", "-2.009"}, {"Portfolio Turnover", "0.023"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "d3fa88c3acadb9345ceac76a2dd3b520"} }; } }
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Castle.DynamicProxy { using System; using System.Collections.Generic; using System.Reflection.Emit; using System.Runtime.Serialization; #if DOTNET40 using System.Security; #endif #if SILVERLIGHT public class ProxyGenerationOptions #else [Serializable] public class ProxyGenerationOptions : ISerializable #endif { public static readonly ProxyGenerationOptions Default = new ProxyGenerationOptions(); private List<object> mixins; internal readonly IList<Attribute> attributesToAddToGeneratedTypes = new List<Attribute>(); private readonly IList<CustomAttributeBuilder> additionalAttributes = new List<CustomAttributeBuilder>(); #if !SILVERLIGHT [NonSerialized] #endif private MixinData mixinData; // this is calculated dynamically on proxy type creation /// <summary> /// Initializes a new instance of the <see cref = "ProxyGenerationOptions" /> class. /// </summary> /// <param name = "hook">The hook.</param> public ProxyGenerationOptions(IProxyGenerationHook hook) { BaseTypeForInterfaceProxy = typeof(object); Hook = hook; } /// <summary> /// Initializes a new instance of the <see cref = "ProxyGenerationOptions" /> class. /// </summary> public ProxyGenerationOptions() : this(new AllMethodsHook()) { } #if !SILVERLIGHT private ProxyGenerationOptions(SerializationInfo info, StreamingContext context) { Hook = (IProxyGenerationHook)info.GetValue("hook", typeof(IProxyGenerationHook)); Selector = (IInterceptorSelector)info.GetValue("selector", typeof(IInterceptorSelector)); mixins = (List<object>)info.GetValue("mixins", typeof(List<object>)); BaseTypeForInterfaceProxy = Type.GetType(info.GetString("baseTypeForInterfaceProxy.AssemblyQualifiedName")); } #endif public void Initialize() { if (mixinData == null) { try { mixinData = new MixinData(mixins); } catch (ArgumentException ex) { throw new InvalidMixinConfigurationException( "There is a problem with the mixins added to this ProxyGenerationOptions: " + ex.Message, ex); } } } #if !SILVERLIGHT #if DOTNET40 [SecurityCritical] #endif public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("hook", Hook); info.AddValue("selector", Selector); info.AddValue("mixins", mixins); info.AddValue("baseTypeForInterfaceProxy.AssemblyQualifiedName", BaseTypeForInterfaceProxy.AssemblyQualifiedName); } #endif public IProxyGenerationHook Hook { get; set; } public IInterceptorSelector Selector { get; set; } public Type BaseTypeForInterfaceProxy { get; set; } [Obsolete( "This property is obsolete and will be removed in future versions. Use AdditionalAttributes property instead. " + "You can use AttributeUtil class to simplify creating CustomAttributeBuilder instances for common cases.")] public IList<Attribute> AttributesToAddToGeneratedTypes { get { return attributesToAddToGeneratedTypes; } } public IList<CustomAttributeBuilder> AdditionalAttributes { get { return additionalAttributes; } } public MixinData MixinData { get { if (mixinData == null) { throw new InvalidOperationException("Call Initialize before accessing the MixinData property."); } return mixinData; } } public void AddMixinInstance(object instance) { if (instance == null) { throw new ArgumentNullException("instance"); } if (mixins == null) { mixins = new List<object>(); } mixins.Add(instance); mixinData = null; } public object[] MixinsAsArray() { if (mixins == null) { return new object[0]; } return mixins.ToArray(); } public bool HasMixins { get { return mixins != null && mixins.Count != 0; } } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) { return true; } var proxyGenerationOptions = obj as ProxyGenerationOptions; if (ReferenceEquals(proxyGenerationOptions, null)) { return false; } // ensure initialization before accessing MixinData Initialize(); proxyGenerationOptions.Initialize(); if (!Equals(Hook, proxyGenerationOptions.Hook)) { return false; } if (!Equals(Selector == null, proxyGenerationOptions.Selector == null)) { return false; } if (!Equals(MixinData, proxyGenerationOptions.MixinData)) { return false; } if (!Equals(BaseTypeForInterfaceProxy, proxyGenerationOptions.BaseTypeForInterfaceProxy)) { return false; } return true; } public override int GetHashCode() { // ensure initialization before accessing MixinData Initialize(); var result = Hook != null ? Hook.GetType().GetHashCode() : 0; result = 29*result + (Selector != null ? 1 : 0); result = 29*result + MixinData.GetHashCode(); result = 29*result + (BaseTypeForInterfaceProxy != null ? BaseTypeForInterfaceProxy.GetHashCode() : 0); return result; } } }
using System; using System.Collections.Generic; using System.Text; namespace ERY.EMath { [Serializable] public struct Vector3 { private double mx, my, mz; public const double TOLERANCE = 1e-10; public Vector3(Vector3 r) { mx = r.X; my = r.Y; mz = r.Z; } public Vector3(double x, double y, double z) { mx = x; my = y; mz = z; } public void set(double x, double y, double z) { mx = x; my = y; mz = z; } public static readonly Vector3 Zero = new Vector3(0,0,0); public double this[int index] { get { switch (index) { case 0: return mx; case 1: return my; case 2: return mz; default: throw new IndexOutOfRangeException(); } } set { switch (index) { case 0: mx = value; break; case 1: my = value; break; case 2: mz = value; break; default: throw new IndexOutOfRangeException(); } } } public double X { get { return mx; } set { mx = value; } } public double Y { get { return my; } set { my = value; } } public double Z { get { return mz; } set { mz = value; } } public double Theta { get { return Math.Acos(Z / Magnitude); } } public double Phi { get { return Math.Atan2(Y, X); } } public double Magnitude { get { return Math.Sqrt(MagnitudeSquared); } } public double MagnitudeSquared { get { return X * X + Y * Y + Z * Z; } } public double DotProduct(Vector3 r) { return X * r.X + Y * r.Y + Z * r.Z; } public Vector3 CrossProduct(Vector3 r) { return new Vector3(this[1] * r[2] - this[2] * r[1], this[2] * r[0] - this[0] * r[2], this[0] * r[1] - this[1] * r[0]); } public static Vector3 CrossProduct(Vector3 left, Vector3 right) { return new Vector3(left[1] * right[2] - left[2] * right[1], left[2] * right[0] - left[0] * right[2], left[0] * right[1] - left[1] * right[0]); } public static Vector3 operator +(Vector3 a, Vector3 b) { Vector3 retval = new Vector3(); for (int i = 0; i < 3; i++) retval[i] = a[i] + b[i]; return retval; } public static Vector3 operator -(Vector3 a, Vector3 b) { Vector3 retval = new Vector3(); for (int i = 0; i < 3; i++) retval[i] = a[i] - b[i]; return retval; } public static Vector3 operator -(Vector3 a) { return new Vector3(-a[0], -a[1], -a[2]); } public static Vector3 operator *(Vector3 a, double r) { Vector3 retval = new Vector3(); for (int i = 0; i < 3; i++) retval[i] = a[i] * r; return retval; } public static Vector3 operator /(Vector3 a, double r) { Vector3 retval = new Vector3(); for (int i = 0; i < 3; i++) retval[i] = a[i] / r; return retval; } /* public static explicit operator Vector3<G> (Vector3 double) { return Vector3<G>(double.x, double.y, double.z); } */ public static bool operator ==(Vector3 a, Vector3 b) { Vector3 t = a - b; if (t.Magnitude <= TOLERANCE * a.Magnitude) return true; else return false; } public static bool operator !=(Vector3 a, Vector3 b) { return !(a == b); } public static Vector3 operator *(double r1, Vector3 r2) { return r2 * r1; } public override string ToString() { string buffer; buffer = string.Format("({0}, {1}, {2})", (double)this[0], (double)this[1], (double)this[2]); return buffer; } public string ToString(string format) { string buffer; buffer = string.Format("({0:" + format + "}, {1:" + format + "}, {2:" + format + "})", (double)this[0], (double)this[1], (double)this[2]); return buffer; } public override bool Equals(object obj) { if (obj is Vector3) { return this == (Vector3)obj; } else return false; } public override int GetHashCode() { return base.GetHashCode(); } public static Vector3 Parse(string text) { Vector3 retval; if (TryParse(text, out retval) == false) throw new InvalidCastException(string.Format( @"Could not parse text ""{0}""", text)); return retval; } public static bool TryParse(string text, out Vector3 value) { if (text.StartsWith("(") && text.EndsWith(")")) text = text.Substring(1, text.Length - 2); string[] vals = text.Split(new char[]{ ' ',',','\t' }, StringSplitOptions.RemoveEmptyEntries); value = new Vector3(); if (vals.Length < 3) return false; bool valid = true; valid &= double.TryParse(vals[0], out value.mx); valid &= double.TryParse(vals[1], out value.my); valid &= double.TryParse(vals[2], out value.mz); return valid; } public static Vector3 Parse(string x, string y, string z) { return new Vector3( double.Parse(x), double.Parse(y), double.Parse(z)); } public static Vector3 SphericalPolar(double r, double theta, double phi) { return new Vector3( r * Math.Sin(theta) * Math.Cos(phi), r * Math.Sin(theta) * Math.Sin(phi), r * Math.Cos(theta)); } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt #nullable enable using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using NUnit.Compatibility; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Builders; namespace NUnit.Framework { /// <summary> /// Marks a method as a parameterized test suite and provides arguments for each test case. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited=false)] public class TestCaseAttribute : NUnitAttribute, ITestBuilder, ITestCaseData, IImplyFixture { #region Constructors /// <summary> /// Construct a TestCaseAttribute with a list of arguments. /// This constructor is not CLS-Compliant /// </summary> /// <param name="arguments"></param> public TestCaseAttribute(params object?[]? arguments) { RunState = RunState.Runnable; if (arguments == null) Arguments = new object?[] { null }; else Arguments = arguments; Properties = new PropertyBag(); } /// <summary> /// Construct a TestCaseAttribute with a single argument /// </summary> /// <param name="arg"></param> public TestCaseAttribute(object? arg) { RunState = RunState.Runnable; Arguments = new object?[] { arg }; Properties = new PropertyBag(); } /// <summary> /// Construct a TestCaseAttribute with a two arguments /// </summary> /// <param name="arg1"></param> /// <param name="arg2"></param> public TestCaseAttribute(object? arg1, object? arg2) { RunState = RunState.Runnable; Arguments = new object?[] { arg1, arg2 }; Properties = new PropertyBag(); } /// <summary> /// Construct a TestCaseAttribute with a three arguments /// </summary> /// <param name="arg1"></param> /// <param name="arg2"></param> /// <param name="arg3"></param> public TestCaseAttribute(object? arg1, object? arg2, object? arg3) { RunState = RunState.Runnable; Arguments = new object?[] { arg1, arg2, arg3 }; Properties = new PropertyBag(); } #endregion #region ITestData Members /// <summary> /// Gets or sets the name of the test. /// </summary> /// <value>The name of the test.</value> public string? TestName { get; set; } /// <summary> /// Gets or sets the RunState of this test case. /// </summary> public RunState RunState { get; private set; } /// <summary> /// Gets the list of arguments to a test case /// </summary> public object?[] Arguments { get; } /// <summary> /// Gets the properties of the test case /// </summary> public IPropertyBag Properties { get; } #endregion #region ITestCaseData Members /// <summary> /// Gets or sets the expected result. /// </summary> /// <value>The result.</value> public object? ExpectedResult { get { return _expectedResult; } set { _expectedResult = value; HasExpectedResult = true; } } private object? _expectedResult; /// <summary> /// Returns true if the expected result has been set /// </summary> public bool HasExpectedResult { get; private set; } #endregion #region Instance Fields private RunState _originalRunState; private DateTimeOffset? _untilDate; #endregion #region Other Properties /// <summary> /// Gets or sets the description. /// </summary> /// <value>The description.</value> [DisallowNull] public string? Description { get { return Properties.Get(PropertyNames.Description) as string; } set { Guard.ArgumentNotNull(value, nameof(value)); Properties.Set(PropertyNames.Description, value); } } /// <summary> /// The author of this test /// </summary> [DisallowNull] public string? Author { get { return Properties.Get(PropertyNames.Author) as string; } set { Guard.ArgumentNotNull(value, nameof(value)); Properties.Set(PropertyNames.Author, value); } } /// <summary> /// The type that this test is testing /// </summary> [DisallowNull] public Type? TestOf { get { return _testOf; } set { Guard.ArgumentNotNull(value, nameof(value)); _testOf = value; Properties.Set(PropertyNames.TestOf, value.FullName); } } private Type? _testOf; /// <summary> /// Gets or sets the reason for ignoring the test /// </summary> [DisallowNull] public string? Ignore { get { return IgnoreReason; } set { Guard.ArgumentNotNull(value, nameof(value)); IgnoreReason = value; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="NUnit.Framework.TestCaseAttribute"/> is explicit. /// </summary> /// <value> /// <see langword="true"/> if explicit; otherwise, <see langword="false"/>. /// </value> public bool Explicit { get { return RunState == RunState.Explicit; } set { RunState = value ? RunState.Explicit : RunState.Runnable; } } /// <summary> /// Gets or sets the reason for not running the test. /// </summary> /// <value>The reason.</value> [DisallowNull] public string? Reason { get { return Properties.Get(PropertyNames.SkipReason) as string; } set { Guard.ArgumentNotNull(value, nameof(value)); Properties.Set(PropertyNames.SkipReason, value); } } /// <summary> /// Gets or sets the ignore reason. When set to a non-null /// non-empty value, the test is marked as ignored. /// </summary> /// <value>The ignore reason.</value> [DisallowNull] public string? IgnoreReason { get { return Reason; } set { Guard.ArgumentNotNull(value, nameof(value)); _originalRunState = RunState; RunState = RunState.Ignored; Reason = value; } } /// <summary> /// Comma-delimited list of platforms to run the test for /// </summary> public string? IncludePlatform { get; set; } /// <summary> /// Comma-delimited list of platforms to not run the test for /// </summary> public string? ExcludePlatform { get; set; } /// <summary> /// Gets and sets the category for this test case. /// May be a comma-separated list of categories. /// </summary> [DisallowNull] public string? Category { get { return Properties.Get(PropertyNames.Category) as string; } set { Guard.ArgumentNotNull(value, nameof(value)); foreach (string cat in value.Split(new char[] { ',' }) ) Properties.Add(PropertyNames.Category, cat); } } /// <summary> /// Gets and sets the ignore until date for this test case. /// </summary> public string? Until { get { return Properties.Get(PropertyNames.IgnoreUntilDate) as string; } set { if (!string.IsNullOrEmpty(IgnoreReason)) { _untilDate = DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); Properties.Set(PropertyNames.IgnoreUntilDate, _untilDate.Value.ToString("u")); } else this.RunState = RunState.NotRunnable; } } #endregion #region Helper Methods private TestCaseParameters GetParametersForTestCase(IMethodInfo method) { TestCaseParameters parms; try { IParameterInfo[] parameters = method.GetParameters(); int argsNeeded = parameters.Length; int argsProvided = Arguments.Length; parms = new TestCaseParameters(this); // Special handling for ExpectedResult (see if it needs to be converted into method return type) if (parms.HasExpectedResult && ParamAttributeTypeConversions.TryConvert(parms.ExpectedResult, method.ReturnType.Type, out var expectedResultInTargetType)) { parms.ExpectedResult = expectedResultInTargetType; } // Special handling for params arguments if (argsNeeded > 0 && argsProvided >= argsNeeded - 1) { IParameterInfo lastParameter = parameters[argsNeeded - 1]; Type lastParameterType = lastParameter.ParameterType; Type elementType = lastParameterType.GetElementType(); if (lastParameterType.IsArray && lastParameter.IsDefined<ParamArrayAttribute>(false)) { if (argsProvided == argsNeeded) { if (!lastParameterType.IsInstanceOfType(parms.Arguments[argsProvided - 1])) { Array array = Array.CreateInstance(elementType, 1); array.SetValue(parms.Arguments[argsProvided - 1], 0); parms.Arguments[argsProvided - 1] = array; } } else { object?[] newArglist = new object?[argsNeeded]; for (int i = 0; i < argsNeeded && i < argsProvided; i++) newArglist[i] = parms.Arguments[i]; int length = argsProvided - argsNeeded + 1; Array array = Array.CreateInstance(elementType, length); for (int i = 0; i < length; i++) array.SetValue(parms.Arguments[argsNeeded + i - 1], i); newArglist[argsNeeded - 1] = array; parms.Arguments = newArglist; argsProvided = argsNeeded; } } } //Special handling for optional parameters if (parms.Arguments.Length < argsNeeded) { object?[] newArgList = new object?[parameters.Length]; Array.Copy(parms.Arguments, newArgList, parms.Arguments.Length); //Fill with Type.Missing for remaining required parameters where optional for (var i = parms.Arguments.Length; i < parameters.Length; i++) { if (parameters[i].IsOptional) newArgList[i] = Type.Missing; else { if (i < parms.Arguments.Length) newArgList[i] = parms.Arguments[i]; else throw new TargetParameterCountException(string.Format( "Method requires {0} arguments but TestCaseAttribute only supplied {1}", argsNeeded, argsProvided)); } } parms.Arguments = newArgList; } // Special handling when sole argument is an object[] if (argsNeeded == 1 && method.GetParameters()[0].ParameterType == typeof(object[])) { if (argsProvided > 1 || argsProvided == 1 && parms.Arguments[0]?.GetType() != typeof(object[])) { parms.Arguments = new object[] { parms.Arguments }; } } if (argsProvided == argsNeeded) PerformSpecialConversions(parms.Arguments, parameters); } catch (Exception ex) { parms = new TestCaseParameters(ex); } return parms; } /// <summary> /// Performs several special conversions allowed by NUnit in order to /// permit arguments with types that cannot be used in the constructor /// of an Attribute such as TestCaseAttribute or to simplify their use. /// </summary> /// <param name="arglist">The arguments to be converted</param> /// <param name="parameters">The ParameterInfo array for the method</param> private static void PerformSpecialConversions(object?[] arglist, IParameterInfo[] parameters) { for (int i = 0; i < arglist.Length; i++) { object? arg = arglist[i]; Type targetType = parameters[i].ParameterType; if (ParamAttributeTypeConversions.TryConvert(arg, targetType, out var argAsTargetType)) { arglist[i] = argAsTargetType; } } } #endregion #region ITestBuilder Members /// <summary> /// Builds a single test from the specified method and context. /// </summary> /// <param name="method">The MethodInfo for which tests are to be constructed.</param> /// <param name="suite">The suite to which the tests will be added.</param> public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test? suite) { TestMethod test = new NUnitTestCaseBuilder().BuildTestMethod(method, suite, GetParametersForTestCase(method)); if (_untilDate.HasValue) { if (_untilDate > DateTimeOffset.UtcNow) { test.RunState = RunState.Ignored; string reason = string.Format("Ignoring until {0}. {1}", _untilDate.Value.ToString("u"), IgnoreReason); test.Properties.Set(PropertyNames.SkipReason, reason); } else { test.RunState = _originalRunState; } } if (IncludePlatform != null || ExcludePlatform != null) { if (test.RunState == RunState.NotRunnable || test.RunState == RunState.Ignored) { yield return test; yield break; } var platformHelper = new PlatformHelper(); if (!platformHelper.IsPlatformSupported(this)) { test.RunState = RunState.Skipped; test.Properties.Add(PropertyNames.SkipReason, platformHelper.Reason); } } yield return test; } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { // [ExportWorkspaceServiceFactory(typeof(ITemporaryStorageService), ServiceLayer.Host), Shared] internal partial class TemporaryStorageServiceFactory : IWorkspaceServiceFactory { public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { var textFactory = workspaceServices.GetService<ITextFactoryService>(); return new TemporaryStorageService(textFactory); } /// <summary> /// Temporarily stores text and streams in memory mapped files. /// </summary> internal class TemporaryStorageService : ITemporaryStorageService2 { private readonly ITextFactoryService _textFactory; public TemporaryStorageService(ITextFactoryService textFactory) { _textFactory = textFactory; } public ITemporaryTextStorage CreateTemporaryTextStorage(CancellationToken cancellationToken) { return new TemporaryTextStorage(this); } public ITemporaryTextStorage AttachTemporaryTextStorage(string storageName, long size, Encoding encoding, CancellationToken cancellationToken) { return new TemporaryTextStorage(this, storageName, size, encoding); } public ITemporaryStreamStorage CreateTemporaryStreamStorage(CancellationToken cancellationToken) { return new TemporaryStreamStorage(this); } public ITemporaryStreamStorage AttachTemporaryStreamStorage(string storageName, long size, CancellationToken cancellationToken) { return new TemporaryStreamStorage(this, storageName, size); } private class TemporaryTextStorage : ITemporaryTextStorage, ITemporaryStorageWithName { private readonly TemporaryStorageService _service; private Encoding _encoding; private MemoryMappedInfo _memoryMappedInfo; public TemporaryTextStorage(TemporaryStorageService service) { _service = service; } public TemporaryTextStorage(TemporaryStorageService service, string storageName, long size, Encoding encoding) { _service = service; _encoding = encoding; // _memoryMappedInfo = new MemoryMappedInfo(storageName, size); } public string Name => ""; // _memoryMappedInfo?.Name; public long Size => 0; // _memoryMappedInfo.Size; public void Dispose() { if (_memoryMappedInfo != null) { // Destructors of SafeHandle and FileStream in MemoryMappedFile // will eventually release resources if this Dispose is not called // explicitly _memoryMappedInfo.Dispose(); _memoryMappedInfo = null; } if (_encoding != null) { _encoding = null; } } public SourceText ReadText(CancellationToken cancellationToken) { if (_memoryMappedInfo == null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadText, cancellationToken)) { //using (var stream = _memoryMappedInfo.CreateReadableStream()) //using (var reader = CreateTextReaderFromTemporaryStorage((ISupportDirectMemoryAccess)stream, (int)stream.Length, cancellationToken)) //{ // // we pass in encoding we got from original source text even if it is null. // return _service._textFactory.CreateText(reader, _encoding, cancellationToken); //} return null; } } public Task<SourceText> ReadTextAsync(CancellationToken cancellationToken) { // There is a reason for implementing it like this: proper async implementation // that reads the underlying memory mapped file stream in an asynchronous fashion // doesn't actually work. Windows doesn't offer // any non-blocking way to read from a memory mapped file; the underlying memcpy // may block as the memory pages back in and that's something you have to live // with. Therefore, any implementation that attempts to use async will still // always be blocking at least one threadpool thread in the memcpy in the case // of a page fault. Therefore, if we're going to be blocking a thread, we should // just block one thread and do the whole thing at once vs. a fake "async" // implementation which will continue to requeue work back to the thread pool. return Task.Factory.StartNew(() => ReadText(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void WriteText(SourceText text, CancellationToken cancellationToken) { if (_memoryMappedInfo != null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteText, cancellationToken)) { _encoding = text.Encoding; // the method we use to get text out of SourceText uses Unicode (2bytes per char). var size = Encoding.Unicode.GetMaxByteCount(text.Length); //_memoryMappedInfo = new MemoryMappedInfo(size); //// Write the source text out as Unicode. We expect that to be cheap. //using (var stream = _memoryMappedInfo.CreateWritableStream()) //{ // using (var writer = new StreamWriter(stream, Encoding.Unicode)) // { // text.Write(writer, cancellationToken); // } //} } } public Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default(CancellationToken)) { // See commentary in ReadTextAsync for why this is implemented this way. return Task.Factory.StartNew(() => WriteText(text, cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } private unsafe TextReader CreateTextReaderFromTemporaryStorage(ISupportDirectMemoryAccess accessor, int streamLength, CancellationToken cancellationToken) { char* src = (char*)accessor.GetPointer(); // BOM: Unicode, little endian // Skip the BOM when creating the reader Debug.Assert(*src == 0xFEFF); return new DirectMemoryAccessStreamReader(src + 1, streamLength / sizeof(char) - 1); } } private class TemporaryStreamStorage : ITemporaryStreamStorage, ITemporaryStorageWithName { private readonly TemporaryStorageService _service; private MemoryMappedInfo _memoryMappedInfo; public TemporaryStreamStorage(TemporaryStorageService service) { _service = service; } public TemporaryStreamStorage(TemporaryStorageService service, string storageName, long size) { _service = service; //_memoryMappedInfo = new MemoryMappedInfo(storageName, size); } public string Name => ""; // _memoryMappedInfo?.Name; public long Size => 0; // _memoryMappedInfo.Size; public void Dispose() { if (_memoryMappedInfo != null) { // Destructors of SafeHandle and FileStream in MemoryMappedFile // will eventually release resources if this Dispose is not called // explicitly _memoryMappedInfo.Dispose(); _memoryMappedInfo = null; } } public Stream ReadStream(CancellationToken cancellationToken) { if (_memoryMappedInfo == null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadStream, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return null; // _memoryMappedInfo.CreateReadableStream(); } } public Task<Stream> ReadStreamAsync(CancellationToken cancellationToken = default(CancellationToken)) { // See commentary in ReadTextAsync for why this is implemented this way. return Task.Factory.StartNew(() => ReadStream(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void WriteStream(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { // The Wait() here will not actually block, since with useAsync: false, the // entire operation will already be done when WaitStreamMaybeAsync completes. WriteStreamMaybeAsync(stream, useAsync: false, cancellationToken: cancellationToken).GetAwaiter().GetResult(); } public Task WriteStreamAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { return WriteStreamMaybeAsync(stream, useAsync: true, cancellationToken: cancellationToken); } private async Task WriteStreamMaybeAsync(Stream stream, bool useAsync, CancellationToken cancellationToken) { if (_memoryMappedInfo != null) { throw new InvalidOperationException(WorkspacesResources.Temporary_storage_cannot_be_written_more_than_once); } if (stream.Length == 0) { throw new ArgumentOutOfRangeException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteStream, cancellationToken)) { var size = stream.Length; //_memoryMappedInfo = new MemoryMappedInfo(size); //using (var viewStream = _memoryMappedInfo.CreateWritableStream()) //{ // var buffer = SharedPools.ByteArray.Allocate(); // try // { // while (true) // { // int count; // if (useAsync) // { // count = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); // } // else // { // count = stream.Read(buffer, 0, buffer.Length); // } // if (count == 0) // { // break; // } // viewStream.Write(buffer, 0, count); // } // } // finally // { // SharedPools.ByteArray.Free(buffer); // } //} } } } } internal unsafe class DirectMemoryAccessStreamReader : TextReaderWithLength { private char* _position; private readonly char* _end; public DirectMemoryAccessStreamReader(char* src, int length) : base(length) { Debug.Assert(src != null); Debug.Assert(length >= 0); _position = src; _end = _position + length; } public override int Peek() { if (_position >= _end) { return -1; } return *_position; } public override int Read() { if (_position >= _end) { return -1; } return *_position++; } public override int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0 || index >= buffer.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0 || (index + count) > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } count = Math.Min(count, (int)(_end - _position)); if (count > 0) { Marshal.Copy((IntPtr)_position, buffer, index, count); _position += count; } return count; } } } }
// 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: Platform independent integer ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Security; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public struct IntPtr : IEquatable<IntPtr>, ISerializable { unsafe private void* m_value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior public static readonly IntPtr Zero; // fast way to compare IntPtr to (IntPtr)0 while IntPtr.Zero doesn't work due to slow statics access [Pure] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe bool IsNull() { return (this.m_value == null); } [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public unsafe IntPtr(int value) { #if BIT64 m_value = (void *)(long)value; #else // !BIT64 (32) m_value = (void *)value; #endif } [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public unsafe IntPtr(long value) { #if BIT64 m_value = (void *)value; #else // !BIT64 (32) m_value = (void *)checked((int)value); #endif } [CLSCompliant(false)] [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public unsafe IntPtr(void* value) { m_value = value; } private unsafe IntPtr(SerializationInfo info, StreamingContext context) { long l = info.GetInt64("value"); if (Size==4 && (l>Int32.MaxValue || l<Int32.MinValue)) { throw new ArgumentException(Environment.GetResourceString("Serialization_InvalidPtrValue")); } m_value = (void *)l; } unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) { throw new ArgumentNullException(nameof(info)); } Contract.EndContractBlock(); #if BIT64 info.AddValue("value", (long)(m_value)); #else // !BIT64 (32) info.AddValue("value", (long)((int)m_value)); #endif } public unsafe override bool Equals(Object obj) { if (obj is IntPtr) { return (m_value == ((IntPtr)obj).m_value); } return false; } unsafe bool IEquatable<IntPtr>.Equals(IntPtr other) { return m_value == other.m_value; } public unsafe override int GetHashCode() { #if BIT64 long l = (long)m_value; return (unchecked((int)l) ^ (int)(l >> 32)); #else // !BIT64 (32) return unchecked((int)m_value); #endif } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public unsafe int ToInt32() { #if BIT64 long l = (long)m_value; return checked((int)l); #else // !BIT64 (32) return (int)m_value; #endif } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public unsafe long ToInt64() { #if BIT64 return (long)m_value; #else // !BIT64 (32) return (long)(int)m_value; #endif } public unsafe override String ToString() { #if BIT64 return ((long)m_value).ToString(CultureInfo.InvariantCulture); #else // !BIT64 (32) return ((int)m_value).ToString(CultureInfo.InvariantCulture); #endif } public unsafe String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); #if BIT64 return ((long)m_value).ToString(format, CultureInfo.InvariantCulture); #else // !BIT64 (32) return ((int)m_value).ToString(format, CultureInfo.InvariantCulture); #endif } [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static explicit operator IntPtr (int value) { return new IntPtr(value); } [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static explicit operator IntPtr (long value) { return new IntPtr(value); } [CLSCompliant(false), ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static unsafe explicit operator IntPtr (void* value) { return new IntPtr(value); } [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static unsafe explicit operator void* (IntPtr value) { return value.m_value; } [System.Runtime.Versioning.NonVersionable] public unsafe static explicit operator int (IntPtr value) { #if BIT64 long l = (long)value.m_value; return checked((int)l); #else // !BIT64 (32) return (int)value.m_value; #endif } [System.Runtime.Versioning.NonVersionable] public unsafe static explicit operator long (IntPtr value) { #if BIT64 return (long)value.m_value; #else // !BIT64 (32) return (long)(int)value.m_value; #endif } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public unsafe static bool operator == (IntPtr value1, IntPtr value2) { return value1.m_value == value2.m_value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public unsafe static bool operator != (IntPtr value1, IntPtr value2) { return value1.m_value != value2.m_value; } [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static IntPtr Add(IntPtr pointer, int offset) { return pointer + offset; } [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static IntPtr operator +(IntPtr pointer, int offset) { #if BIT64 return new IntPtr(pointer.ToInt64() + offset); #else // !BIT64 (32) return new IntPtr(pointer.ToInt32() + offset); #endif } [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static IntPtr Subtract(IntPtr pointer, int offset) { return pointer - offset; } [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static IntPtr operator -(IntPtr pointer, int offset) { #if BIT64 return new IntPtr(pointer.ToInt64() - offset); #else // !BIT64 (32) return new IntPtr(pointer.ToInt32() - offset); #endif } public static int Size { [Pure] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] get { #if BIT64 return 8; #else // !BIT64 (32) return 4; #endif } } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public unsafe void* ToPointer() { return m_value; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using FluentNHibernate.Mapping.Providers; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.Identity; using FluentNHibernate.Utils; namespace FluentNHibernate.Mapping { public class CompositeIdentityPart<T> : ICompositeIdMappingProvider { readonly AccessStrategyBuilder<CompositeIdentityPart<T>> access; readonly AttributeStore attributes = new AttributeStore(); readonly IList<ICompositeIdKeyMapping> keys = new List<ICompositeIdKeyMapping>(); bool nextBool = true; public CompositeIdentityPart() { access = new AccessStrategyBuilder<CompositeIdentityPart<T>>(this, value => attributes.Set("Access", Layer.UserSupplied, value)); } public CompositeIdentityPart(string name) : this() { attributes.Set("Name", Layer.Defaults, name); } /// <summary> /// Defines a property to be used as a key for this composite-id. /// </summary> /// <param name="expression">A member access lambda expression for the property</param> /// <returns>The composite identity part fluent interface</returns> public CompositeIdentityPart<T> KeyProperty(Expression<Func<T, object>> expression) { var member = expression.ToMember(); return KeyProperty(member, member.Name, null); } /// <summary> /// Defines a property to be used as a key for this composite-id with an explicit column name. /// </summary> /// <param name="expression">A member access lambda expression for the property</param> /// <param name="columnName">The column name in the database to use for this key, or null to use the property name</param> /// <returns>The composite identity part fluent interface</returns> public CompositeIdentityPart<T> KeyProperty(Expression<Func<T, object>> expression, string columnName) { var member = expression.ToMember(); return KeyProperty(member, columnName, null); } /// <summary> /// Defines a property to be used as a key for this composite-id with an explicit column name. /// </summary> /// <param name="expression">A member access lambda expression for the property</param> /// <param name="keyPropertyAction">Additional settings for the key property</param> /// <returns>The composite identity part fluent interface</returns> public CompositeIdentityPart<T> KeyProperty(Expression<Func<T, object>> expression, Action<KeyPropertyPart> keyPropertyAction) { var member = expression.ToMember(); return KeyProperty(member, string.Empty, keyPropertyAction); } protected virtual CompositeIdentityPart<T> KeyProperty(Member member, string columnName, Action<KeyPropertyPart> customMapping) { var type = member.PropertyType; if (type.IsEnum) type = typeof(GenericEnumMapper<>).MakeGenericType(type); var key = new KeyPropertyMapping { ContainingEntityType = typeof(T) }; key.Set(x => x.Name, Layer.Defaults, member.Name); key.Set(x => x.Type, Layer.Defaults, new TypeReference(type)); if (customMapping != null) { var part = new KeyPropertyPart(key); customMapping(part); } if (!string.IsNullOrEmpty(columnName)) { var columnMapping = new ColumnMapping(); columnMapping.Set(x => x.Name, Layer.Defaults, columnName); key.AddColumn(columnMapping); } keys.Add(key); return this; } /// <summary> /// Defines a reference to be used as a many-to-one key for this composite-id with an explicit column name. /// </summary> /// <param name="expression">A member access lambda expression for the property</param> /// <returns>The composite identity part fluent interface</returns> public CompositeIdentityPart<T> KeyReference(Expression<Func<T, object>> expression) { var member = expression.ToMember(); return KeyReference(member, new[] { member.Name }, null); } /// <summary> /// Defines a reference to be used as a many-to-one key for this composite-id with an explicit column name. /// </summary> /// <param name="expression">A member access lambda expression for the property</param> /// <param name="columnNames">A list of column names used for this key</param> /// <returns>The composite identity part fluent interface</returns> public CompositeIdentityPart<T> KeyReference(Expression<Func<T, object>> expression, params string[] columnNames) { var member = expression.ToMember(); return KeyReference(member, columnNames, null); } /// <summary> /// Defines a reference to be used as a many-to-one key for this composite-id with an explicit column name. /// </summary> /// <param name="expression">A member access lambda expression for the property</param> /// <param name="customMapping">A lambda expression specifying additional settings for the key reference</param> /// <param name="columnNames">A list of column names used for this key</param> /// <returns>The composite identity part fluent interface</returns> public CompositeIdentityPart<T> KeyReference(Expression<Func<T, object>> expression, Action<KeyManyToOnePart> customMapping, params string[] columnNames) { var member = expression.ToMember(); return KeyReference(member, columnNames, customMapping); } protected virtual CompositeIdentityPart<T> KeyReference(Member property, IEnumerable<string> columnNames, Action<KeyManyToOnePart> customMapping) { var key = new KeyManyToOneMapping { ContainingEntityType = typeof(T) }; key.Set(x => x.Name, Layer.Defaults, property.Name); key.Set(x => x.Class, Layer.Defaults, new TypeReference(property.PropertyType)); foreach (var column in columnNames) { var columnMapping = new ColumnMapping(); columnMapping.Set(x => x.Name, Layer.Defaults, column); key.AddColumn(columnMapping); } var keyPart = new KeyManyToOnePart(key); if (customMapping != null) customMapping(keyPart); keys.Add(key); return this; } public virtual CompositeIdentityPart<T> CustomType<CType>() { var key = keys.Where(x => x is KeyPropertyMapping).Cast<KeyPropertyMapping>().LastOrDefault(); if (key != null) { key.Set(x => x.Type, Layer.Defaults, new TypeReference(typeof(CType))); } return this; } /// <summary> /// Set the access and naming strategy for this identity. /// </summary> public AccessStrategyBuilder<CompositeIdentityPart<T>> Access { get { return access; } } /// <summary> /// Invert the next boolean operation /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public CompositeIdentityPart<T> Not { get { nextBool = false; return this; } } /// <summary> /// Specifies that this composite id is "mapped"; aka, a composite id where /// the properties exist in the identity class as well as in the entity itself /// </summary> public CompositeIdentityPart<T> Mapped() { attributes.Set("Mapped", Layer.UserSupplied, nextBool); nextBool = true; return this; } /// <summary> /// Specifies the unsaved value for the identity /// </summary> /// <param name="value">Unsaved value</param> public CompositeIdentityPart<T> UnsavedValue(string value) { attributes.Set("UnsavedValue", Layer.UserSupplied, value); return this; } /// <summary> /// You may use a component as an identifier of an entity class. Your component class must /// satisfy certain requirements: /// /// * It must be Serializable. /// * It must re-implement Equals() and GetHashCode(), consistently with the database's /// notion of composite key equality. /// /// You can't use an IIdentifierGenerator to generate composite keys. Instead the application /// must assign its own identifiers. Since a composite identifier must be assigned to the object /// before saving it, we can't use unsaved-value of the identifier to distinguish between newly /// instantiated instances and instances saved in a previous session. You may instead implement /// IInterceptor.IsUnsaved() if you wish to use SaveOrUpdate() or cascading save / update. As an /// alternative, you may also set the unsaved-value attribute on a version or timestamp to specify /// a value that indicates a new transient instance. In this case, the version of the entity is /// used instead of the (assigned) identifier and you don't have to implement /// IInterceptor.IsUnsaved() yourself. /// </summary> /// <param name="expression">The property of component type that holds the composite identifier.</param> /// <remarks> /// Your persistent class must override Equals() and GetHashCode() to implement composite identifier /// equality. It must also be Serializable. /// </remarks> public CompositeIdentityPart<T> ComponentCompositeIdentifier<TComponentType>(Expression<Func<T, TComponentType>> expression) { attributes.Set("Class", Layer.Defaults, new TypeReference(typeof(TComponentType))); attributes.Set("Name", Layer.Defaults, expression.ToMember().Name); return this; } CompositeIdMapping ICompositeIdMappingProvider.GetCompositeIdMapping() { var mapping = new CompositeIdMapping(attributes.Clone()) { ContainingEntityType = typeof(T) }; keys.Each(mapping.AddKey); return mapping; } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. 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. *******************************************************************************/ // // Novell.Directory.Ldap.LdapSearchRequest.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using Novell.Directory.LDAP.VQ.Asn1; using Novell.Directory.LDAP.VQ.Rfc2251; namespace Novell.Directory.LDAP.VQ { /// <summary> Represents an Ldap Search request. /// /// </summary> /// <seealso cref="LdapConnection.SendRequest"> /// </seealso> /* * SearchRequest ::= [APPLICATION 3] SEQUENCE { * baseObject LdapDN, * scope ENUMERATED { * baseObject (0), * singleLevel (1), * wholeSubtree (2) }, * derefAliases ENUMERATED { * neverDerefAliases (0), * derefInSearching (1), * derefFindingBaseObj (2), * derefAlways (3) }, * sizeLimit INTEGER (0 .. maxInt), * timeLimit INTEGER (0 .. maxInt), * typesOnly BOOLEAN, * filter Filter, * attributes AttributeDescriptionList } */ public class LdapSearchRequest : LdapMessage { /// <summary> Retrieves the Base DN for a search request. /// /// </summary> /// <returns> the base DN for a search request /// </returns> virtual public string DN { get { return Asn1Object.RequestDN; } } /// <summary> Retrieves the scope of a search request.</summary> /// <returns> scope of a search request /// /// </returns> /// <seealso cref="LdapConnection.SCOPE_BASE"> /// </seealso> /// <seealso cref="LdapConnection.SCOPE_ONE"> /// </seealso> /// <seealso cref="LdapConnection.SCOPE_SUB"> /// </seealso> virtual public int Scope { get { //element number one stores the scope return ((Asn1Enumerated)((RfcSearchRequest)(Asn1Object).get_Renamed(1)).get_Renamed(1)).intValue(); } } /// <summary> Retrieves the behaviour of dereferencing aliases on a search request.</summary> /// <returns> integer representing how to dereference aliases /// /// </returns> /// <seealso cref="LdapSearchConstraints.DEREF_ALWAYS"> /// </seealso> /// <seealso cref="LdapSearchConstraints.DEREF_FINDING"> /// </seealso> /// <seealso cref="LdapSearchConstraints.DEREF_NEVER"> /// </seealso> /// <seealso cref="LdapSearchConstraints.DEREF_SEARCHING"> /// </seealso> virtual public int Dereference { get { //element number two stores the dereference return ((Asn1Enumerated)((RfcSearchRequest)(Asn1Object).get_Renamed(1)).get_Renamed(2)).intValue(); } } /// <summary> Retrieves the maximum number of entries to be returned on a search. /// /// </summary> /// <returns> Maximum number of search entries. /// </returns> virtual public int MaxResults { get { //element number three stores the max results return ((Asn1Integer)((RfcSearchRequest)(Asn1Object).get_Renamed(1)).get_Renamed(3)).intValue(); } } /// <summary> Retrieves the server time limit for a search request. /// /// </summary> /// <returns> server time limit in nanoseconds. /// </returns> virtual public int ServerTimeLimit { get { //element number four stores the server time limit return ((Asn1Integer)((RfcSearchRequest)(Asn1Object).get_Renamed(1)).get_Renamed(4)).intValue(); } } /// <summary> Retrieves whether attribute values or only attribute types(names) should /// be returned in a search request. /// </summary> /// <returns> true if only attribute types (names) are returned, false if /// attributes types and values are to be returned. /// </returns> virtual public bool TypesOnly { get { //element number five stores types value return ((Asn1Boolean)((RfcSearchRequest)(Asn1Object).get_Renamed(1)).get_Renamed(5)).booleanValue(); } } /// <summary> Retrieves an array of attribute names to request for in a search.</summary> /// <returns> Attribute names to be searched /// </returns> virtual public string[] Attributes { get { RfcAttributeDescriptionList attrs = (RfcAttributeDescriptionList)((RfcSearchRequest)(Asn1Object).get_Renamed(1)).get_Renamed(7); string[] rAttrs = new string[attrs.size()]; for (int i = 0; i < rAttrs.Length; i++) { rAttrs[i] = ((RfcAttributeDescription)attrs.get_Renamed(i)).stringValue(); } return rAttrs; } } /// <summary> Creates a string representation of the filter in this search request.</summary> /// <returns> filter string for this search request /// </returns> virtual public string StringFilter { get { return RfcFilter.filterToString(); } } /// <summary> Retrieves an SearchFilter object representing a filter for a search request</summary> /// <returns> filter object for a search request. /// </returns> private RfcFilter RfcFilter { get { return (RfcFilter)((RfcSearchRequest)(Asn1Object).get_Renamed(1)).get_Renamed(6); } } /// <summary> Retrieves an Iterator object representing the parsed filter for /// this search request. /// /// The first object returned from the Iterator is an Integer indicating /// the type of filter component. One or more values follow the component /// type as subsequent items in the Iterator. The pattern of Integer /// component type followed by values continues until the end of the /// filter. /// /// Values returned as a byte array may represent UTF-8 characters or may /// be binary values. The possible Integer components of a search filter /// and the associated values that follow are: /// <ul> /// <li>AND - followed by an Iterator value</li> /// <li>OR - followed by an Iterator value</li> /// <li>NOT - followed by an Iterator value</li> /// <li>EQUALITY_MATCH - followed by the attribute name represented as a /// string, and by the attribute value represented as a byte array</li> /// <li>GREATER_OR_EQUAL - followed by the attribute name represented as a /// string, and by the attribute value represented as a byte array</li> /// <li>LESS_OR_EQUAL - followed by the attribute name represented as a /// string, and by the attribute value represented as a byte array</li> /// <li>APPROX_MATCH - followed by the attribute name represented as a /// string, and by the attribute value represented as a byte array</li> /// <li>PRESENT - followed by a attribute name respresented as a string</li> /// <li>EXTENSIBLE_MATCH - followed by the name of the matching rule /// represented as a string, by the attribute name represented /// as a string, and by the attribute value represented as a /// byte array.</li> /// <li>SUBSTRINGS - followed by the attribute name represented as a /// string, by one or more SUBSTRING components (INITIAL, ANY, /// or FINAL) followed by the SUBSTRING value.</li> /// </ul> /// /// </summary> /// <returns> Iterator representing filter components /// </returns> virtual public System.Collections.IEnumerator SearchFilter { get { return RfcFilter.getFilterIterator(); } } //************************************************************************* // Public variables for Filter //************************************************************************* /// <summary> Search Filter Identifier for an AND component.</summary> public const int AND = 0; /// <summary> Search Filter Identifier for an OR component.</summary> public const int OR = 1; /// <summary> Search Filter Identifier for a NOT component.</summary> public const int NOT = 2; /// <summary> Search Filter Identifier for an EQUALITY_MATCH component.</summary> public const int EQUALITY_MATCH = 3; /// <summary> Search Filter Identifier for a SUBSTRINGS component.</summary> public const int SUBSTRINGS = 4; /// <summary> Search Filter Identifier for a GREATER_OR_EQUAL component.</summary> public const int GREATER_OR_EQUAL = 5; /// <summary> Search Filter Identifier for a LESS_OR_EQUAL component.</summary> public const int LESS_OR_EQUAL = 6; /// <summary> Search Filter Identifier for a PRESENT component.</summary> public const int PRESENT = 7; /// <summary> Search Filter Identifier for an APPROX_MATCH component.</summary> public const int APPROX_MATCH = 8; /// <summary> Search Filter Identifier for an EXTENSIBLE_MATCH component.</summary> public const int EXTENSIBLE_MATCH = 9; /// <summary> Search Filter Identifier for an INITIAL component of a SUBSTRING. /// Note: An initial SUBSTRING is represented as "value*". /// </summary> public const int INITIAL = 0; /// <summary> Search Filter Identifier for an ANY component of a SUBSTRING. /// Note: An ANY SUBSTRING is represented as "*value*". /// </summary> public const int ANY = 1; /// <summary> Search Filter Identifier for a FINAL component of a SUBSTRING. /// Note: A FINAL SUBSTRING is represented as "*value". /// </summary> public const int FINAL = 2; /// <summary> Constructs an Ldap Search Request. /// /// </summary> /// <param name="base"> The base distinguished name to search from. /// /// </param> /// <param name="scope"> The scope of the entries to search. The following /// are the valid options: /// <ul> /// <li>SCOPE_BASE - searches only the base DN</li> /// /// <li>SCOPE_ONE - searches only entries under the base DN</li> /// /// <li>SCOPE_SUB - searches the base DN and all entries /// within its subtree</li> /// </ul> /// </param> /// <param name="filter"> The search filter specifying the search criteria. /// /// </param> /// <param name="attrs"> The names of attributes to retrieve. /// operation exceeds the time limit. /// /// </param> /// <param name="dereference">Specifies when aliases should be dereferenced. /// Must be one of the constants defined in /// LdapConstraints, which are DEREF_NEVER, /// DEREF_FINDING, DEREF_SEARCHING, or DEREF_ALWAYS. /// /// </param> /// <param name="maxResults">The maximum number of search results to return /// for a search request. /// The search operation will be terminated by the server /// with an LdapException.SIZE_LIMIT_EXCEEDED if the /// number of results exceed the maximum. /// /// </param> /// <param name="serverTimeLimit">The maximum time in seconds that the server /// should spend returning search results. This is a /// server-enforced limit. A value of 0 means /// no time limit. /// /// </param> /// <param name="typesOnly"> If true, returns the names but not the values of /// the attributes found. If false, returns the /// names and values for attributes found. /// /// </param> /// <param name="cont"> Any controls that apply to the search request. /// or null if none. /// /// </param> /// <seealso cref="Novell.Directory.Ldap.LdapConnection.Search"> /// </seealso> /// <seealso cref="Novell.Directory.Ldap.LdapSearchConstraints"> /// </seealso> public LdapSearchRequest(string base_Renamed, int scope, string filter, string[] attrs, int dereference, int maxResults, int serverTimeLimit, bool typesOnly, LdapControl[] cont) : base(SEARCH_REQUEST, new RfcSearchRequest(new RfcLdapDN(base_Renamed), new Asn1Enumerated(scope), new Asn1Enumerated(dereference), new Asn1Integer(maxResults), new Asn1Integer(serverTimeLimit), new Asn1Boolean(typesOnly), new RfcFilter(filter), new RfcAttributeDescriptionList(attrs)), cont) { } /// <summary> Constructs an Ldap Search Request with a filter in Asn1 format. /// /// </summary> /// <param name="base"> The base distinguished name to search from. /// /// </param> /// <param name="scope"> The scope of the entries to search. The following /// are the valid options: /// <ul> /// <li>SCOPE_BASE - searches only the base DN</li> /// /// <li>SCOPE_ONE - searches only entries under the base DN</li> /// /// <li>SCOPE_SUB - searches the base DN and all entries /// within its subtree</li> /// </ul> /// </param> /// <param name="filter"> The search filter specifying the search criteria. /// /// </param> /// <param name="attrs"> The names of attributes to retrieve. /// operation exceeds the time limit. /// /// </param> /// <param name="dereference">Specifies when aliases should be dereferenced. /// Must be either one of the constants defined in /// LdapConstraints, which are DEREF_NEVER, /// DEREF_FINDING, DEREF_SEARCHING, or DEREF_ALWAYS. /// /// </param> /// <param name="maxResults">The maximum number of search results to return /// for a search request. /// The search operation will be terminated by the server /// with an LdapException.SIZE_LIMIT_EXCEEDED if the /// number of results exceed the maximum. /// /// </param> /// <param name="serverTimeLimit">The maximum time in seconds that the server /// should spend returning search results. This is a /// server-enforced limit. A value of 0 means /// no time limit. /// /// </param> /// <param name="typesOnly"> If true, returns the names but not the values of /// the attributes found. If false, returns the /// names and values for attributes found. /// /// </param> /// <param name="cont"> Any controls that apply to the search request. /// or null if none. /// /// </param> /// <seealso cref="Novell.Directory.Ldap.LdapConnection.Search"> /// </seealso> /// <seealso cref="Novell.Directory.Ldap.LdapSearchConstraints"> /// </seealso> public LdapSearchRequest(string base_Renamed, int scope, RfcFilter filter, string[] attrs, int dereference, int maxResults, int serverTimeLimit, bool typesOnly, LdapControl[] cont) : base(SEARCH_REQUEST, new RfcSearchRequest(new RfcLdapDN(base_Renamed), new Asn1Enumerated(scope), new Asn1Enumerated(dereference), new Asn1Integer(maxResults), new Asn1Integer(serverTimeLimit), new Asn1Boolean(typesOnly), filter, new RfcAttributeDescriptionList(attrs)), cont) { } } }
using System.IO; using System.Linq; using LibGit2Sharp.Tests.TestHelpers; using Xunit; using Xunit.Extensions; using System; namespace LibGit2Sharp.Tests { public class RevertFixture : BaseFixture { [Fact] public void CanRevert() { // The branch name to perform the revert on, // and the file whose contents we expect to be reverted. const string revertBranchName = "refs/heads/revert"; const string revertedFile = "a.txt"; string path = CloneRevertTestRepo(); using (var repo = new Repository(path)) { // Checkout the revert branch. Branch branch = repo.Checkout(revertBranchName); Assert.NotNull(branch); // Revert tip commit. RevertResult result = repo.Revert(repo.Head.Tip, Constants.Signature); Assert.NotNull(result); Assert.Equal(RevertStatus.Reverted, result.Status); // Verify commit was made. Assert.NotNull(result.Commit); // Verify the expected commit ID. Assert.Equal("04746060fa753c9970d88a0b59151d7b212ac903", result.Commit.Id.Sha); // Verify workspace is clean. Assert.True(repo.Index.IsFullyMerged); Assert.False(repo.Index.RetrieveStatus().IsDirty); // Lookup the blob containing the expected reverted content of a.txt. Blob expectedBlob = repo.Lookup<Blob>("bc90ea420cf6c5ae3db7dcdffa0d79df567f219b"); Assert.NotNull(expectedBlob); // Verify contents of Index. IndexEntry revertedIndexEntry = repo.Index[revertedFile]; Assert.NotNull(revertedIndexEntry); // Verify the contents of the index. Assert.Equal(expectedBlob.Id, revertedIndexEntry.Id); // Verify contents of workspace. string fullPath = Path.Combine(repo.Info.WorkingDirectory, revertedFile); Assert.Equal(expectedBlob.GetContentText(new FilteringOptions(revertedFile)), File.ReadAllText(fullPath)); } } [Fact] public void CanRevertAndNotCommit() { // The branch name to perform the revert on, // and the file whose contents we expect to be reverted. const string revertBranchName = "refs/heads/revert"; const string revertedFile = "a.txt"; string path = CloneRevertTestRepo(); using (var repo = new Repository(path)) { string modifiedFileFullPath = Path.Combine(repo.Info.WorkingDirectory, revertedFile); // Checkout the revert branch. Branch branch = repo.Checkout(revertBranchName); Assert.NotNull(branch); // Revert tip commit. RevertResult result = repo.Revert(repo.Head.Tip, Constants.Signature, new RevertOptions() { CommitOnSuccess = false }); Assert.NotNull(result); Assert.Equal(RevertStatus.Reverted, result.Status); // Verify the commit was made. Assert.Null(result.Commit); // Verify workspace is dirty. FileStatus fileStatus = repo.Index.RetrieveStatus(revertedFile); Assert.Equal(FileStatus.Staged, fileStatus); // This is the ID of the blob containing the expected content. Blob expectedBlob = repo.Lookup<Blob>("bc90ea420cf6c5ae3db7dcdffa0d79df567f219b"); Assert.NotNull(expectedBlob); // Verify contents of Index. IndexEntry revertedIndexEntry = repo.Index[revertedFile]; Assert.NotNull(revertedIndexEntry); Assert.Equal(expectedBlob.Id, revertedIndexEntry.Id); // Verify contents of workspace. string fullPath = Path.Combine(repo.Info.WorkingDirectory, revertedFile); Assert.Equal(expectedBlob.GetContentText(new FilteringOptions(revertedFile)), File.ReadAllText(fullPath)); } } [Fact] public void RevertWithConflictDoesNotCommit() { // The branch name to perform the revert on, // and the file whose contents we expect to be reverted. const string revertBranchName = "refs/heads/revert"; string path = CloneRevertTestRepo(); using (var repo = new Repository(path)) { // Checkout the revert branch. Branch branch = repo.Checkout(revertBranchName); Assert.NotNull(branch); // The commit to revert - we know that reverting this // specific commit will generate conflicts. Commit commitToRevert = repo.Lookup<Commit>("cb4f7f0eca7a0114cdafd8537332aa17de36a4e9"); Assert.NotNull(commitToRevert); // Perform the revert and verify there were conflicts. RevertResult result = repo.Revert(commitToRevert, Constants.Signature); Assert.NotNull(result); Assert.Equal(RevertStatus.Conflicts, result.Status); Assert.Null(result.Commit); // Verify there is a conflict on the expected path. Assert.False(repo.Index.IsFullyMerged); Assert.NotNull(repo.Index.Conflicts["a.txt"]); // Verify the non-conflicting paths are staged. Assert.Equal(FileStatus.Staged, repo.Index.RetrieveStatus("b.txt")); Assert.Equal(FileStatus.Staged, repo.Index.RetrieveStatus("c.txt")); } } [Theory] [InlineData(CheckoutFileConflictStrategy.Ours)] [InlineData(CheckoutFileConflictStrategy.Theirs)] public void RevertWithFileConflictStrategyOption(CheckoutFileConflictStrategy conflictStrategy) { // The branch name to perform the revert on, // and the file which we expect conflicts as result of the revert. const string revertBranchName = "refs/heads/revert"; const string conflictedFilePath = "a.txt"; string path = CloneRevertTestRepo(); using (var repo = new Repository(path)) { // Checkout the revert branch. Branch branch = repo.Checkout(revertBranchName); Assert.NotNull(branch); // Specify FileConflictStrategy. RevertOptions options = new RevertOptions() { FileConflictStrategy = conflictStrategy, }; RevertResult result = repo.Revert(repo.Head.Tip.Parents.First(), Constants.Signature, options); // Verify there is a conflict. Assert.False(repo.Index.IsFullyMerged); Conflict conflict = repo.Index.Conflicts[conflictedFilePath]; Assert.NotNull(conflict); Assert.NotNull(conflict); Assert.NotNull(conflict.Theirs); Assert.NotNull(conflict.Ours); // Get the blob containing the expected content. Blob expectedBlob = null; switch (conflictStrategy) { case CheckoutFileConflictStrategy.Theirs: expectedBlob = repo.Lookup<Blob>(conflict.Theirs.Id); break; case CheckoutFileConflictStrategy.Ours: expectedBlob = repo.Lookup<Blob>(conflict.Ours.Id); break; default: throw new Exception("Unexpected FileConflictStrategy"); } Assert.NotNull(expectedBlob); // Check the content of the file on disk matches what is expected. string expectedContent = expectedBlob.GetContentText(new FilteringOptions(conflictedFilePath)); Assert.Equal(expectedContent, File.ReadAllText(Path.Combine(repo.Info.WorkingDirectory, conflictedFilePath))); } } [Fact] public void RevertReportsCheckoutProgress() { const string revertBranchName = "refs/heads/revert"; string repoPath = CloneRevertTestRepo(); using (var repo = new Repository(repoPath)) { // Checkout the revert branch. Branch branch = repo.Checkout(revertBranchName); Assert.NotNull(branch); bool wasCalled = false; RevertOptions options = new RevertOptions() { OnCheckoutProgress = (path, completed, total) => wasCalled = true }; repo.Revert(repo.Head.Tip, Constants.Signature, options); Assert.True(wasCalled); } } [Fact] public void RevertReportsCheckoutNotification() { const string revertBranchName = "refs/heads/revert"; string repoPath = CloneRevertTestRepo(); using (var repo = new Repository(repoPath)) { // Checkout the revert branch. Branch branch = repo.Checkout(revertBranchName); Assert.NotNull(branch); bool wasCalled = false; CheckoutNotifyFlags actualNotifyFlags = CheckoutNotifyFlags.None; RevertOptions options = new RevertOptions() { OnCheckoutNotify = (path, notificationType) => { wasCalled = true; actualNotifyFlags = notificationType; return true; }, CheckoutNotifyFlags = CheckoutNotifyFlags.Updated, }; repo.Revert(repo.Head.Tip, Constants.Signature, options); Assert.True(wasCalled); } } [Theory] [InlineData(null)] [InlineData(true)] [InlineData(false)] public void RevertFindsRenames(bool? findRenames) { // The environment is set up such that: // - file d.txt is edited in the commit that is to be reverted (commit A) // - file d.txt is renamed to d_renamed.txt // - commit A is reverted. // If rename detection is enabled, then the revert is applied // to d_renamed.txt. If rename detection is not enabled, // then the revert results in a conflict. const string revertBranchName = "refs/heads/revert_rename"; const string commitIdToRevert = "ca3e813"; const string expectedBlobId = "0ff3bbb9c8bba2291654cd64067fa417ff54c508"; const string modifiedFilePath = "d_renamed.txt"; string repoPath = CloneRevertTestRepo(); using (var repo = new Repository(repoPath)) { Branch currentBranch = repo.Checkout(revertBranchName); Assert.NotNull(currentBranch); Commit commitToRevert = repo.Lookup<Commit>(commitIdToRevert); Assert.NotNull(currentBranch); RevertOptions options; if (findRenames.HasValue) { options = new RevertOptions() { FindRenames = findRenames.Value, }; } else { options = new RevertOptions(); } RevertResult result = repo.Revert(commitToRevert, Constants.Signature, options); Assert.NotNull(result); if(!findRenames.HasValue || findRenames.Value == true) { Assert.Equal(RevertStatus.Reverted, result.Status); Assert.NotNull(result.Commit); Blob expectedBlob = repo.Lookup<Blob>(expectedBlobId); Assert.NotNull(expectedBlob); GitObject blob = result.Commit.Tree[modifiedFilePath].Target as Blob; Assert.NotNull(blob); Assert.Equal(blob.Id, expectedBlob.Id); // Verify contents of workspace string fullPath = Path.Combine(repo.Info.WorkingDirectory, modifiedFilePath); Assert.Equal(expectedBlob.GetContentText(new FilteringOptions(modifiedFilePath)), File.ReadAllText(fullPath)); } else { Assert.Equal(RevertStatus.Conflicts, result.Status); Assert.Null(result.Commit); } } } [Theory] [InlineData(1, "a04ef5f22c2413a9743046436c0e5354ed903f78")] [InlineData(2, "1ae0cd88802bb4f4e6413ba63e41376d235b6fd0")] public void CanRevertMergeCommit(int mainline, string expectedId) { const string revertBranchName = "refs/heads/revert_merge"; const string commitIdToRevert = "2747045"; string repoPath = CloneRevertTestRepo(); using (var repo = new Repository(repoPath)) { Branch branch = repo.Checkout(revertBranchName); Assert.NotNull(branch); Commit commitToRevert = repo.Lookup<Commit>(commitIdToRevert); Assert.NotNull(commitToRevert); RevertOptions options = new RevertOptions() { Mainline = mainline, }; RevertResult result = repo.Revert(commitToRevert, Constants.Signature, options); Assert.NotNull(result); Assert.Equal(RevertStatus.Reverted, result.Status); Assert.Equal(result.Commit.Sha, expectedId); if(mainline == 1) { // In this case, we expect "d_renamed.txt" to be reverted (deleted), // and a.txt to match the tip of the "revert" branch. Assert.Equal(FileStatus.Nonexistent, repo.Index.RetrieveStatus("d_renamed.txt")); // This is the commit containing the expected contents of a.txt. Commit commit = repo.Lookup<Commit>("b6fbb29b625aabe0fb5736da6fd61d4147e4405e"); Assert.NotNull(commit); Assert.Equal(commit["a.txt"].Target.Id, repo.Index["a.txt"].Id); } else if(mainline == 2) { // In this case, we expect "d_renamed.txt" to be preset, // and a.txt to match the tip of the master branch. // In this case, we expect "d_renamed.txt" to be reverted (deleted), // and a.txt to match the tip of the "revert" branch. Assert.Equal(FileStatus.Unaltered, repo.Index.RetrieveStatus("d_renamed.txt")); // This is the commit containing the expected contents of "d_renamed.txt". Commit commit = repo.Lookup<Commit>("c4b5cea70e4cd5b633ed0f10ae0ed5384e8190d8"); Assert.NotNull(commit); Assert.Equal(commit["d_renamed.txt"].Target.Id, repo.Index["d_renamed.txt"].Id); // This is the commit containing the expected contents of a.txt. commit = repo.Lookup<Commit>("cb4f7f0eca7a0114cdafd8537332aa17de36a4e9"); Assert.NotNull(commit); Assert.Equal(commit["a.txt"].Target.Id, repo.Index["a.txt"].Id); } } } [Fact] public void CanNotRevertAMergeCommitWithoutSpecifyingTheMainlineBranch() { const string revertBranchName = "refs/heads/revert_merge"; const string commitIdToRevert = "2747045"; string repoPath = CloneRevertTestRepo(); using (var repo = new Repository(repoPath)) { Branch branch = repo.Checkout(revertBranchName); Assert.NotNull(branch); var commitToRevert = repo.Lookup<Commit>(commitIdToRevert); Assert.NotNull(commitToRevert); Assert.Throws<LibGit2SharpException>(() => repo.Revert(commitToRevert, Constants.Signature)); } } [Theory] [InlineData(true)] [InlineData(false)] public void RevertWithNothingToRevert(bool commitOnSuccess) { // The branch name to perform the revert on const string revertBranchName = "refs/heads/revert"; string path = CloneRevertTestRepo(); using (var repo = new Repository(path)) { // Checkout the revert branch. Branch branch = repo.Checkout(revertBranchName); Assert.NotNull(branch); Commit commitToRevert = repo.Head.Tip; // Revert tip commit. RevertResult result = repo.Revert(commitToRevert, Constants.Signature); Assert.NotNull(result); Assert.Equal(RevertStatus.Reverted, result.Status); // Revert the same commit a second time result = repo.Revert( commitToRevert, Constants.Signature, new RevertOptions() { CommitOnSuccess = commitOnSuccess }); Assert.NotNull(result); Assert.Equal(null, result.Commit); Assert.Equal(RevertStatus.NothingToRevert, result.Status); if (commitOnSuccess) { Assert.Equal(CurrentOperation.None, repo.Info.CurrentOperation); } else { Assert.Equal(CurrentOperation.Revert, repo.Info.CurrentOperation); } } } [Fact] public void RevertOrphanedBranchThrows() { // The branch name to perform the revert on const string revertBranchName = "refs/heads/revert"; string path = CloneRevertTestRepo(); using (var repo = new Repository(path)) { // Checkout the revert branch. Branch branch = repo.Checkout(revertBranchName); Assert.NotNull(branch); Commit commitToRevert = repo.Head.Tip; // Move the HEAD to an orphaned branch. repo.Refs.UpdateTarget("HEAD", "refs/heads/orphan"); Assert.True(repo.Info.IsHeadUnborn); // Revert the tip of the refs/heads/revert branch. Assert.Throws<UnbornBranchException>(() => repo.Revert(commitToRevert, Constants.Signature)); } } } } /* This is extra325 */
/*============================================================================ * AUTHOR: Eric G. Miller * DATE: 2004-09-15 * PURPOSE: * Provide both high-level and low-level interfaces to the PROJ.4 * projection library. This interface was written against a slightly * modified copy of version 4.4.8. Any significant changes were sent to * upstream for incorporation into later versions. * COPYRIGHT: Copyright (c) 2004, 2010 California Department of Fish and Game * LICENSE: MIT Style * 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. * * CHANGES: * For 4.7.0 (2010-01-29, Eric G. Miller) * - Change definition of pj_alloc and pj_dalloc to work with IntPtr's * - Change return values of pj_get_def, pj_strerrno, pj_release to * IntPtr's. Use Marshal.PtrToStringAnsi. Free the IntPtr from pj_get_def * using either pj_dalloc or Marshal.FreeHGlobal. The results from * the other two functions should not be released (static data). * - Add GetErrorMessage and GetErrno helpers to Projection class. * - Removed all unsafe code * - Implemented IDisposable on the Projection class * - Other minor modifications related to the changes noted above. *===========================================================================*/ using System; using System.Runtime.InteropServices; namespace ProjApi { /// <summary> /// Common struct for data points /// </summary> [ StructLayout(LayoutKind.Sequential) ] public struct ProjUV { public double u; public double v; } /// <summary> /// This class thinly wraps proj.4 library functions. Some of it uses /// unsafe code. /// </summary> public class Proj { /// <summary> /// Constants for converting coordinates between radians and degrees /// </summary> public const double RAD_TO_DEG = 57.29577951308232; public const double DEG_TO_RAD = .0174532925199432958; /// <summary> /// The finder function is used by the projection library to locate /// resources like datum shift files and projection configuration /// files. (NOTE: Not functional due to calling convention). /// </summary> public delegate IntPtr FinderFunction([MarshalAs(UnmanagedType.LPStr)] string path); ///// <summary> ///// Pointer to the global error number ///// </summary> //public unsafe static int* pj_errno = pj_get_errno_ref(); /// <summary> /// Perform a forward projection (from lat/long). /// </summary> /// <param name="LP">The lat/long coordinate in radians</param> /// <param name="projPJ">The projection definition</param> /// <returns>The projected coordinate in system units</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern ProjUV pj_fwd(ProjUV LP, IntPtr projPJ); /// <summary> /// Perform an inverse projection (to lat/long). /// </summary> /// <param name="XY">The projected coordinate in system units</param> /// <param name="projPJ">The projection definition</param> /// <returns>The lat/long coordinate in radians</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern ProjUV pj_inv(ProjUV XY, IntPtr projPJ); /// <summary> /// Transform a set of coordinates from one system to another (includes datum transformation) /// </summary> /// <param name="src">Source coordinate system</param> /// <param name="dst">Destination coordinate system</param> /// <param name="point_count">Number of points in the arrays</param> /// <param name="point_offset">Offset to use when iterating through array. Use "1" for /// normal arrays or use "2" or "3" when using a single array for all of the x, y /// and [optional] z elements.</param> /// <param name="x">The "X" coordinate array</param> /// <param name="y">The "Y" coordinate array</param> /// <param name="z">The "Z" coordinate array (may be null)</param> /// <returns>Zero on success, pj_errno on failure</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern int pj_transform(IntPtr src, IntPtr dst, int point_count, int point_offset, [InAttribute, OutAttribute] double[] x, [InAttribute, OutAttribute] double[] y, [InAttribute, OutAttribute] double[] z); /// <summary> /// Perform a datum transformation on the inputs. Typically you would use /// pj_transform which calls this function internally. /// </summary> /// <param name="src">Source coordinate system definition</param> /// <param name="dst">Destination coordinate system definition</param> /// <param name="point_count">Count of points in the array(s)</param> /// <param name="point_offset">Offset of each element (see pj_transform)</param> /// <param name="x">Array of "X" values</param> /// <param name="y">Array of "Y" values</param> /// <param name="z">Array of "Z" values (may be null)</param> /// <returns>Zero on success, pj_errno on failure</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern int pj_datum_transform(IntPtr src, IntPtr dst, int point_count, int point_offset, [InAttribute, OutAttribute] double[] x, [InAttribute, OutAttribute] double[] y, [InAttribute, OutAttribute] double[] z); /// <summary> /// Convert geocentric coordinates to geodetic. /// </summary> /// <param name="a">Ellipsoid semi-major axis</param> /// <param name="es">Square of ellipsoid eccentricity</param> /// <param name="point_count">Count of points in array(s)</param> /// <param name="point_offset">Offset of each element in array(s) (see pj_transform)</param> /// <param name="x">Array of "X" values</param> /// <param name="y">Array of "Y" values</param> /// <param name="z">Array of "Z" values</param> /// <returns>Zero</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern int pj_geocentric_to_geodetic(double a, double es, int point_count, int point_offset, [InAttribute, OutAttribute] double[] x, [InAttribute, OutAttribute] double[] y, [InAttribute, OutAttribute] double[] z); /// <summary> /// Convert geodetic coordinates to geocentric. Called by pj_datum_transform /// if needed. /// </summary> /// <param name="a">Ellipsoid semi-major axis</param> /// <param name="es">Square of ellipsoid eccentricity</param> /// <param name="point_count">Count of points in array(s)</param> /// <param name="point_offset">Offset of each element in array(s) (see pj_transform)</param> /// <param name="x">Array of "X" values</param> /// <param name="y">Array of "Y" values</param> /// <param name="z">Array of "Z" values</param> /// <returns>Zero</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern int pj_geodetic_to_geocentric(double a, double es, int point_count, int point_offset, [InAttribute, OutAttribute] double[] x, [InAttribute, OutAttribute] double[] y, [InAttribute, OutAttribute] double[] z); /// <summary> /// Compare the datum definitions in two coordinate system definitions /// for equality. /// </summary> /// <param name="srcdefn">Source coordinate system</param> /// <param name="dstdefn">Destination coordinate system</param> /// <returns>One if true, Zero if false</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern int pj_compare_datums(IntPtr srcdefn, IntPtr dstdefn ); /// <summary> /// Apply a gridshift datum transformation on the inputs /// </summary> /// <param name="nadgrids">name of the gridshift file</param> /// <param name="inverse">flag whether shifting to or from</param> /// <param name="point_count">Count of points in the array(s)</param> /// <param name="point_offset">Offset of each element (see pj_transform)</param> /// <param name="x">Array of "X" values</param> /// <param name="y">Array of "Y" values</param> /// <param name="z">Array of "Z" values (may be null)</param> /// <returns>Zero on success, pj_errno on failure</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern int pj_apply_gridshift([MarshalAs(UnmanagedType.LPStr)] string nadgrids, int inverse, int point_count, int point_offset, [InAttribute, OutAttribute] double[] x, [InAttribute, OutAttribute] double[] y, [InAttribute, OutAttribute] double[] z); /// <summary> /// Free up any loaded datum grids from memory. /// </summary> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern void pj_deallocate_grids(); /// <summary> /// Is the coordinate system definition lat/long ? /// </summary> /// <param name="projPJ">Coordinate system definition</param> /// <returns>One if true, Zero if false</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern int pj_is_latlong(IntPtr projPJ); /// <summary> /// Is the coordinate system definition geocentric? /// </summary> /// <param name="projPJ">Coordinate system definition</param> /// <returns>One if true, Zero if false</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern int pj_is_geocent(IntPtr projPJ); /// <summary> /// Print the coordinate system definition to stdout. /// </summary> /// <param name="projPJ">The coordinate system definition</param> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern void pj_pr_list(IntPtr projPJ); /// <summary> /// Frees the memory allocated for a projection definition. /// Attempting to use the object after calling this function or attempting /// to call this function more than once with the same object will cause /// your application to blow up. /// </summary> /// <param name="projPJ">Opaque pointer to a projection definition (null is okay)</param> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] //public unsafe static extern void pj_free(void* projPJ); public static extern void pj_free(IntPtr projPJ); /// <summary> /// Install a custom function to locate resource files. Once installed, the /// library will use this until uninstalled (set to null), so make sure the /// delegate variable is not garbage collected without "uninstalling" the /// function first. (NOTE: Not useable due to calling convention) /// </summary> /// <param name="f">The function delegate</param> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern void pj_set_finder( [MarshalAs(UnmanagedType.FunctionPtr)] FinderFunction f); /// <summary> /// Initialize a coordinate system definition like a "C" style main function /// loop. /// </summary> /// <param name="argc">Count of elements in argv</param> /// <param name="argv">Array of string parameters</param> /// <returns>Opaque pointer to a coordinate system definition, or null on failure.</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern IntPtr pj_init(int argc, [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr, SizeParamIndex=1)] string[] argv); /// <summary> /// Initialize a projection definition object from a string of arguments /// </summary> /// <param name="pjstr">The string of projection arguments</param> /// <returns>Opaque pointer to a projection definition or null on failure</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern IntPtr pj_init_plus( [MarshalAs(UnmanagedType.LPStr)] string pjstr); /// <summary> /// Get a string representation of the coordinate system definition /// </summary> /// <param name="projPJ">The coordinate system definition</param> /// <param name="options">Unused</param> /// <returns>A string representing the coordinate system definition</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern IntPtr pj_get_def(IntPtr projPJ, int options); /// <summary> /// Return a coordinate system definition defining the lat/long coordinate */ /// system on which a projection is based. If the coordinate /// system passed in is latlong, a clone of the same will be returned. /// </summary> /// <param name="projPJ">The source coordinate system definition</param> /// <returns>The lat/long coordinate system definition</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern IntPtr pj_latlong_from_proj(IntPtr projPJ); /// <summary> /// Allocate a chunk of memory using malloc. /// </summary> /// <param name="size">The size of the memory chunk to allocate</param> /// <returns>A pointer to the allocated memory, or null on failure.</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern IntPtr pj_malloc(uint size); /// <summary> /// Deallocate a chunk of memory previously allocated with pj_alloc (malloc). /// </summary> /// <param name="memory">The pointer to the chunk of memory to free.</param> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern void pj_dalloc(IntPtr memory); /// <summary> /// Get the string value corresponding to the error number. /// </summary> /// <param name="errno">The error number</param> /// <returns>The error message</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern IntPtr pj_strerrno(int errno); /// <summary> /// Get a pointer to the int holding the last error number /// </summary> /// <returns>pointer to the error number variable</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern IntPtr pj_get_errno_ref(); /// <summary> /// Get the PROJ.4 library release string /// </summary> /// <returns>string containing library release version</returns> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern IntPtr pj_get_release(); /// <summary> /// Specifies directories in which the projection library should look for /// resource files. /// </summary> /// <param name="count">number of elements in the array</param> /// <param name="path">array of strings specifying directories to look for files in.</param> [DllImport("proj.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] public static extern void pj_set_searchpath(int count, string[] path ); } /// <summary> /// This class is a thicker interface to the PROJ.4 library. It exposes a small /// set of methods, but generally these are all that is needed. /// </summary> public class Projection : IDisposable { // INTERNAL data /// <summary> /// The pointer to the projection definition object /// </summary> internal IntPtr prj = IntPtr.Zero; /// <summary> /// Cache of the definition string returned by pj_get_def /// </summary> internal string out_def = null; /// <summary> /// Common object initialization function /// </summary> /// <param name="definition">The projection definition string</param> /// <exception cref="System.ArgumentException">Thrown when initialization fails. /// The reason may vary and will be documented in the Message</exception> private void Initialize(string definition) { IntPtr thePrj = Proj.pj_init_plus(definition); if (thePrj == IntPtr.Zero) { string message = GetErrorMessage(GetErrNo()); throw new System.ArgumentException(message); } this.prj = thePrj; this.out_def = null; } /// <summary> /// Read the current pj_errno value. /// </summary> /// <returns>The current pj_errno value.</returns> public static int GetErrNo() { int errno = 0; IntPtr pErrNo = Proj.pj_get_errno_ref(); errno = Marshal.ReadInt32(pErrNo); return errno; } /// <summary> /// Get the error message corresponding to /// the errno /// </summary> /// <param name="errno">The error number</param> /// <returns>The message, or null if errno == 0</returns> public static string GetErrorMessage(int errno) { if (errno == 0) return null; IntPtr pMsg = Proj.pj_strerrno(errno); return Marshal.PtrToStringAnsi(pMsg); } /// <summary> /// Instance version checks initialization status. /// </summary> private void CheckInitialized() { Projection.CheckInitialized(this); } /// <summary> /// Static version that checks initialization status. /// </summary> /// <param name="p">The projection object</param> private static void CheckInitialized(Projection p) { if (p.prj == IntPtr.Zero) { throw new ApplicationException("Projection not initialized"); } } /// <summary> /// The default constructor /// </summary> public Projection() {} /// <summary> /// Constructor with a definition /// </summary> /// <param name="paramaters">string defining the coordinate system</param> public Projection(string definition) : base() { this.Initialize(definition); } // PROPERTIES /// <summary> /// A string representing the coordinate system. Setting it [re]initializes the /// projection definition. /// </summary> /// <exception cref="System.ArgumentException">Thrown when initialization fails (set). /// The reason may vary and will be documented in the Message</exception> /// <exception cref="System.ApplicationException">Thrown when the projection is /// not initialized (get).</exception> public string Definition { set { this.Initialize(value); } get { this.CheckInitialized(); if (this.out_def == null) { IntPtr pDef = Proj.pj_get_def(this.prj, 0); this.out_def = Marshal.PtrToStringAnsi(pDef); Proj.pj_dalloc(pDef); } return this.out_def; } } /// <summary> /// Returns true if the projection definition is Lat/Long. /// </summary> /// <exception cref="System.ApplicationException">Thrown when the projection is /// not initialized (get).</exception> public bool IsLatLong { get { this.CheckInitialized(); return (Proj.pj_is_latlong(this.prj) == 0) ? false : true; } } /// <summary> /// Returns true if the projection definition is Geocentric (XYZ) /// </summary> /// <exception cref="System.ApplicationException">Thrown when the projection is /// not initialized (get).</exception> public bool IsGeoCentric { get { this.CheckInitialized(); return (Proj.pj_is_geocent(this.prj) == 0) ? false : true; } } // METHODS /// <summary> /// Get a projection object with the underlying /// Lat/Long definition /// </summary> /// <returns>Projection</returns> /// <exception cref="System.ApplicationException">Thrown when the projection is /// not initialized.</exception> /// <exception cref="System.ArgumentException">Thrown when the underlying library /// does not return a valid Lat/Long projection object. This might happen if the /// original projection does not have an underlying Lat/Long coordinate system. /// </exception> public Projection GetLatLong() { this.CheckInitialized(); Projection new_prj = new Projection(); new_prj.prj = Proj.pj_latlong_from_proj(this.prj); if (new_prj.prj == IntPtr.Zero) { string message = GetErrorMessage(GetErrNo()); throw new System.ArgumentException(message); } return new_prj; } /// <summary> /// Returns the projection definition string (Same as .Definition property) /// </summary> /// <returns>Projection definition string</returns> /// <exception cref="System.ApplicationException">Thrown when the projection is /// not initialized.</exception> public override string ToString() { return this.Definition; } /// <summary> /// Sets search directories for the PROJ.4 library to look for its resource /// files (such as datum grid files, state plane files, etc...). Search /// paths are only used if other means fail (default install directory, PROJ_LIB /// environment variable, installed callback, current directory). Therefore, /// do not expect the search path to override the other methods of specifying /// the location of resource files. /// </summary> /// <param name="path">An array of strings specifying directories to look for /// files in.</param> public static void SetSearchPath(string[] path) { if (path != null && path.Length > 0) Proj.pj_set_searchpath(path.Length, path); } /// <summary> /// Transform coordinates from one projection system to another /// </summary> /// <param name="dst">The destination projection</param> /// <param name="x">The "X" coordinate values.</param> /// <param name="y">The "Y" coordinate values.</param> /// <exception cref="System.ApplicationException">Thrown when the projection is /// not initialized or the transformation failed. The message will indicate the error. /// </exception> /// <exception cref="System.ArgumentException"> /// May be thrown for any of the following reasons: /// <list type="bullet"> /// <item>The "x" array is null</item> /// <item>The "y" array is null</item> /// <item>The length of the x and y arrays don't match</item> /// </list> /// </exception> public void Transform (Projection dst, double[] x, double[] y) { this.Transform(dst, x, y, null); } /// <summary> /// Transform coordinates from one projection system to another /// </summary> /// <param name="dst">The destination projection</param> /// <param name="x">The "X" coordinate values.</param> /// <param name="y">The "Y" coordinate values.</param> /// <param name="z">The "Z" coordinate values.</param> /// <exception cref="System.ApplicationException">Thrown when the projection is /// not initialized or the transformation failed. The message will indicate the error. /// </exception> /// <exception cref="System.ArgumentException"> /// May be thrown for any of the following reasons: /// <list type="bullet"> /// <item>The "x" array is null</item> /// <item>The "y" array is null</item> /// <item>The length of the x, y and z (if not null) arrays don't match</item> /// </list> /// </exception> public void Transform (Projection dst, double[] x, double[] y, double[] z) { Projection.Transform(this, dst, x, y, z); } /// <summary> /// Transform coordinates from one projection system to another /// </summary> /// <param name="src">The source projection</param> /// <param name="dst">The destination projection</param> /// <param name="x">The "X" coordinate values.</param> /// <param name="y">The "Y" coordinate values.</param> /// <exception cref="System.ApplicationException">Thrown when the projection is /// not initialized or the transformation failed. The message will indicate the error. /// </exception> /// <exception cref="System.ArgumentException"> /// May be thrown for any of the following reasons: /// <list type="bullet"> /// <item>The "x" array is null</item> /// <item>The "y" array is null</item> /// <item>The length of the x and y arrays don't match</item> /// </list> /// </exception> public static void Transform (Projection src, Projection dst, double[] x, double[] y) { Projection.Transform(src, dst, x, y, null); } /// <summary> /// Transform coordinates from one projection system to another /// </summary> /// <param name="src">The source projection</param> /// <param name="dst">The destination projection</param> /// <param name="x">The "X" coordinate values.</param> /// <param name="y">The "Y" coordinate values.</param> /// <param name="z">The "Z" coordinate values.</param> /// <exception cref="System.ApplicationException">Thrown when the projection is /// not initialized or the transformation failed. The message will indicate the error. /// </exception> /// <exception cref="System.ArgumentException"> /// May be thrown for any of the following reasons: /// <list type="bullet"> /// <item>The "x" array is null</item> /// <item>The "y" array is null</item> /// <item>The length of the x, y and z (if not null) arrays don't match</item> /// </list> /// </exception> public static void Transform (Projection src, Projection dst, double[] x, double[] y, double[] z) { Projection.CheckInitialized(src); Projection.CheckInitialized(dst); if (x == null) { throw new ArgumentException("Argument is required", "x"); } if (y == null) { throw new ArgumentException("Argument is required", "y"); } if (x.Length != y.Length || (z != null && z.Length != x.Length)) { throw new ArgumentException("Coordinate arrays must have the same length"); } if (src.IsLatLong) { for (int i = 0; i < x.Length; i++) { x[i] *= Proj.DEG_TO_RAD; y[i] *= Proj.DEG_TO_RAD; } } int result = Proj.pj_transform(src.prj, dst.prj, x.Length, 1, x, y, z); if (result != 0) { string message = "Tranformation Error"; int errno = GetErrNo(); if (errno != 0) message = Projection.GetErrorMessage(errno); throw new ApplicationException(message); } if (dst.IsLatLong) { for (int i = 0; i < x.Length; i++) { x[i] *= Proj.RAD_TO_DEG; y[i] *= Proj.RAD_TO_DEG; } } } #region IDisposable Members public void Dispose() { if (this.prj != IntPtr.Zero) Proj.pj_free(this.prj); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor01.cnstrctor01 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a constructor with OP</Description> // <Expects status=success></Expects> // <Code> public class Parent { public Parent(dynamic i = null) { } public dynamic Foo() { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor01a.cnstrctor01a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a constructor with OP</Description> // <Expects status=success></Expects> // <Code> public class Parent { public Parent(dynamic i = default(object)) { } public int Foo() { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int? a = null; Parent p = new Parent(a); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor02.cnstrctor02 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a constructor with OP</Description> // <Expects status=success></Expects> // <Code> public class Parent { public Parent(dynamic i = default(dynamic), dynamic j = null) { } public int Foo() { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor04.cnstrctor04 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a constructor with OP</Description> // <Expects status=success></Expects> // <Code> public class Parent { public Parent(dynamic i, int j = 1) { } public int Foo() { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(i: 1); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.cnstrctor04a.cnstrctor04a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a constructor with OP</Description> // <Expects status=success></Expects> // <Code> public class Parent { public Parent(dynamic i, int j = 1) { } public int Foo() { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic i = 1; dynamic p = new Parent(i, j: i); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl01.decl01 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic x = null, dynamic y = null) { if (x == null && y == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl01a.decl01a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? x = 2, int? y = 1) { if (x == null && y == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic x = default(int?); dynamic p = new Parent(); return p.Foo(x); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl03a.decl03a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic x, int? y = 1) { if (x == 2 && y == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int? x = 2; Parent p = new Parent(); return p.Foo(x); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl05.decl05 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. multiple optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int z, dynamic x = default(dynamic), dynamic y = default(object)) { if (z == 1 && x == null && y == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(1); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl05a.decl05a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. multiple optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? z, int x = 2, int y = 1) { if (z == 1 && x == 2 && y == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic z = 1; Parent p = new Parent(); return p.Foo(z); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl06a.decl06a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. Expressions used</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? z = 1 + 1) { if (z == 2) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl07a.decl07a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. Max int</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? z = 2147483647) { if (z == 2147483647) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl09a.decl09a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(long? z = (long)1) { if (z == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl12.decl12 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public class Parent { public int Foo( [Optional] dynamic i) { if (i == System.Type.Missing) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl12a.decl12a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public class Parent { public int Foo( [Optional] int ? i) { if (i == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl13.decl13 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional params specified via opt attribute</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public class Parent { public int Foo( [Optional] dynamic i, [Optional] dynamic j, [Optional] dynamic f, [Optional] dynamic d) { if (d == System.Type.Missing) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl13a.decl13a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional params specified via opt attribute</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public class Parent { public int Foo( [Optional] int ? i, [Optional] long ? j, [Optional] float ? f, [Optional] decimal ? d) { if (d == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl14a.decl14a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent { private const int x = 1; public int Foo(int? z = x) { if (z == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl16a.decl16a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent { private const int x = 1; public int Foo(bool? z = true) { if (z.Value) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl16b.decl16b { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent { private const int x = 1; public int Foo(bool z = true) { if (z) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl18a.decl18a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent { private const string x = "test"; public int Foo(string z = x) { if (z == "test") return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl19a.decl19a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent { private const bool x = true; public int Foo(bool? z = x) { if ((bool)z) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.decl20a.decl20a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(string z = "test", int? y = 3) { if (z == "test" && y == 3) return 1; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); try { p.Foo(3, "test"); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Parent.Foo(string, int?)"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.generic01.generic01 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent<T> where T : class { public int Foo(T t = null) { if (t == null) return 0; return 1; } } public class Foo { } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent<Foo>(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.generic02.generic02 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public class Parent<T> { public int Foo(T t = default(T)) { if (t == null) return 0; return 1; } } public class Foo { } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent<Foo>(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer02.indexer02 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[dynamic index = null, dynamic index2 = default(dynamic)] { get { return index2 ?? 1 - index; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p[1]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer02a.indexer02a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[int? index = 1, int? index2 = 1] { get { return (int)index2 - 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = 1; return p[d]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer03a.indexer03a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[int? index = 1, long? index2 = 1] { get { return (int)(index2 - 1); } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = 1; return p[d]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer05.indexer05 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[int index = 1, dynamic index2 = null] { get { return index2 == null ? 0 : 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p[1]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer05a.indexer05a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[int? index = 1, string index2 = "test"] { get { return index2 == "test" ? 0 : 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p[d]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer06a.indexer06a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public struct S { public int x; } public class Parent { public int this[int? index = 1, S s = default(S)] { get { return s.x == 0 ? 0 : 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p[d]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer07a.indexer07a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class S { } public class Parent { public int this[int? index = 1, S s = null] { get { return s == null ? 0 : 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p[d]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer08.indexer08 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[dynamic index = null, int? s = null] { get { return s == null ? 0 : 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p[1]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer08a.indexer08a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[int? index = 1, int? s = null] { get { return s == null ? 0 : 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p[d]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.indexer09a.indexer09a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an indexer with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int this[int? index = 1, int? s = 0] { get { return s == 0 ? 0 : 1; } set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p[d]; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms02.prms02 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Optional before params should be allowed</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic x = default(dynamic), params object[] array) { if (x == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms02a.prms02a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Optional before params should be allowed</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? x = 2, params object[] array) { if (x == 2) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms08.prms08 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic x = null, params dynamic[] array) { x = 2; if (x == 2) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms08a.prms08a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? x = 2, params object[] array) { x = 2; if (x == 2) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms09.prms09 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic x = null, params dynamic[] array) { if (x == 1 && array.Length == 3) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(1, 2, 3, 4); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms09a.prms09a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? x = 2, params object[] array) { x = 2; if (array == null) return 1; return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d1 = 1; dynamic d2 = 2; dynamic d3 = 3; dynamic d4 = 4; dynamic p = new Parent(); return p.Foo(d1, d2, d3, d4); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms10a.prms10a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? x = 2, params object[] array) { x = 2; if (x == 2) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p.Foo(d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms11.prms11 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(params dynamic[] array) { if (array.Length == 0) return 1; return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(1); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms11a.prms11a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(params object[] array) { if (array.Length == 0) return 1; return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p.Foo(d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms12.prms12 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic x = null, params dynamic[] array) { if (x == 1 && (array == null || array.Length == 0)) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(1); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.declaration.prms12a.prms12a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters // Params can't be defaulted</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int? x = 2, params object[] array) { x = 2; if (array == null) return 1; return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = 1; dynamic p = new Parent(); return p.Foo(d); } } //</Code> }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Gaming.V1Beta.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedGameServerConfigsServiceClientTest { [xunit::FactAttribute] public void GetGameServerConfigRequestObject() { moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient> mockGrpcClient = new moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerConfigRequest request = new GetGameServerConfigRequest { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), }; GameServerConfig expectedResponse = new GameServerConfig { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, FleetConfigs = { new FleetConfig(), }, ScalingConfigs = { new ScalingConfig(), }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetGameServerConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GameServerConfigsServiceClient client = new GameServerConfigsServiceClientImpl(mockGrpcClient.Object, null); GameServerConfig response = client.GetGameServerConfig(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGameServerConfigRequestObjectAsync() { moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient> mockGrpcClient = new moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerConfigRequest request = new GetGameServerConfigRequest { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), }; GameServerConfig expectedResponse = new GameServerConfig { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, FleetConfigs = { new FleetConfig(), }, ScalingConfigs = { new ScalingConfig(), }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetGameServerConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GameServerConfigsServiceClient client = new GameServerConfigsServiceClientImpl(mockGrpcClient.Object, null); GameServerConfig responseCallSettings = await client.GetGameServerConfigAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GameServerConfig responseCancellationToken = await client.GetGameServerConfigAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetGameServerConfig() { moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient> mockGrpcClient = new moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerConfigRequest request = new GetGameServerConfigRequest { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), }; GameServerConfig expectedResponse = new GameServerConfig { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, FleetConfigs = { new FleetConfig(), }, ScalingConfigs = { new ScalingConfig(), }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetGameServerConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GameServerConfigsServiceClient client = new GameServerConfigsServiceClientImpl(mockGrpcClient.Object, null); GameServerConfig response = client.GetGameServerConfig(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGameServerConfigAsync() { moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient> mockGrpcClient = new moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerConfigRequest request = new GetGameServerConfigRequest { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), }; GameServerConfig expectedResponse = new GameServerConfig { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, FleetConfigs = { new FleetConfig(), }, ScalingConfigs = { new ScalingConfig(), }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetGameServerConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GameServerConfigsServiceClient client = new GameServerConfigsServiceClientImpl(mockGrpcClient.Object, null); GameServerConfig responseCallSettings = await client.GetGameServerConfigAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GameServerConfig responseCancellationToken = await client.GetGameServerConfigAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetGameServerConfigResourceNames() { moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient> mockGrpcClient = new moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerConfigRequest request = new GetGameServerConfigRequest { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), }; GameServerConfig expectedResponse = new GameServerConfig { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, FleetConfigs = { new FleetConfig(), }, ScalingConfigs = { new ScalingConfig(), }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetGameServerConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GameServerConfigsServiceClient client = new GameServerConfigsServiceClientImpl(mockGrpcClient.Object, null); GameServerConfig response = client.GetGameServerConfig(request.GameServerConfigName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGameServerConfigResourceNamesAsync() { moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient> mockGrpcClient = new moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerConfigRequest request = new GetGameServerConfigRequest { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), }; GameServerConfig expectedResponse = new GameServerConfig { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, FleetConfigs = { new FleetConfig(), }, ScalingConfigs = { new ScalingConfig(), }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetGameServerConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GameServerConfigsServiceClient client = new GameServerConfigsServiceClientImpl(mockGrpcClient.Object, null); GameServerConfig responseCallSettings = await client.GetGameServerConfigAsync(request.GameServerConfigName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GameServerConfig responseCancellationToken = await client.GetGameServerConfigAsync(request.GameServerConfigName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv4 { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_ARM; public abstract partial class ProcessorARMv4 : Processor { public const int c_psr_bit_T = EncDef.c_psr_bit_T; public const int c_psr_bit_F = EncDef.c_psr_bit_F; public const int c_psr_bit_I = EncDef.c_psr_bit_I; public const int c_psr_bit_V = EncDef.c_psr_bit_V; public const int c_psr_bit_C = EncDef.c_psr_bit_C; public const int c_psr_bit_Z = EncDef.c_psr_bit_Z; public const int c_psr_bit_N = EncDef.c_psr_bit_N; public const uint c_psr_T = EncDef.c_psr_T; public const uint c_psr_F = EncDef.c_psr_F; public const uint c_psr_I = EncDef.c_psr_I; public const uint c_psr_V = EncDef.c_psr_V; public const uint c_psr_C = EncDef.c_psr_C; public const uint c_psr_Z = EncDef.c_psr_Z; public const uint c_psr_N = EncDef.c_psr_N; //--// public const uint c_psr_mode = EncDef.c_psr_mode; public const uint c_psr_mode_USER = EncDef.c_psr_mode_USER; public const uint c_psr_mode_FIQ = EncDef.c_psr_mode_FIQ; public const uint c_psr_mode_IRQ = EncDef.c_psr_mode_IRQ; public const uint c_psr_mode_SVC = EncDef.c_psr_mode_SVC; public const uint c_psr_mode_ABORT = EncDef.c_psr_mode_ABORT; public const uint c_psr_mode_UNDEF = EncDef.c_psr_mode_UNDEF; public const uint c_psr_mode_SYS = EncDef.c_psr_mode_SYS; public const uint c_psr_field_c = EncDef.c_psr_field_c; public const uint c_psr_field_x = EncDef.c_psr_field_x; public const uint c_psr_field_s = EncDef.c_psr_field_s; public const uint c_psr_field_f = EncDef.c_psr_field_f; public const uint c_psr_field_ALL = EncDef.c_psr_field_ALL; //--// public const uint c_InterruptsOff = EncDef.c_psr_I; public const uint c_AllInterruptsOff = EncDef.c_psr_I | EncDef.c_psr_F; public static class MethodWrapperHelpers { [TS.WellKnownMethod( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_ScratchedRegisters" )] public static extern uint ScratchedRegisters(); [TS.WellKnownMethod( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PushRegisters" )] public static extern void PushRegisters( uint indexRegister , bool fWriteBackIndexRegister , bool fAddComputedRegisters , uint registerMask ); [TS.WellKnownMethod( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PopRegisters" )] public static extern void PopRegisters( uint indexRegister , bool fWriteBackIndexRegister , bool fAddComputedRegisters , bool fRestoreSPSR , uint registerMask ); [TS.WellKnownMethod( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PushStackFrame" )] public static extern void PushStackFrame(); [TS.WellKnownMethod( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PopStackFrame" )] public static extern void PopStackFrame(); [Inline] public static void AdjustLinkAddress( uint offset ) { ProcessorARMv4.SetRegister( EncDef.c_register_lr, AddressMath.Decrement( ProcessorARMv4.GetRegister( EncDef.c_register_lr ), offset ) ); } [Inline] public static void PushStackPointer( uint offset ) { ProcessorARMv4.SetRegister( EncDef.c_register_sp, AddressMath.Decrement( ProcessorARMv4.GetRegister( EncDef.c_register_sp ), offset ) ); } [Inline] public static void PopStackPointer( uint offset ) { ProcessorARMv4.SetRegister( EncDef.c_register_sp, AddressMath.Increment( ProcessorARMv4.GetRegister( EncDef.c_register_sp ), offset ) ); } } [TS.WellKnownType( "Microsoft_Zelig_ProcessorARMv4_MethodWrapper" )] public sealed class MethodWrapper : AbstractMethodWrapper { public const uint DisableInterruptsMask = EncDef.c_psr_I | EncDef.c_psr_F; private const uint ExtraRegistersSize = 3 * sizeof(uint); [Inline] [DisableNullChecks(ApplyRecursively=true)] public override void Prologue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs ) { AddActivationRecordEvent( ActivationRecordEvents.Constructing ); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.StackNotAvailable) == 0) { MethodWrapperHelpers.PushRegisters( EncDef.c_register_sp, true, true, EncDef.c_register_lst_lr ); MethodWrapperHelpers.PushStackFrame(); } AddActivationRecordEvent( ActivationRecordEvents.ReadyForUse ); } [Inline] [DisableNullChecks(ApplyRecursively=true)] public unsafe override void Prologue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs , HardwareException he ) { AddActivationRecordEvent( ActivationRecordEvents.EnteringException ); AddActivationRecordEvent( ActivationRecordEvents.Constructing ); switch(he) { case HardwareException.UndefinedInstruction: MethodWrapperHelpers.AdjustLinkAddress( 4 ); break; // Point to the undefined instruction. case HardwareException.PrefetchAbort : MethodWrapperHelpers.AdjustLinkAddress( 4 ); break; case HardwareException.DataAbort : MethodWrapperHelpers.AdjustLinkAddress( 8 ); break; case HardwareException.Interrupt : MethodWrapperHelpers.AdjustLinkAddress( 4 ); break; case HardwareException.FastInterrupt : MethodWrapperHelpers.AdjustLinkAddress( 4 ); break; case HardwareException.SoftwareInterrupt : break; // Skip the SWI instruction. } switch(he) { case HardwareException.VectorTable: case HardwareException.Bootstrap: case HardwareException.LongJump: case HardwareException.Reset: // // No prologue for these. // AddActivationRecordEvent( ActivationRecordEvents.ReadyForUse ); return; } MethodWrapperHelpers.PushRegisters( EncDef.c_register_sp, true, true, EncDef.c_register_lst_lr ); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.SaveFullProcessorContext) != 0) { MethodWrapperHelpers.PushStackPointer( ExtraRegistersSize ); } var ptr = (Context.RegistersOnStack*)GetRegister( EncDef.c_register_sp ).ToPointer(); MethodWrapperHelpers.PushStackFrame(); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.SaveFullProcessorContext) != 0) { switch(he) { case HardwareException.UndefinedInstruction: PrepareStackForException( EncDef.c_psr_mode_UNDEF, ptr ); break; case HardwareException.PrefetchAbort : PrepareStackForException( EncDef.c_psr_mode_ABORT, ptr ); break; case HardwareException.DataAbort : PrepareStackForException( EncDef.c_psr_mode_ABORT, ptr ); break; case HardwareException.Interrupt : PrepareStackForException( EncDef.c_psr_mode_IRQ , ptr ); break; case HardwareException.FastInterrupt : PrepareStackForException( EncDef.c_psr_mode_FIQ , ptr ); break; case HardwareException.SoftwareInterrupt : PrepareStackForException( EncDef.c_psr_mode_SYS , ptr ); break; } } AddActivationRecordEvent( ActivationRecordEvents.ReadyForUse ); } [Inline] [DisableNullChecks(ApplyRecursively=true)] public override void Epilogue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs ) { AddActivationRecordEvent( ActivationRecordEvents.ReadyForTearDown ); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.NoReturn) == 0) { MethodWrapperHelpers.PopStackFrame(); AddActivationRecordEvent( ActivationRecordEvents.ReturnToCaller ); MethodWrapperHelpers.PopRegisters( EncDef.c_register_sp, true, true, false, EncDef.c_register_lst_pc ); AddActivationRecordEvent( ActivationRecordEvents.NonReachable ); } else { // // The method is not supposed to return, but we have to put something here, // because the stack crawling code will look for this spot during stack unwinding... // Breakpoint( 0x1 ); AddActivationRecordEvent( ActivationRecordEvents.NonReachable ); } } [Inline] [DisableNullChecks(ApplyRecursively=true)] public unsafe override void Epilogue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs , HardwareException he ) { AddActivationRecordEvent( ActivationRecordEvents.ReadyForTearDown ); switch(he) { case HardwareException.VectorTable: case HardwareException.Bootstrap: case HardwareException.Reset: return; case HardwareException.LongJump: { var ptr = (Context.RegistersOnStack*)GetRegister( EncDef.c_register_r1 ).ToPointer(); SetRegister( EncDef.c_register_sp, ptr->SP ); SetRegister( EncDef.c_register_lr, ptr->LR ); SetRegister( EncDef.c_register_r1, new UIntPtr( &ptr->R0 ) ); AddActivationRecordEvent( ActivationRecordEvents.LongJump ); MethodWrapperHelpers.PopRegisters( EncDef.c_register_r1, false, true, false, EncDef.c_register_lst_pc ); AddActivationRecordEvent( ActivationRecordEvents.NonReachable ); } return; default: { MethodWrapperHelpers.PopStackFrame(); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.SaveFullProcessorContext) != 0) { var ptr = (Context.RegistersOnStack*)GetRegister( EncDef.c_register_sp ).ToPointer(); switch(he) { case HardwareException.UndefinedInstruction: RestoreStackForException( EncDef.c_psr_mode_UNDEF, ptr ); break; case HardwareException.PrefetchAbort : RestoreStackForException( EncDef.c_psr_mode_ABORT, ptr ); break; case HardwareException.DataAbort : RestoreStackForException( EncDef.c_psr_mode_ABORT, ptr ); break; case HardwareException.Interrupt : RestoreStackForException( EncDef.c_psr_mode_IRQ , ptr ); break; case HardwareException.FastInterrupt : RestoreStackForException( EncDef.c_psr_mode_FIQ , ptr ); break; case HardwareException.SoftwareInterrupt : RestoreStackForException( EncDef.c_psr_mode_SYS , ptr ); break; } MethodWrapperHelpers.PopStackPointer( ExtraRegistersSize ); } AddActivationRecordEvent( ActivationRecordEvents.ReturnFromException ); MethodWrapperHelpers.PopRegisters( EncDef.c_register_sp, true, true, true, EncDef.c_register_lst_pc ); AddActivationRecordEvent( ActivationRecordEvents.NonReachable ); } return; } } [Inline] private static unsafe void PrepareStackForException( uint mode , Context.RegistersOnStack* ptr ) { // // Keep interrupts disabled. // mode |= DisableInterruptsMask; // // Get CSPR of the calling context. // var CPSR = GetSavedStatusRegister(); // // Save it. // ptr->CPSR = CPSR; // // Disable interrupts. // CPSR |= DisableInterruptsMask; // // Go back to the previous mode. // SetStatusRegister( EncDef.c_psr_field_c, CPSR ); // // Save unbanked R13 and R14. // ptr->LR = GetRegister( EncDef.c_register_lr ); ptr->SP = GetRegister( EncDef.c_register_sp ); // // Switch back to the exception handling mode. // SetStatusRegister( EncDef.c_psr_field_c, mode ); // // R1 should point to the Register Context on the stack. // SetRegister( EncDef.c_register_r1, new UIntPtr( ptr ) ); } [Inline] private static unsafe void RestoreStackForException( uint mode , Context.RegistersOnStack* ptr ) { // // Keep interrupts disabled. // mode |= DisableInterruptsMask; // // Get CSPR of the calling context. // var CPSR = ptr->CPSR; // // Restore the SPSR // SetSavedStatusRegister( EncDef.c_psr_field_ALL, CPSR ); // // Disable interrupts. // CPSR |= DisableInterruptsMask; // // Go back to the previous mode. // SetStatusRegister( EncDef.c_psr_field_c, CPSR ); // // Save unbanked R13 and R14. // SetRegister( EncDef.c_register_lr, ptr->LR ); SetRegister( EncDef.c_register_sp, ptr->SP ); // // Switch back to the exception handling mode. // SetStatusRegister( EncDef.c_psr_field_c, mode ); } } //--// // // Helper Methods // [TS.WellKnownMethod( "ProcessorARM_SetRegister" )] public static extern void SetRegister( uint reg , UIntPtr value ); [TS.WellKnownMethod( "ProcessorARM_GetRegister" )] public static extern UIntPtr GetRegister( uint reg ); [TS.WellKnownMethod( "ProcessorARM_SetSystemRegister" )] public static extern void SetSystemRegister( uint reg , uint value ); [TS.WellKnownMethod( "ProcessorARM_GetSystemRegister" )] public static extern uint GetSystemRegister( uint reg ); //--// [TS.WellKnownMethod( "ProcessorARM_SetStatusRegister" )] public static extern void SetStatusRegister( uint fields , uint value ); [TS.WellKnownMethod( "ProcessorARM_GetStatusRegister" )] public static extern uint GetStatusRegister(); [TS.WellKnownMethod( "ProcessorARM_SetSavedStatusRegister" )] public static extern void SetSavedStatusRegister( uint fields , uint value ); [TS.WellKnownMethod( "ProcessorARM_GetSavedStatusRegister" )] public static extern uint GetSavedStatusRegister(); //--// [TS.WellKnownMethod( "ProcessorARM_MoveToCoprocessor" )] public static extern void MoveToCoprocessor( uint CpNum , uint Op1 , uint CRn , uint CRm , uint Op2 , uint value ); [TS.WellKnownMethod( "ProcessorARM_MoveFromCoprocessor" )] public static extern uint MoveFromCoprocessor( uint CpNum , uint Op1 , uint CRn , uint CRm , uint Op2 ); [TS.WellKnownMethod( "ProcessorARM_Breakpoint" )] public static extern void Breakpoint( uint value ); //--// public override void FlushCacheLine( UIntPtr target ) { } //--//--// [Inline] public override bool AreInterruptsDisabled() { uint cpsr = GetStatusRegister(); return (cpsr & c_InterruptsOff) == c_InterruptsOff; } public override bool AreAllInterruptsDisabled() { uint cpsr = GetStatusRegister(); return (cpsr & c_AllInterruptsOff) == c_AllInterruptsOff; } //--//--// [Inline] public static uint DisableInterrupts() { uint cpsr = GetStatusRegister(); SetStatusRegister( c_psr_field_c, cpsr | c_InterruptsOff ); return cpsr; } [Inline] public static uint DisableAllInterrupts() { uint cpsr = GetStatusRegister(); SetStatusRegister( c_psr_field_c, cpsr | c_AllInterruptsOff ); return cpsr; } //--// [Inline] public static uint EnableInterrupts() { uint cpsr = GetStatusRegister(); SetStatusRegister( c_psr_field_c, cpsr & ~c_InterruptsOff ); return cpsr; } [Inline] public static uint EnableAllInterrupts() { uint cpsr = GetStatusRegister(); SetStatusRegister( c_psr_field_c, cpsr & ~c_AllInterruptsOff ); return cpsr; } //--// [Inline] public override void Breakpoint() { Breakpoint( 0 ); } //--// [Inline] public static void SetMode( uint cpsr ) { SetStatusRegister( c_psr_field_c, cpsr ); } [NoInline] [MemoryUsage(MemoryUsage.Bootstrap)] public static void Nop() { // // Do-nothing method just to flush the pipeline. // } //--// [NoReturn()] [BottomOfCallStack()] [HardwareExceptionHandler(HardwareException.Bootstrap)] private static void Bootstrap() { // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // // We need a way to bootstrap code generation for the entrypoint into the system, which is not a regular piece of code. // It's only composed of a single absolute branch to the entrypoint. // // The code responsible for emitting the opcode for the return operator will detect that // this method is decorated with the Bootstrap flag and it will generate the proper code. // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // } [NoInline] [NoReturn()] [BottomOfCallStack()] [HardwareExceptionHandler(HardwareException.VectorTable)] private static void VectorsTable() { // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // // We need a way to bootstrap code generation for the vector table, which is not a regular piece of code. // It's only composed of branches and the location of the branches is mandated by the hardware. // // The code responsible for emitting the opcode for the return operator will detect that // this method is decorated with the VectorTable flag and it will generate the proper code. // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // } //--// static readonly SoftBreakpointDescriptor[] s_softBreakpointTable = new SoftBreakpointDescriptor[128]; [NoInline] [BottomOfCallStack] [MemoryUsage( MemoryUsage.Bootstrap )] [DebuggerHookHandler( DebuggerHook.GetSoftBreakpointTable )] static SoftBreakpointDescriptor[] GetSoftBreakpointTable() { SoftBreakpointDescriptor[] res = s_softBreakpointTable; Processor.Instance.Breakpoint(); return res; } public static unsafe uint DebuggerAwareRead( uint* ptr ) { uint val = *ptr; if(val == 0xE1200070) // BKPT opcode { UIntPtr address = new UIntPtr( ptr ); for(int i = 0; i < s_softBreakpointTable.Length; i++) { var address2 = s_softBreakpointTable[i].Address; if(address2 == new UIntPtr( 0 )) { break; } if(address2 == address) { return s_softBreakpointTable[i].Value; } } } return val; } } [ExtendClass( typeof( Microsoft.Zelig.Runtime.Processor ) )] internal class ProcessorImpl { [MergeWithTargetImplementation] internal ProcessorImpl() { } [NoInline] [MemoryUsage( MemoryUsage.Bootstrap )] public static int Delay( int count ) { const int fixedOverhead = 16; const int perRoundCost = 6; count -= fixedOverhead; while(count > 0) { count -= perRoundCost; } return count; } } }
using Discord; using Discord.Commands; using NadekoBot.Common; using NadekoBot.Common.Attributes; using NadekoBot.Core.Services; using NadekoBot.Extensions; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Image = SixLabors.ImageSharp.Image; namespace NadekoBot.Modules.Gambling { public partial class Gambling { [Group] public class DiceRollCommands : NadekoSubmodule { private static readonly Regex dndRegex = new Regex(@"^(?<n1>\d+)d(?<n2>\d+)(?:\+(?<add>\d+))?(?:\-(?<sub>\d+))?$", RegexOptions.Compiled); private static readonly Regex fudgeRegex = new Regex(@"^(?<n1>\d+)d(?:F|f)$", RegexOptions.Compiled); private static readonly char[] _fateRolls = { '-', ' ', '+' }; private readonly IImageCache _images; public DiceRollCommands(IDataCache data) { _images = data.LocalImages; } [NadekoCommand, Usage, Description, Aliases] public async Task Roll() { var rng = new NadekoRandom(); var gen = rng.Next(1, 101); var num1 = gen / 10; var num2 = gen % 10; using (var img1 = GetDice(num1)) using (var img2 = GetDice(num2)) using (var img = new[] { img1, img2 }.Merge(out var format)) using (var ms = img.ToStream(format)) { await ctx.Channel.SendFileAsync(ms, $"dice.{format.FileExtensions.First()}", Format.Bold(ctx.User.ToString()) + " " + GetText("dice_rolled", Format.Code(gen.ToString()))).ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [Priority(1)] public async Task Roll(int num) { await InternalRoll(num, true).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [Priority(1)] public async Task Rolluo(int num = 1) { await InternalRoll(num, false).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [Priority(0)] public async Task Roll(string arg) { await InternallDndRoll(arg, true).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [Priority(0)] public async Task Rolluo(string arg) { await InternallDndRoll(arg, false).ConfigureAwait(false); } private async Task InternalRoll(int num, bool ordered) { if (num < 1 || num > 30) { await ReplyErrorLocalizedAsync("dice_invalid_number", 1, 30).ConfigureAwait(false); return; } var rng = new NadekoRandom(); var dice = new List<Image<Rgba32>>(num); var values = new List<int>(num); for (var i = 0; i < num; i++) { var randomNumber = rng.Next(1, 7); var toInsert = dice.Count; if (ordered) { if (randomNumber == 6 || dice.Count == 0) toInsert = 0; else if (randomNumber != 1) for (var j = 0; j < dice.Count; j++) { if (values[j] < randomNumber) { toInsert = j; break; } } } else { toInsert = dice.Count; } dice.Insert(toInsert, GetDice(randomNumber)); values.Insert(toInsert, randomNumber); } using (var bitmap = dice.Merge(out var format)) using (var ms = bitmap.ToStream(format)) { foreach (var d in dice) { d.Dispose(); } await ctx.Channel.SendFileAsync(ms, $"dice.{format.FileExtensions.First()}", Format.Bold(ctx.User.ToString()) + " " + GetText("dice_rolled_num", Format.Bold(values.Count.ToString())) + " " + GetText("total_average", Format.Bold(values.Sum().ToString()), Format.Bold((values.Sum() / (1.0f * values.Count)).ToString("N2")))).ConfigureAwait(false); } } private async Task InternallDndRoll(string arg, bool ordered) { Match match; if ((match = fudgeRegex.Match(arg)).Length != 0 && int.TryParse(match.Groups["n1"].ToString(), out int n1) && n1 > 0 && n1 < 500) { var rng = new NadekoRandom(); var rolls = new List<char>(); for (int i = 0; i < n1; i++) { rolls.Add(_fateRolls[rng.Next(0, _fateRolls.Length)]); } var embed = new EmbedBuilder().WithOkColor().WithDescription(ctx.User.Mention + " " + GetText("dice_rolled_num", Format.Bold(n1.ToString()))) .AddField(efb => efb.WithName(Format.Bold("Result")) .WithValue(string.Join(" ", rolls.Select(c => Format.Code($"[{c}]"))))); await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false); } else if ((match = dndRegex.Match(arg)).Length != 0) { var rng = new NadekoRandom(); if (int.TryParse(match.Groups["n1"].ToString(), out n1) && int.TryParse(match.Groups["n2"].ToString(), out int n2) && n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0) { if (!int.TryParse(match.Groups["add"].Value, out int add)) add = 0; if (!int.TryParse(match.Groups["sub"].Value, out int sub)) sub = 0; var arr = new int[n1]; for (int i = 0; i < n1; i++) { arr[i] = rng.Next(1, n2 + 1); } var sum = arr.Sum(); var embed = new EmbedBuilder().WithOkColor().WithDescription(ctx.User.Mention + " " + GetText("dice_rolled_num", n1) + $"`1 - {n2}`") .AddField(efb => efb.WithName(Format.Bold("Rolls")) .WithValue(string.Join(" ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => Format.Code(x.ToString()))))) .AddField(efb => efb.WithName(Format.Bold("Sum")) .WithValue(sum + " + " + add + " - " + sub + " = " + (sum + add - sub))); await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false); } } } [NadekoCommand, Usage, Description, Aliases] public async Task NRoll([Leftover] string range) { int rolled; if (range.Contains("-")) { var arr = range.Split('-') .Take(2) .Select(int.Parse) .ToArray(); if (arr[0] > arr[1]) { await ReplyErrorLocalizedAsync("second_larger_than_first").ConfigureAwait(false); return; } rolled = new NadekoRandom().Next(arr[0], arr[1] + 1); } else { rolled = new NadekoRandom().Next(0, int.Parse(range) + 1); } await ReplyConfirmLocalizedAsync("dice_rolled", Format.Bold(rolled.ToString())).ConfigureAwait(false); } private Image<Rgba32> GetDice(int num) { if (num < 0 || num > 10) throw new ArgumentOutOfRangeException(nameof(num)); if (num == 10) { var images = _images.Dice; using (var imgOne = Image.Load(images[1])) using (var imgZero = Image.Load(images[0])) { return new[] { imgOne, imgZero }.Merge(); } } return Image.Load(_images.Dice[num]); } } } }
// // MeasuringStream.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013 Jeffrey Stedfast // // 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; namespace MimeKit.IO { /// <summary> /// A stream useful for measuring the amount of data written. /// </summary> public class MeasuringStream : Stream { bool disposed; long position; long length; /// <summary> /// Initializes a new instance of the <see cref="MimeKit.IO.MeasuringStream"/> class. /// </summary> public MeasuringStream () { } void CheckDisposed () { if (disposed) throw new ObjectDisposedException ("stream"); } #region implemented abstract members of Stream /// <summary> /// Checks whether or not the stream supports reading. /// </summary> /// <value><c>true</c> if the stream supports reading; otherwise, <c>false</c>.</value> public override bool CanRead { get { return false; } } /// <summary> /// Checks whether or not the stream supports writing. /// </summary> /// <value> /// <c>true</c> if the stream supports writing; otherwise, <c>false</c>.</value> public override bool CanWrite { get { return true; } } /// <summary> /// Checks whether or not the stream supports seeking. /// </summary> /// <value><c>true</c> if the stream supports seeking; otherwise, <c>false</c>.</value> public override bool CanSeek { get { return true; } } /// <summary> /// Checks whether or not reading and writing to the stream can timeout. /// </summary> /// <value><c>true</c> if reading and writing to the stream can timeout; otherwise, <c>false</c>.</value> public override bool CanTimeout { get { return false; } } /// <summary> /// Gets the length in bytes of the stream. /// </summary> /// <returns>A long value representing the length of the stream in bytes.</returns> /// <value>The length of the stream.</value> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> public override long Length { get { CheckDisposed (); return length; } } /// <summary> /// Gets or sets the position within the current stream. /// </summary> /// <returns>The current position within the stream.</returns> /// <value>The position of the stream.</value> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="System.NotSupportedException"> /// The stream does not support seeking. /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> public override long Position { get { return position; } set { Seek (value, SeekOrigin.Begin); } } void ValidateArguments (byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException ("buffer"); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException ("offset"); if (count < 0 || offset + count > buffer.Length) throw new ArgumentOutOfRangeException ("count"); } /// <summary> /// Reads a sequence of bytes from the stream and advances the position /// within the stream by the number of bytes read. /// </summary> /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many /// bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns> /// <param name="buffer">The buffer to read data into.</param> /// <param name="offset">The offset into the buffer to start reading data.</param> /// <param name="count">The number of bytes to read.</param> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> /// <exception cref="System.NotSupportedException"> /// The stream does not support reading. /// </exception> public override int Read (byte[] buffer, int offset, int count) { CheckDisposed (); throw new NotSupportedException ("The stream does not support reading"); } /// <summary> /// Writes a sequence of bytes to the stream and advances the current /// position within this stream by the number of bytes written. /// </summary> /// <param name='buffer'>The buffer to write.</param> /// <param name='offset'>The offset of the first byte to write.</param> /// <param name='count'>The number of bytes to write.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para> /// <para>-or-</para> /// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting /// at the specified <paramref name="offset"/>.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> /// <exception cref="System.NotSupportedException"> /// The stream does not support writing. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public override void Write (byte[] buffer, int offset, int count) { CheckDisposed (); ValidateArguments (buffer, offset, count); position += count; length = Math.Max (length, position); } /// <summary> /// Sets the position within the current stream. /// </summary> /// <returns>The new position within the stream.</returns> /// <param name="offset">The offset into the stream relative to the <paramref name="origin"/>.</param> /// <param name="origin">The origin to seek from.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="origin"/> is not a valid <see cref="System.IO.SeekOrigin"/>. /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> public override long Seek (long offset, SeekOrigin origin) { long real; CheckDisposed (); switch (origin) { case SeekOrigin.Begin: real = offset; break; case SeekOrigin.Current: real = position + offset; break; case SeekOrigin.End: real = length + offset; break; default: throw new ArgumentOutOfRangeException ("origin", "Invalid SeekOrigin specified"); } // sanity check the resultant offset if (real < 0) throw new IOException ("Cannot seek to a position before the beginning of the stream"); // short-cut if we are seeking to our current position if (real == position) return position; if (real > length) throw new IOException ("Cannot seek beyond the end of the stream"); position = real; return position; } /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written /// to the underlying device. /// </summary> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> public override void Flush () { CheckDisposed (); // nothing to do... } /// <summary> /// Sets the length of the stream. /// </summary> /// <param name='value'>The desired length of the stream in bytes.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="value"/> is out of range. /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> public override void SetLength (long value) { CheckDisposed (); if (value < 0) throw new ArgumentOutOfRangeException ("value"); position = Math.Min (position, value); length = value; } #endregion /// <summary> /// Dispose the specified disposing. /// </summary> /// <param name="disposing">If set to <c>true</c> disposing.</param> protected override void Dispose (bool disposing) { base.Dispose (disposing); disposed = true; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class NamespaceCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) { var collection = new NamespaceCollection(state, parent, fileCodeModel, nodeKey); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private SyntaxNodeKey _nodeKey; private NamespaceCollection( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) : base(state, parent) { Debug.Assert(fileCodeModel != null); _fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel); _nodeKey = nodeKey; } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private bool IsRootNamespace { get { return _nodeKey == SyntaxNodeKey.Empty; } } private SyntaxNode LookupNode() { if (!IsRootNamespace) { return FileCodeModel.LookupNode(_nodeKey); } else { return FileCodeModel.GetSyntaxRoot(); } } private EnvDTE.CodeElement CreateCodeOptionsStatement(SyntaxNode node, SyntaxNode parentNode) { string name; int ordinal; CodeModelService.GetOptionNameAndOrdinal(parentNode, node, out name, out ordinal); return CodeOptionsStatement.Create(this.State, this.FileCodeModel, name, ordinal); } private EnvDTE.CodeElement CreateCodeImport(SyntaxNode node, AbstractCodeElement parentElement) { var name = CodeModelService.GetImportNamespaceOrType(node); return CodeImport.Create(this.State, this.FileCodeModel, parentElement, name); } private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node, SyntaxNode parentNode, AbstractCodeElement parentElement) { string name; int ordinal; CodeModelService.GetAttributeNameAndOrdinal(parentNode, node, out name, out ordinal); return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this.FileCodeModel, parentElement, name, ordinal); } internal override Snapshot CreateSnapshot() { var node = LookupNode(); var parentElement = !this.IsRootNamespace ? (AbstractCodeElement)this.Parent : null; var nodesBuilder = ArrayBuilder<SyntaxNode>.GetInstance(); nodesBuilder.AddRange(CodeModelService.GetOptionNodes(node)); nodesBuilder.AddRange(CodeModelService.GetImportNodes(node)); nodesBuilder.AddRange(CodeModelService.GetAttributeNodes(node)); nodesBuilder.AddRange(CodeModelService.GetLogicalSupportedMemberNodes(node)); return new NodeSnapshot(this.State, _fileCodeModel, node, parentElement, nodesBuilder.ToImmutableAndFree()); } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var node = LookupNode(); var parentElement = !this.IsRootNamespace ? (AbstractCodeElement)this.Parent : null; int currentIndex = 0; // Option statements var optionNodes = CodeModelService.GetOptionNodes(node); var optionNodeCount = optionNodes.Count(); if (index < currentIndex + optionNodeCount) { var child = optionNodes.ElementAt(index - currentIndex); element = CreateCodeOptionsStatement(child, node); return true; } currentIndex += optionNodeCount; // Imports/using statements var importNodes = CodeModelService.GetImportNodes(node); var importNodeCount = importNodes.Count(); if (index < currentIndex + importNodeCount) { var child = importNodes.ElementAt(index - currentIndex); element = CreateCodeImport(child, parentElement); return true; } currentIndex += importNodeCount; // Attributes var attributeNodes = CodeModelService.GetAttributeNodes(node); var attributeNodeCount = attributeNodes.Count(); if (index < currentIndex + attributeNodeCount) { var child = attributeNodes.ElementAt(index - currentIndex); element = CreateCodeAttribute(child, node, parentElement); return true; } currentIndex += attributeNodeCount; // Members var memberNodes = CodeModelService.GetLogicalSupportedMemberNodes(node); var memberNodeCount = memberNodes.Count(); if (index < currentIndex + memberNodeCount) { var child = memberNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var node = LookupNode(); var parentElement = !IsRootNamespace ? (AbstractCodeElement)Parent : null; // Option statements foreach (var child in CodeModelService.GetOptionNodes(node)) { string childName; int ordinal; CodeModelService.GetOptionNameAndOrdinal(node, child, out childName, out ordinal); if (childName == name) { element = CodeOptionsStatement.Create(State, FileCodeModel, childName, ordinal); return true; } } // Imports/using statements foreach (var child in CodeModelService.GetImportNodes(node)) { var childName = CodeModelService.GetImportNamespaceOrType(child); if (childName == name) { element = CodeImport.Create(State, FileCodeModel, parentElement, childName); return true; } } // Attributes foreach (var child in CodeModelService.GetAttributeNodes(node)) { string childName; int ordinal; CodeModelService.GetAttributeNameAndOrdinal(node, child, out childName, out ordinal); if (childName == name) { element = (EnvDTE.CodeElement)CodeAttribute.Create(State, FileCodeModel, parentElement, childName, ordinal); return true; } } // Members foreach (var child in CodeModelService.GetLogicalSupportedMemberNodes(node)) { var childName = CodeModelService.GetName(child); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } element = null; return false; } public override int Count { get { var node = LookupNode(); return CodeModelService.GetOptionNodes(node).Count() + CodeModelService.GetImportNodes(node).Count() + CodeModelService.GetAttributeNodes(node).Count() + CodeModelService.GetLogicalSupportedMemberNodes(node).Count(); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenSim.Framework.Monitoring; using OpenSim.Data; using OpenSim.Server.Base; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalInventoryServicesConnector")] public class LocalInventoryServicesConnector : ISharedRegionModule, IInventoryService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Scene used by this module. This currently needs to be publicly settable for HGInventoryBroker. /// </summary> public Scene Scene { get; set; } private IInventoryService m_InventoryService; private IUserManagement m_UserManager; private IUserManagement UserManager { get { if (m_UserManager == null) { m_UserManager = Scene.RequestModuleInterface<IUserManagement>(); } return m_UserManager; } } private bool m_Enabled = false; public Type ReplaceableInterface { get { return null; } } public string Name { get { return "LocalInventoryServicesConnector"; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("InventoryServices", ""); if (name == Name) { IConfig inventoryConfig = source.Configs["InventoryService"]; if (inventoryConfig == null) { m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: InventoryService missing from OpenSim.ini"); return; } string serviceDll = inventoryConfig.GetString("LocalServiceModule", String.Empty); if (serviceDll == String.Empty) { m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: No LocalServiceModule named in section InventoryService"); return; } Object[] args = new Object[] { source }; m_log.DebugFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Service dll = {0}", serviceDll); m_InventoryService = ServerUtils.LoadPlugin<IInventoryService>(serviceDll, args); if (m_InventoryService == null) { m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: Can't load inventory service"); throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's"); } m_Enabled = true; m_log.Info("[LOCAL INVENTORY SERVICES CONNECTOR]: Local inventory connector enabled"); } } } public void PostInitialise() { } public void Close() { } public void AddRegion(Scene scene) { if (!m_Enabled) return; scene.RegisterModuleInterface<IInventoryService>(this); if (Scene == null) Scene = scene; } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; } #region IInventoryService public bool CreateUserInventory(UUID user) { return m_InventoryService.CreateUserInventory(user); } public List<InventoryFolderBase> GetInventorySkeleton(UUID userId) { return m_InventoryService.GetInventorySkeleton(userId); } public InventoryFolderBase GetRootFolder(UUID userID) { return m_InventoryService.GetRootFolder(userID); } public InventoryFolderBase GetFolderForType(UUID userID, AssetType type) { return m_InventoryService.GetFolderForType(userID, type); } public InventoryCollection GetFolderContent(UUID userID, UUID folderID) { InventoryCollection invCol = m_InventoryService.GetFolderContent(userID, folderID); if (UserManager != null) { // Protect ourselves against the caller subsequently modifying the items list List<InventoryItemBase> items = new List<InventoryItemBase>(invCol.Items); WorkManager.RunInThread(delegate { foreach (InventoryItemBase item in items) if (!string.IsNullOrEmpty(item.CreatorData)) UserManager.AddUser(item.CreatorIdAsUuid, item.CreatorData); }, null, string.Format("GetFolderContent (user {0}, folder {1})", userID, folderID)); } return invCol; } public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID) { return m_InventoryService.GetFolderItems(userID, folderID); } /// <summary> /// Add a new folder to the user's inventory /// </summary> /// <param name="folder"></param> /// <returns>true if the folder was successfully added</returns> public bool AddFolder(InventoryFolderBase folder) { return m_InventoryService.AddFolder(folder); } /// <summary> /// Update a folder in the user's inventory /// </summary> /// <param name="folder"></param> /// <returns>true if the folder was successfully updated</returns> public bool UpdateFolder(InventoryFolderBase folder) { return m_InventoryService.UpdateFolder(folder); } /// <summary> /// Move an inventory folder to a new location /// </summary> /// <param name="folder">A folder containing the details of the new location</param> /// <returns>true if the folder was successfully moved</returns> public bool MoveFolder(InventoryFolderBase folder) { return m_InventoryService.MoveFolder(folder); } public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs) { return m_InventoryService.DeleteFolders(ownerID, folderIDs); } /// <summary> /// Purge an inventory folder of all its items and subfolders. /// </summary> /// <param name="folder"></param> /// <returns>true if the folder was successfully purged</returns> public bool PurgeFolder(InventoryFolderBase folder) { return m_InventoryService.PurgeFolder(folder); } public bool AddItem(InventoryItemBase item) { // m_log.DebugFormat( // "[LOCAL INVENTORY SERVICES CONNECTOR]: Adding inventory item {0} to user {1} folder {2}", // item.Name, item.Owner, item.Folder); return m_InventoryService.AddItem(item); } /// <summary> /// Update an item in the user's inventory /// </summary> /// <param name="item"></param> /// <returns>true if the item was successfully updated</returns> public bool UpdateItem(InventoryItemBase item) { return m_InventoryService.UpdateItem(item); } public bool MoveItems(UUID ownerID, List<InventoryItemBase> items) { return m_InventoryService.MoveItems(ownerID, items); } /// <summary> /// Delete an item from the user's inventory /// </summary> /// <param name="item"></param> /// <returns>true if the item was successfully deleted</returns> public bool DeleteItems(UUID ownerID, List<UUID> itemIDs) { return m_InventoryService.DeleteItems(ownerID, itemIDs); } public InventoryItemBase GetItem(InventoryItemBase item) { // m_log.DebugFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Requesting inventory item {0}", item.ID); // UUID requestedItemId = item.ID; item = m_InventoryService.GetItem(item); // if (null == item) // m_log.ErrorFormat( // "[LOCAL INVENTORY SERVICES CONNECTOR]: Could not find item with id {0}", requestedItemId); return item; } public InventoryFolderBase GetFolder(InventoryFolderBase folder) { return m_InventoryService.GetFolder(folder); } /// <summary> /// Does the given user have an inventory structure? /// </summary> /// <param name="userID"></param> /// <returns></returns> public bool HasInventoryForUser(UUID userID) { return m_InventoryService.HasInventoryForUser(userID); } public List<InventoryItemBase> GetActiveGestures(UUID userId) { return m_InventoryService.GetActiveGestures(userId); } public int GetAssetPermissions(UUID userID, UUID assetID) { return m_InventoryService.GetAssetPermissions(userID, assetID); } #endregion IInventoryService } }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ------------------------------------------------------------------------------ namespace Microsoft.Live { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; /// <summary> /// LiveAuthClientCore class provides the core implementation of authentication/authorization logic /// behind the public LiveAuthClient class /// </summary> internal class LiveAuthClientCore { private readonly LiveAuthClient publicAuthClient; private readonly string clientId; private readonly IRefreshTokenHandler refreshTokenHandler; private LiveLoginResult loginStatus; private RefreshTokenInfo refreshTokenInfo; private TaskCompletionSource<LiveLoginResult> initTask; private TaskCompletionSource<LiveConnectSession> codeExchangeTask; private IEnumerable<string> initScopes; /// <summary> /// Initializes a new instance of the LiveAuthClientCore class. /// </summary> public LiveAuthClientCore( string clientId, IRefreshTokenHandler refreshTokenHandler, LiveAuthClient authClient) { Debug.Assert(!string.IsNullOrEmpty(clientId)); Debug.Assert(authClient != null); this.clientId = clientId; this.refreshTokenHandler = refreshTokenHandler; this.publicAuthClient = authClient; } /// <summary> /// Initializes the LiveAuthClient instance by trying to retrieve an access token using refresh token /// provided by the app via the IRefreshTokenHandler instance. /// </summary> public Task<LiveLoginResult> InitializeAsync(IEnumerable<string> scopes) { // We don't allow InitializeAsync or ExchangeAuthCodeAsync to be invoked concurrently. if (this.initTask != null) { throw new InvalidOperationException(ErrorText.ExistingAuthTaskRunning); } var task = new TaskCompletionSource<LiveLoginResult>(); this.initTask = task; this.initScopes = scopes; if (this.loginStatus != null) { // We have a result already, then return this one. this.OnInitCompleted(null); } else { this.loginStatus = new LiveLoginResult(LiveConnectSessionStatus.Unknown, null); this.TryRefreshToken(); } return task.Task; } /// <summary> /// Exchange authentication code for access token. /// </summary> /// <param name="AuthenticationCode">The authentication code the app received from Microsoft authorization server during user authentication and authorization process.</param> /// <returns></returns> public Task<LiveConnectSession> ExchangeAuthCodeAsync(string authenticationCode) { Debug.Assert(!string.IsNullOrEmpty(authenticationCode)); // We don't allow InitializeAsync or ExchangeAuthCodeAsync to be invoked concurrently. if (this.codeExchangeTask != null) { throw new InvalidOperationException(ErrorText.ExistingAuthTaskRunning); } this.codeExchangeTask = new TaskCompletionSource<LiveConnectSession>(); this.ExchangeCodeForToken(authenticationCode); return this.codeExchangeTask.Task; } /// <summary> /// Generates a consent URL that includes a set of provided parameters. /// </summary> public string GetLoginUrl(IEnumerable<string> scopes, string redirectUrl, DisplayType display, ThemeType theme, string locale, string state) { return LiveAuthUtility.BuildAuthorizeUrl(this.clientId, redirectUrl, scopes, ResponseType.Code, display, theme, locale, state); } internal bool CanRefreshToken { get { return this.refreshTokenHandler != null; } } internal void TryRefreshToken() { this.TryRefreshToken(null); } internal void TryRefreshToken(Action<LiveLoginResult> completionCallback) { LiveLoginResult result = new LiveLoginResult(LiveConnectSessionStatus.Unknown, null); if (this.refreshTokenHandler != null) { if (this.refreshTokenInfo == null) { this.refreshTokenHandler.RetrieveRefreshTokenAsync().ContinueWith(t => { this.refreshTokenInfo = t.Result; this.RefreshToken(completionCallback); }); return; } this.RefreshToken(completionCallback); return; } this.OnRefreshTokenCompleted(result, completionCallback); } private void RefreshToken(Action<LiveLoginResult> completionCallback) { if (this.refreshTokenInfo != null) { LiveAuthRequestUtility.RefreshTokenAsync( this.clientId, null, LiveAuthUtility.BuildDesktopRedirectUrl(), this.refreshTokenInfo.RefreshToken, null /*scopes*/ ).ContinueWith(t => { this.OnRefreshTokenCompleted(t.Result, completionCallback); }); } else { LiveLoginResult result = new LiveLoginResult(LiveConnectSessionStatus.Unknown, null); this.OnRefreshTokenCompleted(result, completionCallback); } } private void OnRefreshTokenCompleted(LiveLoginResult result, Action<LiveLoginResult> completionCallback) { if (completionCallback != null) { this.UpdateSession(result); completionCallback(result); } else { this.OnInitCompleted(result); } } private void UpdateSession(LiveLoginResult result) { Debug.Assert(result != null); if (result.Session != null) { // Set the AuthClient that is needed when refreshing a token. result.Session.AuthClient = this.publicAuthClient; // We have a new session, update the public property this.loginStatus = result; this.publicAuthClient.Session = result.Session; if (this.refreshTokenHandler != null && !string.IsNullOrEmpty(result.Session.RefreshToken)) { RefreshTokenInfo refreshInfo = new RefreshTokenInfo(result.Session.RefreshToken); this.refreshTokenHandler.SaveRefreshTokenAsync(refreshInfo); } } else if (this.loginStatus.Status == LiveConnectSessionStatus.Unknown && result.Status == LiveConnectSessionStatus.NotConnected) { this.loginStatus = result; } } private void OnInitCompleted(LiveLoginResult authResult) { authResult = this.ValidateSessionInitScopes(authResult); this.UpdateSession(authResult); Debug.Assert(this.loginStatus != null); this.publicAuthClient.FirePendingPropertyChangedEvents(); if (authResult != null && authResult.Error != null) { this.initTask.SetException(authResult.Error); } else { this.initTask.SetResult(this.loginStatus); } this.initTask = null; } private LiveLoginResult ValidateSessionInitScopes(LiveLoginResult loginResult) { if (loginResult.Session != null && this.initScopes != null) { if (!LiveAuthUtility.IsSubsetOfScopeRange(this.initScopes, loginResult.Session.Scopes)) { loginResult = new LiveLoginResult(LiveConnectSessionStatus.NotConnected, null); } this.initScopes = null; } return loginResult; } private void ExchangeCodeForToken(string authorizationCode) { Task<LiveLoginResult> task = LiveAuthRequestUtility.ExchangeCodeForTokenAsync( this.clientId, null, LiveAuthUtility.BuildDesktopRedirectUrl(), authorizationCode); task.ContinueWith((Task<LiveLoginResult> t) => { this.OnExchangeCodeCompleted(t.Result); }); } private void OnExchangeCodeCompleted(LiveLoginResult authResult) { this.UpdateSession(authResult); Debug.Assert(this.loginStatus != null); this.publicAuthClient.FirePendingPropertyChangedEvents(); if (authResult != null && authResult.Error != null) { this.codeExchangeTask.SetException(authResult.Error); } else { this.codeExchangeTask.SetResult(authResult.Session); } this.codeExchangeTask = null; } } }
// Adaptive Quality|Utilities|90050 // Adapted from The Lab Renderer's ValveCamera.cs, available at // https://github.com/ValveSoftware/the_lab_renderer/blob/ae64c48a8ccbe5406aba1e39b160d4f2f7156c2c/Assets/TheLabRenderer/Scripts/ValveCamera.cs // For The Lab Renderer's license see THIRD_PARTY_NOTICES. // **Only Compatible With Unity 5.4 and above** #if (UNITY_5_4_OR_NEWER) namespace VRTK { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.VR; /// <summary> /// Adaptive Quality dynamically changes rendering settings to maintain VR framerate while maximizing GPU utilization. /// </summary> /// <remarks> /// > **Only Compatible With Unity 5.4 and above** /// /// There are two goals: /// <list type="bullet"> /// <item> <description>Reduce the chances of dropping frames and reprojecting</description> </item> /// <item> <description>Increase quality when there are idle GPU cycles</description> </item> /// </list> /// <para /> /// This script currently changes the following to reach these goals: /// <list type="bullet"> /// <item> <description>Rendering resolution and viewport size (aka Dynamic Resolution)</description> </item> /// </list> /// <para /> /// In the future it could be changed to also change the following: /// <list type="bullet"> /// <item> <description>MSAA level</description> </item> /// <item> <description>Fixed Foveated Rendering</description> </item> /// <item> <description>Radial Density Masking</description> </item> /// <item> <description>(Non-fixed) Foveated Rendering (once HMDs support eye tracking)</description> </item> /// </list> /// <para /> /// Some shaders, especially Image Effects, need to be modified to work with the changed render scale. To fix them /// pass `1.0f / VRSettings.renderViewportScale` into the shader and scale all incoming UV values with it in the vertex /// program. Do this by using `Material.SetFloat` to set the value in the script that configures the shader. /// <para /> /// In more detail: /// <list type="bullet"> /// <item> <description>In the `.shader` file: Add a new runtime-set property value `float _InverseOfRenderViewportScale` /// and add `vertexInput.texcoord *= _InverseOfRenderViewportScale` to the start of the vertex program</description> </item> /// <item> <description>In the `.cs` file: Before using the material (eg. `Graphics.Blit`) add /// `material.SetFloat("_InverseOfRenderViewportScale", 1.0f / VRSettings.renderViewportScale)`</description> </item> /// </list> /// </remarks> /// <example> /// `VRTK/Examples/039_CameraRig_AdaptiveQuality` displays the frames per second in the centre of the headset view. /// The debug visualization of this script is displayed near the top edge of the headset view. /// Pressing the trigger generates a new sphere and pressing the touchpad generates ten new spheres. /// Eventually when lots of spheres are present the FPS will drop and demonstrate the script. /// </example> public sealed class VRTK_AdaptiveQuality : MonoBehaviour { #region Public fields [Tooltip("Toggles whether to show the debug overlay.\n\n" + "Each square represents a different level on the quality scale. Levels increase from left to right," + " the first green box that is lit above represents the recommended render target resolution provided by the" + " current `VRDevice`, the box that is lit below in cyan represents the current resolution and the filled box" + " represents the current viewport scale. The yellow boxes represent resolutions below the recommended render target resolution.\n" + "The currently lit box becomes red whenever the user is likely seeing reprojection in the HMD since the" + " application isn't maintaining VR framerate. If lit, the box all the way on the left is almost always lit" + " red because it represents the lowest render scale with reprojection on.")] public bool drawDebugVisualization; [Tooltip("Toggles whether to allow keyboard shortcuts to control this script.\n\n" + "* The supported shortcuts are:\n" + " * `Shift+F1`: Toggle debug visualization on/off\n" + " * `Shift+F2`: Toggle usage of override render scale on/off\n" + " * `Shift+F3`: Decrease override render scale level\n" + " * `Shift+F4`: Increase override render scale level")] public bool allowKeyboardShortcuts = true; [Tooltip("Toggles whether to allow command line arguments to control this script at startup of the standalone build.\n\n" + "* The supported command line arguments all begin with '-' and are:\n" + " * `-noaq`: Disable adaptive quality\n" + " * `-aqminscale X`: Set minimum render scale to X\n" + " * `-aqmaxscale X`: Set maximum render scale to X\n" + " * `-aqmaxres X`: Set maximum render target dimension to X\n" + " * `-aqfillratestep X`: Set render scale fill rate step size in percent to X (X from 1 to 100)\n" + " * `-aqoverride X`: Set override render scale level to X\n" + " * `-vrdebug`: Enable debug visualization\n" + " * `-msaa X`: Set MSAA level to X")] public bool allowCommandLineArguments = true; [Tooltip("The MSAA level to use.")] [Header("Quality")] [Range(0, 8)] public int msaaLevel = 4; [Tooltip("Toggles whether the render viewport scale is dynamically adjusted to maintain VR framerate.\n\n" + "If unchecked, the renderer will render at the recommended resolution provided by the current `VRDevice`.")] public bool scaleRenderViewport = true; [Tooltip("The minimum allowed render scale.")] [Range(0.01f, 5)] public float minimumRenderScale = 0.8f; [Tooltip("The maximum allowed render scale.")] public float maximumRenderScale = 1.4f; [Tooltip("The maximum allowed render target dimension.\n\n" + "This puts an upper limit on the size of the render target regardless of the maximum render scale.")] public int maximumRenderTargetDimension = 4096; [Tooltip("The fill rate step size in percent by which the render scale levels will be calculated.")] [Range(1, 100)] public int renderScaleFillRateStepSizeInPercent = 15; [Tooltip("Toggles whether the render target resolution is dynamically adjusted to maintain VR framerate.\n\n" + "If unchecked, the renderer will use the maximum target resolution specified by `maximumRenderScale`.")] public bool scaleRenderTargetResolution = false; [Tooltip("Toggles whether to override the used render viewport scale level.")] [Header("Override")] [NonSerialized] public bool overrideRenderViewportScale; [Tooltip("The render viewport scale level to override the current one with.")] [NonSerialized] public int overrideRenderViewportScaleLevel; #endregion #region Public readonly fields & properties /// <summary> /// All the calculated render scales. /// </summary> /// <remarks> /// The elements of this collection are to be interpreted as modifiers to the recommended render target /// resolution provided by the current `VRDevice`. /// </remarks> public readonly ReadOnlyCollection<float> renderScales; /// <summary> /// The current render scale. /// </summary> /// <remarks> /// A render scale of `1.0` represents the recommended render target resolution provided by the current `VRDevice`. /// </remarks> public static float CurrentRenderScale { get { return VRSettings.renderScale * VRSettings.renderViewportScale; } } /// <summary> /// The recommended render target resolution provided by the current `VRDevice`. /// </summary> public Vector2 defaultRenderTargetResolution { get { return RenderTargetResolutionForRenderScale(allRenderScales[defaultRenderViewportScaleLevel]); } } /// <summary> /// The current render target resolution. /// </summary> public Vector2 currentRenderTargetResolution { get { return RenderTargetResolutionForRenderScale(CurrentRenderScale); } } #endregion #region Private fields /// <summary> /// The frame duration in milliseconds to fallback to if the current `VRDevice` specifies no refresh rate. /// </summary> private const float DefaultFrameDurationInMilliseconds = 1000f / 90f; private readonly AdaptiveSetting<int> renderViewportScaleSetting = new AdaptiveSetting<int>(0, 30, 10); private readonly AdaptiveSetting<int> renderScaleSetting = new AdaptiveSetting<int>(0, 180, 90); private readonly List<float> allRenderScales = new List<float>(); private int defaultRenderViewportScaleLevel; private float previousMinimumRenderScale; private float previousMaximumRenderScale; private float previousRenderScaleFillRateStepSizeInPercent; private readonly Timing timing = new Timing(); private int lastRenderViewportScaleLevelBelowRenderScaleLevelFrameCount; private bool interleavedReprojectionEnabled; private bool hmdDisplayIsOnDesktop; private float singleFrameDurationInMilliseconds; private GameObject debugVisualizationQuad; private Material debugVisualizationQuadMaterial; #endregion public VRTK_AdaptiveQuality() { renderScales = allRenderScales.AsReadOnly(); } /// <summary> /// Calculates and returns the render target resolution for a given render scale. /// </summary> /// <param name="renderScale"> /// The render scale to calculate the render target resolution with. /// </param> /// <returns> /// The render target resolution for `renderScale`. /// </returns> public static Vector2 RenderTargetResolutionForRenderScale(float renderScale) { return new Vector2((int)(VRSettings.eyeTextureWidth / VRSettings.renderScale * renderScale), (int)(VRSettings.eyeTextureHeight / VRSettings.renderScale * renderScale)); } /// <summary> /// Calculates and returns the biggest allowed maximum render scale to be used for `maximumRenderScale` /// given the current `maximumRenderTargetDimension`. /// </summary> /// <returns> /// The biggest allowed maximum render scale. /// </returns> public float BiggestAllowedMaximumRenderScale() { if (VRSettings.eyeTextureWidth == 0 || VRSettings.eyeTextureHeight == 0) { return maximumRenderScale; } float maximumHorizontalRenderScale = maximumRenderTargetDimension * VRSettings.renderScale / VRSettings.eyeTextureWidth; float maximumVerticalRenderScale = maximumRenderTargetDimension * VRSettings.renderScale / VRSettings.eyeTextureHeight; return Mathf.Min(maximumHorizontalRenderScale, maximumVerticalRenderScale); } /// <summary> /// A summary of this script by listing all the calculated render scales with their /// corresponding render target resolution. /// </summary> /// <returns> /// The summary. /// </returns> public override string ToString() { var stringBuilder = new StringBuilder("Adaptive Quality\n"); stringBuilder.AppendLine("Render Scale:"); stringBuilder.AppendLine("Level - Resolution - Multiplier"); for (int index = 0; index < allRenderScales.Count; index++) { float renderScale = allRenderScales[index]; var renderTargetResolution = RenderTargetResolutionForRenderScale(renderScale); stringBuilder.AppendFormat( "{0, 3} {1, 5}x{2, -5} {3, -8}", index, (int)renderTargetResolution.x, (int)renderTargetResolution.y, renderScale); if (index == 0) { stringBuilder.Append(" (Interleaved reprojection hint)"); } else if (index == defaultRenderViewportScaleLevel) { stringBuilder.Append(" (Default)"); } if (index == renderViewportScaleSetting.currentValue) { stringBuilder.Append(" (Current Viewport)"); } if (index == renderScaleSetting.currentValue) { stringBuilder.Append(" (Current Target Resolution)"); } if (index != allRenderScales.Count - 1) { stringBuilder.AppendLine(); } } return stringBuilder.ToString(); } #region MonoBehaviour methods private void OnEnable() { Camera.onPreCull += OnCameraPreCull; hmdDisplayIsOnDesktop = VRTK_SDK_Bridge.IsDisplayOnDesktop(); singleFrameDurationInMilliseconds = VRDevice.refreshRate > 0.0f ? 1000.0f / VRDevice.refreshRate : DefaultFrameDurationInMilliseconds; HandleCommandLineArguments(); if (!Application.isEditor) { OnValidate(); } } private void OnDisable() { Camera.onPreCull -= OnCameraPreCull; SetRenderScale(1.0f, 1.0f); } private void OnValidate() { minimumRenderScale = Mathf.Max(0.01f, minimumRenderScale); maximumRenderScale = Mathf.Max(minimumRenderScale, maximumRenderScale); maximumRenderTargetDimension = Mathf.Max(2, maximumRenderTargetDimension); renderScaleFillRateStepSizeInPercent = Mathf.Max(1, renderScaleFillRateStepSizeInPercent); msaaLevel = msaaLevel == 1 ? 0 : Mathf.Clamp(Mathf.ClosestPowerOfTwo(msaaLevel), 0, 8); } private void Update() { HandleKeyPresses(); UpdateRenderScaleLevels(); CreateOrDestroyDebugVisualization(); UpdateDebugVisualization(); timing.SaveCurrentFrameTiming(); } #if UNITY_5_4_1 || UNITY_5_4_2 || UNITY_5_4_3 || UNITY_5_5_OR_NEWER private void LateUpdate() { UpdateRenderScale(); } #endif private void OnCameraPreCull(Camera camera) { if (camera.transform != VRTK_SDK_Bridge.GetHeadsetCamera()) { return; } #if !(UNITY_5_4_1 || UNITY_5_4_2 || UNITY_5_4_3 || UNITY_5_5_OR_NEWER) UpdateRenderScale(); #endif UpdateMSAALevel(); } #endregion private void HandleCommandLineArguments() { if (!allowCommandLineArguments) { return; } var commandLineArguments = Environment.GetCommandLineArgs(); for (int index = 0; index < commandLineArguments.Length; index++) { string argument = commandLineArguments[index]; string nextArgument = index + 1 < commandLineArguments.Length ? commandLineArguments[index + 1] : ""; switch (argument) { case CommandLineArguments.Disable: scaleRenderViewport = false; break; case CommandLineArguments.MinimumRenderScale: minimumRenderScale = float.Parse(nextArgument); break; case CommandLineArguments.MaximumRenderScale: maximumRenderScale = float.Parse(nextArgument); break; case CommandLineArguments.MaximumRenderTargetDimension: maximumRenderTargetDimension = int.Parse(nextArgument); break; case CommandLineArguments.RenderScaleFillRateStepSizeInPercent: renderScaleFillRateStepSizeInPercent = int.Parse(nextArgument); break; case CommandLineArguments.OverrideRenderScaleLevel: overrideRenderViewportScale = true; overrideRenderViewportScaleLevel = int.Parse(nextArgument); break; case CommandLineArguments.DrawDebugVisualization: drawDebugVisualization = true; break; case CommandLineArguments.MSAALevel: msaaLevel = int.Parse(nextArgument); break; } } } private void HandleKeyPresses() { if (!allowKeyboardShortcuts || !KeyboardShortcuts.Modifiers.Any(Input.GetKey)) { return; } if (Input.GetKeyDown(KeyboardShortcuts.ToggleDrawDebugVisualization)) { drawDebugVisualization = !drawDebugVisualization; } else if (Input.GetKeyDown(KeyboardShortcuts.ToggleOverrideRenderScale)) { overrideRenderViewportScale = !overrideRenderViewportScale; } else if (Input.GetKeyDown(KeyboardShortcuts.DecreaseOverrideRenderScaleLevel)) { overrideRenderViewportScaleLevel = ClampRenderScaleLevel(overrideRenderViewportScaleLevel - 1); } else if (Input.GetKeyDown(KeyboardShortcuts.IncreaseOverrideRenderScaleLevel)) { overrideRenderViewportScaleLevel = ClampRenderScaleLevel(overrideRenderViewportScaleLevel + 1); } } private void UpdateMSAALevel() { if (QualitySettings.antiAliasing != msaaLevel) { QualitySettings.antiAliasing = msaaLevel; } } #region Render scale methods private void UpdateRenderScaleLevels() { if (Mathf.Abs(previousMinimumRenderScale - minimumRenderScale) <= float.Epsilon && Mathf.Abs(previousMaximumRenderScale - maximumRenderScale) <= float.Epsilon && Mathf.Abs(previousRenderScaleFillRateStepSizeInPercent - renderScaleFillRateStepSizeInPercent) <= float.Epsilon) { return; } previousMinimumRenderScale = minimumRenderScale; previousMaximumRenderScale = maximumRenderScale; previousRenderScaleFillRateStepSizeInPercent = renderScaleFillRateStepSizeInPercent; allRenderScales.Clear(); // Respect maximumRenderTargetDimension float allowedMaximumRenderScale = BiggestAllowedMaximumRenderScale(); float renderScaleToAdd = Mathf.Min(minimumRenderScale, allowedMaximumRenderScale); // Add min scale as the reprojection scale allRenderScales.Add(renderScaleToAdd); // Add all entries while (renderScaleToAdd <= maximumRenderScale) { allRenderScales.Add(renderScaleToAdd); renderScaleToAdd = Mathf.Sqrt((renderScaleFillRateStepSizeInPercent + 100) / 100.0f * renderScaleToAdd * renderScaleToAdd); if (renderScaleToAdd > allowedMaximumRenderScale) { // Too large break; } } // Figure out default render viewport scale level for debug visualization defaultRenderViewportScaleLevel = Mathf.Clamp( allRenderScales.FindIndex(renderScale => renderScale >= 1.0f), 1, allRenderScales.Count - 1); renderViewportScaleSetting.currentValue = defaultRenderViewportScaleLevel; renderScaleSetting.currentValue = defaultRenderViewportScaleLevel; overrideRenderViewportScaleLevel = ClampRenderScaleLevel(overrideRenderViewportScaleLevel); } private void UpdateRenderScale() { if (!scaleRenderViewport) { renderViewportScaleSetting.currentValue = defaultRenderViewportScaleLevel; renderScaleSetting.currentValue = defaultRenderViewportScaleLevel; SetRenderScale(1.0f, 1.0f); return; } // Rendering in low resolution means adaptive quality needs to scale back the render scale target to free up gpu cycles bool renderInLowResolution = VRTK_SDK_Bridge.ShouldAppRenderWithLowResources(); // Thresholds float allowedSingleFrameDurationInMilliseconds = renderInLowResolution ? singleFrameDurationInMilliseconds * 0.75f : singleFrameDurationInMilliseconds; float lowThresholdInMilliseconds = 0.7f * allowedSingleFrameDurationInMilliseconds; float extrapolationThresholdInMilliseconds = 0.85f * allowedSingleFrameDurationInMilliseconds; float highThresholdInMilliseconds = 0.9f * allowedSingleFrameDurationInMilliseconds; int newRenderViewportScaleLevel = renderViewportScaleSetting.currentValue; // Rapidly reduce render viewport scale level if cost of last 1 or 3 frames, or the predicted next frame's cost are expensive if (timing.WasFrameTimingBad( 1, highThresholdInMilliseconds, renderViewportScaleSetting.lastChangeFrameCount, renderViewportScaleSetting.decreaseFrameCost) || timing.WasFrameTimingBad( 3, highThresholdInMilliseconds, renderViewportScaleSetting.lastChangeFrameCount, renderViewportScaleSetting.decreaseFrameCost) || timing.WillFrameTimingBeBad( extrapolationThresholdInMilliseconds, highThresholdInMilliseconds, renderViewportScaleSetting.lastChangeFrameCount, renderViewportScaleSetting.decreaseFrameCost)) { // Always drop 2 levels except when dropping from level 2 (level 0 is for reprojection) newRenderViewportScaleLevel = ClampRenderScaleLevel(renderViewportScaleSetting.currentValue == 2 ? 1 : renderViewportScaleSetting.currentValue - 2); } // Rapidly increase render viewport scale level if last 12 frames are cheap else if (timing.WasFrameTimingGood( 12, lowThresholdInMilliseconds, renderViewportScaleSetting.lastChangeFrameCount - renderViewportScaleSetting.increaseFrameCost, renderViewportScaleSetting.increaseFrameCost)) { newRenderViewportScaleLevel = ClampRenderScaleLevel(renderViewportScaleSetting.currentValue + 2); } // Slowly increase render viewport scale level if last 6 frames are cheap else if (timing.WasFrameTimingGood( 6, lowThresholdInMilliseconds, renderViewportScaleSetting.lastChangeFrameCount, renderViewportScaleSetting.increaseFrameCost)) { // Only increase by 1 level to prevent frame drops caused by adjusting newRenderViewportScaleLevel = ClampRenderScaleLevel(renderViewportScaleSetting.currentValue + 1); } // Apply and remember when render viewport scale level changed if (newRenderViewportScaleLevel != renderViewportScaleSetting.currentValue) { if (renderViewportScaleSetting.currentValue >= renderScaleSetting.currentValue && newRenderViewportScaleLevel < renderScaleSetting.currentValue) { lastRenderViewportScaleLevelBelowRenderScaleLevelFrameCount = Time.frameCount; } renderViewportScaleSetting.currentValue = newRenderViewportScaleLevel; } // Ignore frame timings if overriding if (overrideRenderViewportScale) { renderViewportScaleSetting.currentValue = overrideRenderViewportScaleLevel; } // Force on interleaved reprojection for level 0 which is just a replica of level 1 with reprojection enabled float additionalViewportScale = 1.0f; if (!hmdDisplayIsOnDesktop) { if (renderViewportScaleSetting.currentValue == 0) { if (interleavedReprojectionEnabled && timing.GetFrameTiming(0) < singleFrameDurationInMilliseconds * 0.85f) { interleavedReprojectionEnabled = false; } else if (timing.GetFrameTiming(0) > singleFrameDurationInMilliseconds * 0.925f) { interleavedReprojectionEnabled = true; } } else { interleavedReprojectionEnabled = false; } VRTK_SDK_Bridge.ForceInterleavedReprojectionOn(interleavedReprojectionEnabled); } // Not running in direct mode! Interleaved reprojection not supported, so scale down the viewport some more else if (renderViewportScaleSetting.currentValue == 0) { additionalViewportScale = 0.8f; } int newRenderScaleLevel = renderScaleSetting.currentValue; int levelInBetween = (renderViewportScaleSetting.currentValue - renderScaleSetting.currentValue) / 2; // Increase render scale level to the level in between if (renderScaleSetting.currentValue < renderViewportScaleSetting.currentValue && Time.frameCount >= renderScaleSetting.lastChangeFrameCount + renderScaleSetting.increaseFrameCost) { newRenderScaleLevel = ClampRenderScaleLevel(renderScaleSetting.currentValue + Mathf.Max(1, levelInBetween)); } // Decrease render scale level else if (renderScaleSetting.currentValue > renderViewportScaleSetting.currentValue && Time.frameCount >= renderScaleSetting.lastChangeFrameCount + renderScaleSetting.decreaseFrameCost && Time.frameCount >= lastRenderViewportScaleLevelBelowRenderScaleLevelFrameCount + renderViewportScaleSetting.increaseFrameCost) { // Slowly decrease render scale level to level in between if last 6 frames are cheap, otherwise rapidly newRenderScaleLevel = timing.WasFrameTimingGood(6, lowThresholdInMilliseconds, 0, 0) ? ClampRenderScaleLevel(renderScaleSetting.currentValue + Mathf.Min(-1, levelInBetween)) : renderViewportScaleSetting.currentValue; } // Apply and remember when render scale level changed renderScaleSetting.currentValue = newRenderScaleLevel; if (!scaleRenderTargetResolution) { renderScaleSetting.currentValue = allRenderScales.Count - 1; } float newRenderScale = allRenderScales[renderScaleSetting.currentValue]; float newRenderViewportScale = allRenderScales[Mathf.Min(renderViewportScaleSetting.currentValue, renderScaleSetting.currentValue)] / newRenderScale * additionalViewportScale; SetRenderScale(newRenderScale, newRenderViewportScale); } private static void SetRenderScale(float renderScale, float renderViewportScale) { if (Mathf.Abs(VRSettings.renderScale - renderScale) > float.Epsilon) { VRSettings.renderScale = renderScale; } if (Mathf.Abs(VRSettings.renderViewportScale - renderViewportScale) > float.Epsilon) { VRSettings.renderViewportScale = renderViewportScale; } } private int ClampRenderScaleLevel(int renderScaleLevel) { return Mathf.Clamp(renderScaleLevel, 0, allRenderScales.Count - 1); } #endregion #region Debug visualization methods private void CreateOrDestroyDebugVisualization() { if (!Application.isPlaying) { return; } if (enabled && drawDebugVisualization && debugVisualizationQuad == null) { var mesh = new Mesh { vertices = new[] { new Vector3(-0.5f, 0.9f, 1.0f), new Vector3(-0.5f, 1.0f, 1.0f), new Vector3(0.5f, 1.0f, 1.0f), new Vector3(0.5f, 0.9f, 1.0f) }, uv = new[] { new Vector2(0.0f, 0.0f), new Vector2(0.0f, 1.0f), new Vector2(1.0f, 1.0f), new Vector2(1.0f, 0.0f) }, triangles = new[] { 0, 1, 2, 0, 2, 3 } }; #if !UNITY_5_5_OR_NEWER mesh.Optimize(); #endif mesh.UploadMeshData(true); debugVisualizationQuad = new GameObject(VRTK_SharedMethods.GenerateVRTKObjectName(true, "AdaptiveQualityDebugVisualizationQuad")); if (VRTK_SDKManager.instance) { debugVisualizationQuad.transform.SetParent(VRTK_DeviceFinder.HeadsetTransform()); } debugVisualizationQuad.transform.localPosition = Vector3.forward; debugVisualizationQuad.transform.localRotation = Quaternion.identity; debugVisualizationQuad.AddComponent<MeshFilter>().mesh = mesh; debugVisualizationQuadMaterial = Resources.Load<Material>("AdaptiveQualityDebugVisualization"); debugVisualizationQuad.AddComponent<MeshRenderer>().material = debugVisualizationQuadMaterial; } else if ((!enabled || !drawDebugVisualization) && debugVisualizationQuad != null) { Destroy(debugVisualizationQuad); debugVisualizationQuad = null; debugVisualizationQuadMaterial = null; } } private void UpdateDebugVisualization() { if (!drawDebugVisualization || debugVisualizationQuadMaterial == null) { return; } int lastFrameIsInBudget = (interleavedReprojectionEnabled || VRTK_SharedMethods.GetGPUTimeLastFrame() > singleFrameDurationInMilliseconds ? 0 : 1); debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.RenderScaleLevelsCount, allRenderScales.Count); debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.DefaultRenderViewportScaleLevel, defaultRenderViewportScaleLevel); debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.CurrentRenderViewportScaleLevel, renderViewportScaleSetting.currentValue); debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.CurrentRenderScaleLevel, renderScaleSetting.currentValue); debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.LastFrameIsInBudget, lastFrameIsInBudget); } #endregion #region Private helper classes private sealed class AdaptiveSetting<T> { public T currentValue { get { return _currentValue; } set { if (!EqualityComparer<T>.Default.Equals(value, _currentValue)) { lastChangeFrameCount = Time.frameCount; } previousValue = _currentValue; _currentValue = value; } } public T previousValue { get; private set; } public int lastChangeFrameCount { get; private set; } public readonly int increaseFrameCost; public readonly int decreaseFrameCost; private T _currentValue; public AdaptiveSetting(T currentValue, int increaseFrameCost, int decreaseFrameCost) { previousValue = currentValue; this.currentValue = currentValue; this.increaseFrameCost = increaseFrameCost; this.decreaseFrameCost = decreaseFrameCost; } } private static class CommandLineArguments { public const string Disable = "-noaq"; public const string MinimumRenderScale = "-aqminscale"; public const string MaximumRenderScale = "-aqmaxscale"; public const string MaximumRenderTargetDimension = "-aqmaxres"; public const string RenderScaleFillRateStepSizeInPercent = "-aqfillratestep"; public const string OverrideRenderScaleLevel = "-aqoverride"; public const string DrawDebugVisualization = "-vrdebug"; public const string MSAALevel = "-msaa"; } private static class KeyboardShortcuts { public static readonly KeyCode[] Modifiers = { KeyCode.LeftShift, KeyCode.RightShift }; public const KeyCode ToggleDrawDebugVisualization = KeyCode.F1; public const KeyCode ToggleOverrideRenderScale = KeyCode.F2; public const KeyCode DecreaseOverrideRenderScaleLevel = KeyCode.F3; public const KeyCode IncreaseOverrideRenderScaleLevel = KeyCode.F4; } private static class ShaderPropertyIDs { public static readonly int RenderScaleLevelsCount = Shader.PropertyToID("_RenderScaleLevelsCount"); public static readonly int DefaultRenderViewportScaleLevel = Shader.PropertyToID("_DefaultRenderViewportScaleLevel"); public static readonly int CurrentRenderViewportScaleLevel = Shader.PropertyToID("_CurrentRenderViewportScaleLevel"); public static readonly int CurrentRenderScaleLevel = Shader.PropertyToID("_CurrentRenderScaleLevel"); public static readonly int LastFrameIsInBudget = Shader.PropertyToID("_LastFrameIsInBudget"); } private sealed class Timing { private readonly float[] buffer = new float[12]; private int bufferIndex; public void SaveCurrentFrameTiming() { bufferIndex = (bufferIndex + 1) % buffer.Length; buffer[bufferIndex] = VRTK_SharedMethods.GetGPUTimeLastFrame(); } public float GetFrameTiming(int framesAgo) { return buffer[(bufferIndex - framesAgo + buffer.Length) % buffer.Length]; } public bool WasFrameTimingBad(int framesAgo, float thresholdInMilliseconds, int lastChangeFrameCount, int changeFrameCost) { if (!AreFramesAvailable(framesAgo, lastChangeFrameCount, changeFrameCost)) { // Too early to know return false; } for (int frame = 0; frame < framesAgo; frame++) { if (GetFrameTiming(frame) <= thresholdInMilliseconds) { return false; } } return true; } public bool WasFrameTimingGood(int framesAgo, float thresholdInMilliseconds, int lastChangeFrameCount, int changeFrameCost) { if (!AreFramesAvailable(framesAgo, lastChangeFrameCount, changeFrameCost)) { // Too early to know return false; } for (int frame = 0; frame < framesAgo; frame++) { if (GetFrameTiming(frame) > thresholdInMilliseconds) { return false; } } return true; } public bool WillFrameTimingBeBad(float extrapolationThresholdInMilliseconds, float thresholdInMilliseconds, int lastChangeFrameCount, int changeFrameCost) { if (!AreFramesAvailable(2, lastChangeFrameCount, changeFrameCost)) { // Too early to know return false; } // Predict next frame's cost using linear extrapolation: max(frame-1 to frame+1, frame-2 to frame+1) float frameMinus0Timing = GetFrameTiming(0); if (frameMinus0Timing <= extrapolationThresholdInMilliseconds) { return false; } float delta = frameMinus0Timing - GetFrameTiming(1); if (!AreFramesAvailable(3, lastChangeFrameCount, changeFrameCost)) { delta = Mathf.Max(delta, (frameMinus0Timing - GetFrameTiming(2)) / 2f); } return frameMinus0Timing + delta > thresholdInMilliseconds; } private static bool AreFramesAvailable(int framesAgo, int lastChangeFrameCount, int changeFrameCost) { return Time.frameCount >= framesAgo + lastChangeFrameCount + changeFrameCost; } } #endregion } } #endif
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using SIL.CommandLineProcessing; using SIL.IO; using SIL.PlatformUtilities; using SIL.Progress; namespace SIL.Media { ///<summary> /// FFmpeg is an open source media processing commandline library ///</summary> public class FFmpegRunner { /// <summary> /// If your app knows where FFMPEG lives, you can tell us before making any calls. /// </summary> public static string FFmpegLocation; /// <summary> /// Find the path to ffmpeg, and remember it (some apps (like SayMore) call ffmpeg a lot) /// </summary> /// <returns></returns> static internal string LocateAndRememberFFmpeg() { if (null != FFmpegLocation) //NO! string.empty means we looked and didn't find: string.IsNullOrEmpty(s_ffmpegLocation)) return FFmpegLocation; FFmpegLocation = LocateFFmpeg(); return FFmpegLocation; } /// <summary> /// ffmpeg is more of a "compile it yourself" thing, and yet /// SIL doesn't necessarily want to be redistributing something /// which may violate software patents (e.g. mp3) in certain countries, so /// we ask users to get it themselves. /// See: http://www.ffmpeg.org/legal.html /// This tries to find where they put it. /// </summary> /// <returns>the path, if found, else null</returns> static private string LocateFFmpeg() { if (Platform.IsLinux) { //on linux, we can safely assume the package has included the needed dependency if (File.Exists("/usr/bin/ffmpeg")) return "/usr/bin/ffmpeg"; if (File.Exists("/usr/bin/avconv")) return "/usr/bin/avconv"; // the new name of ffmpeg on Linux return null; } string withApplicationDirectory = GetPathToBundledFFmpeg(); if (!string.IsNullOrEmpty(withApplicationDirectory) && File.Exists(withApplicationDirectory)) return withApplicationDirectory; var progFileDirs = new List<string> { Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) }; /* We DON't SUPPORT THIS ONE (it lacks some information on the output, at least as of * Julu 2010) //from http://www.arachneweb.co.uk/software/windows/avchdview/ffmpeg.html foreach (var path in progFileDirs) { var exePath = (Path.Combine(path, "ffmpeg/win32-static/bin/ffmpeg.exe")); if(File.Exists(exePath)) return exePath; } */ //http://manual.audacityteam.org/index.php?title=FAQ:Installation_and_Plug-Ins#installffmpeg foreach (var path in progFileDirs) { var exePath = (Path.Combine(path, "FFmpeg for Audacity/ffmpeg.exe")); if (File.Exists(exePath)) return exePath; } return string.Empty; } private static string GetPathToBundledFFmpeg() { try { return FileLocationUtilities.GetFileDistributedWithApplication("ffmpeg", "ffmpeg.exe"); } catch (Exception) { return string.Empty; } } ///<summary> /// Returns false if it can't find ffmpeg ///</summary> static public bool HaveNecessaryComponents { get { return !string.IsNullOrEmpty(LocateFFmpeg()); } } ///<summary> /// Returns false if it can't find ffmpeg ///</summary> static private bool HaveValidFFMpegOnPath { get { if (Platform.IsWindows) { if (!string.IsNullOrEmpty(LocateFFmpeg())) return true; } //see if there is one on the %path% var p = new Process(); p.StartInfo.FileName = "ffmpeg"; p.StartInfo.RedirectStandardError = true; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; try { p.Start(); } catch (Exception) { return false; } return true; } } /// <summary> /// Extracts the audio from a video. Note, it will fail if the file exists, so the client /// is resonsible for verifying with the user and deleting the file before calling this. /// </summary> /// <param name="inputPath"></param> /// <param name="outputPath"></param> /// <param name="channels">1 for mono, 2 for stereo</param> /// <param name="progress"></param> /// <returns>log of the run</returns> public static ExecutionResult ExtractMp3Audio(string inputPath, string outputPath, int channels, IProgress progress) { if (string.IsNullOrEmpty(LocateFFmpeg())) { return new ExecutionResult() { StandardError = "Could not locate FFMpeg" }; } var arguments = string.Format("-i \"{0}\" -vn -acodec libmp3lame -ac {1} \"{2}\"", inputPath, channels, outputPath); var result = CommandLineRunner.Run(LocateAndRememberFFmpeg(), arguments, Environment.CurrentDirectory, 60 * 10, //10 minutes progress ); progress.WriteVerbose(result.StandardOutput); //hide a meaningless error produced by some versions of liblame if (result.StandardError.Contains("lame: output buffer too small") && File.Exists(outputPath)) { var doctoredResult = new ExecutionResult { ExitCode = 0, StandardOutput = result.StandardOutput, StandardError = string.Empty }; return doctoredResult; } if (result.StandardError.ToLower().Contains("error")) //ffmpeg always outputs config info to standarderror progress.WriteError(result.StandardError); return result; } /// <summary> /// Extracts the audio from a video. Note, it will fail if the file exists, so the client /// is resonsible for verifying with the user and deleting the file before calling this. /// </summary> /// <param name="inputPath"></param> /// <param name="outputPath"></param> /// <param name="channels">1 for mono, 2 for stereo</param> /// <param name="progress"></param> /// <returns>log of the run</returns> public static ExecutionResult ExtractOggAudio(string inputPath, string outputPath, int channels, IProgress progress) { if (string.IsNullOrEmpty(LocateFFmpeg())) { return new ExecutionResult() { StandardError = "Could not locate FFMpeg" }; } var arguments = string.Format("-i \"{0}\" -vn -acodec vorbis -ac {1} \"{2}\"", inputPath, channels, outputPath); progress.WriteMessage("ffmpeg " + arguments); var result = CommandLineRunner.Run(LocateAndRememberFFmpeg(), arguments, Environment.CurrentDirectory, 60 * 10, //10 minutes progress ); progress.WriteVerbose(result.StandardOutput); //hide a meaningless error produced by some versions of liblame if (result.StandardError.Contains("lame: output buffer too small") && File.Exists(outputPath)) { var doctoredResult = new ExecutionResult { ExitCode = 0, StandardOutput = result.StandardOutput, StandardError = string.Empty }; return doctoredResult; } if (result.StandardError.ToLower().Contains("error")) //ffmpeg always outputs config info to standarderror progress.WriteError(result.StandardError); return result; } /// <summary> /// Extracts the audio from a video. Note, it will fail if the file exists, so the client /// is responsible for verifying with the user and deleting the file before calling this. /// </summary> /// <param name="inputPath"></param> /// <param name="outputPath"></param> /// <param name="channels">0 for same, 1 for mono, 2 for stereo</param> /// <param name="progress"></param> /// <returns>log of the run</returns> public static ExecutionResult ExtractBestQualityWavAudio(string inputPath, string outputPath, int channels, IProgress progress) { return ExtractAudio(inputPath, outputPath, "copy", 0, channels, progress); } /// <summary> /// Extracts the audio from a video. Note, it will fail if the file exists, so the client /// is responsible for verifying with the user and deleting the file before calling this. /// </summary> /// <param name="inputPath"></param> /// <param name="outputPath"></param> /// <param name="bitsPerSample">e.g. 8, 16, 24, 32</param> /// <param name="sampleRate">e.g. 22050, 44100, 4800</param> /// <param name="channels">0 for same, 1 for mono, 2 for stereo</param> /// <param name="progress"></param> /// <returns>log of the run</returns> public static ExecutionResult ExtractPcmAudio(string inputPath, string outputPath, int bitsPerSample, int sampleRate, int channels, IProgress progress) { var audioCodec = "copy"; switch (bitsPerSample) { case 8: audioCodec = "pcm_s8"; break; case 16: audioCodec = "pcm_s16le"; break; case 24: audioCodec = "pcm_s24le"; break; case 32: audioCodec = "pcm_s32le"; break; } return ExtractAudio(inputPath, outputPath, audioCodec, sampleRate, channels, progress); } /// <summary> /// Extracts the audio from a video. Note, it will fail if the file exists, so the client /// is responsible for verifying with the user and deleting the file before calling this. /// </summary> /// <param name="inputPath"></param> /// <param name="outputPath"></param> /// <param name="audioCodec">e.g. copy, pcm_s16le, pcm_s32le, etc.</param> /// <param name="sampleRate">e.g. 22050, 44100, 4800. Use 0 to use ffmpeg's default</param> /// <param name="channels">0 for same, 1 for mono, 2 for stereo</param> /// <param name="progress"></param> /// <returns>log of the run</returns> private static ExecutionResult ExtractAudio(string inputPath, string outputPath, string audioCodec, int sampleRate, int channels, IProgress progress) { if (string.IsNullOrEmpty(LocateFFmpeg())) { return new ExecutionResult() { StandardError = "Could not locate FFMpeg" }; } var sampleRateArg = ""; if (sampleRate > 0) sampleRateArg = string.Format("-ar {0}", sampleRate); //TODO: this will output whatever mp3 or wav or whatever is in the video... might not be wav at all! var channelsArg = ""; if (channels > 0) channelsArg = string.Format(" -ac {0}", channels); var arguments = string.Format("-i \"{0}\" -vn -acodec {1} {2} {3} \"{4}\"", inputPath, audioCodec, sampleRateArg, channelsArg, outputPath); progress.WriteMessage("ffmpeg " + arguments); var result = CommandLineRunner.Run(LocateAndRememberFFmpeg(), arguments, Environment.CurrentDirectory, 60 * 10, //10 minutes progress); progress.WriteVerbose(result.StandardOutput); //hide a meaningless error produced by some versions of liblame if (result.StandardError.Contains("lame: output buffer too small") && File.Exists(outputPath)) { var doctoredResult = new ExecutionResult { ExitCode = 0, StandardOutput = result.StandardOutput, StandardError = string.Empty }; return doctoredResult; } if (result.StandardError.ToLower().Contains("error")) //ffmpeg always outputs config info to standarderror progress.WriteError(result.StandardError); return result; } /// <summary> /// Creates an audio file, using the received one as the bases, with the specified number /// of channels. For example, this can be used to convert a 2-channel audio file to a /// single channel audio file. /// </summary> /// <returns>log of the run</returns> public static ExecutionResult ChangeNumberOfAudioChannels(string inputPath, string outputPath, int channels, IProgress progress) { if (string.IsNullOrEmpty(LocateFFmpeg())) return new ExecutionResult { StandardError = "Could not locate FFMpeg" }; var arguments = string.Format("-i \"{0}\" -vn -ac {1} \"{2}\"", inputPath, channels, outputPath); var result = CommandLineRunner.Run(LocateAndRememberFFmpeg(), arguments, Environment.CurrentDirectory, 60 * 10, //10 minutes progress); progress.WriteVerbose(result.StandardOutput); //hide a meaningless error produced by some versions of liblame if (result.StandardError.Contains("lame: output buffer too small") && File.Exists(outputPath)) { var doctoredResult = new ExecutionResult { ExitCode = 0, StandardOutput = result.StandardOutput, StandardError = string.Empty }; return doctoredResult; } // ffmpeg always outputs config info to standarderror if (result.StandardError.ToLower().Contains("error")) progress.WriteError(result.StandardError); return result; } /// <summary> /// Converts to low-quality, mono mp3 /// </summary> /// <returns>log of the run</returns> public static ExecutionResult MakeLowQualityCompressedAudio(string inputPath, string outputPath, IProgress progress) { if (string.IsNullOrEmpty(LocateAndRememberFFmpeg())) { return new ExecutionResult() { StandardError = "Could not locate FFMpeg" }; } var arguments = "-i \"" + inputPath + "\" -acodec libmp3lame -ac 1 -ar 8000 \"" + outputPath + "\""; progress.WriteMessage("ffmpeg " + arguments); var result = CommandLineRunner.Run(LocateAndRememberFFmpeg(), arguments, Environment.CurrentDirectory, 60 * 10, //10 minutes progress ); progress.WriteVerbose(result.StandardOutput); //hide a meaningless error produced by some versions of liblame if (result.StandardError.Contains("lame: output buffer too small") && File.Exists(outputPath)) { result = new ExecutionResult { ExitCode = 0, StandardOutput = result.StandardOutput, StandardError = string.Empty }; } if (result.StandardError.ToLower().Contains("error") || result.StandardError.ToLower().Contains("unable to") || result.StandardError.ToLower().Contains("invalid") || result.StandardError.ToLower().Contains("could not") ) //ffmpeg always outputs config info to standarderror progress.WriteError(result.StandardError); return result; } /// <summary> /// Converts to low-quality, small video /// </summary> /// <param name="inputPath">file location for original file</param> /// <param name="outputPath">file location for converted file</param> /// <param name="maxSeconds">0 if you don't want to truncate at all</param> /// <param name="progress">progress bar</param> /// <returns>log of the run</returns> public static ExecutionResult MakeLowQualitySmallVideo(string inputPath, string outputPath, int maxSeconds, IProgress progress) { if (string.IsNullOrEmpty(LocateAndRememberFFmpeg())) { return new ExecutionResult() { StandardError = "Could not locate FFMpeg" }; } // isn't working: var arguments = "-i \"" + inputPath + "\" -vcodec mpeg4 -s 160x120 -b 800 -acodec libmp3lame -ar 22050 -ab 32k -ac 1 \"" + outputPath + "\""; var arguments = "-i \"" + inputPath + "\" -vcodec mpeg4 -s 160x120 -b 800 -acodec libmp3lame -ar 22050 -ab 32k -ac 1 "; if (maxSeconds > 0) arguments += " -t " + maxSeconds + " "; arguments += "\"" + outputPath + "\""; progress.WriteMessage("ffmpeg " + arguments); var result = CommandLineRunner.Run(LocateAndRememberFFmpeg(), arguments, Environment.CurrentDirectory, 60 * 10, //10 minutes progress ); progress.WriteVerbose(result.StandardOutput); //hide a meaningless error produced by some versions of liblame if (result.StandardError.Contains("lame: output buffer too small") && File.Exists(outputPath)) { result = new ExecutionResult { ExitCode = 0, StandardOutput = result.StandardOutput, StandardError = string.Empty }; } if (result.StandardError.ToLower().Contains("error") //ffmpeg always outputs config info to standarderror || result.StandardError.ToLower().Contains("unable to") || result.StandardError.ToLower().Contains("invalid") || result.StandardError.ToLower().Contains("could not")) progress.WriteWarning(result.StandardError); return result; } /// <summary> /// Converts to low-quality, small picture /// </summary> /// <returns>log of the run</returns> public static ExecutionResult MakeLowQualitySmallPicture(string inputPath, string outputPath, IProgress progress) { if (string.IsNullOrEmpty(LocateAndRememberFFmpeg())) { return new ExecutionResult() { StandardError = "Could not locate FFMpeg" }; } //enhance: how to lower the quality? var arguments = "-i \"" + inputPath + "\" -f image2 -s 176x144 \"" + outputPath + "\""; progress.WriteMessage("ffmpeg " + arguments); var result = CommandLineRunner.Run(LocateAndRememberFFmpeg(), arguments, Environment.CurrentDirectory, 60 * 10, //10 minutes progress ); progress.WriteVerbose(result.StandardOutput); if (result.StandardError.ToLower().Contains("error")) //ffmpeg always outputs config info to standarderror progress.WriteError(result.StandardError); return result; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Linq; using System.Collections.Generic; using System.Security.Cryptography; using Microsoft.Azure.Test.HttpRecorder; using System.Security.Cryptography.X509Certificates; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System.Net; using Microsoft.Azure.Graph.RBAC.Models; using System.Threading; using Microsoft.Rest.Azure.OData; namespace Microsoft.Azure.Graph.RBAC.Tests { public class TenantAndDomain { public TenantAndDomain() { } public TenantAndDomain(string t, string d) { TenantId = t; Domain = d; } public string TenantId { get; set; } public string Domain { get; set; } } public class GraphTestBase : TestBase { public const string TenantIdKey = "TenantId"; public const string DomainKey = "Domain"; public TenantAndDomain GetTenantAndDomain() { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); TenantAndDomain result = new TenantAndDomain(); if (HttpMockServer.Mode == HttpRecorderMode.Record) { var environment = TestEnvironmentFactory.GetTestEnvironment(); result.TenantId = environment.Tenant; if (!string.IsNullOrEmpty(environment.UserName)) { result.Domain = environment.UserName .Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries) .Last(); } HttpMockServer.Variables[TenantIdKey] = result.TenantId; if (!string.IsNullOrEmpty(result.Domain)) { HttpMockServer.Variables[DomainKey] = result.Domain; } } else if (HttpMockServer.Mode == HttpRecorderMode.Playback) { result.TenantId = HttpMockServer.Variables[TenantIdKey]; if (HttpMockServer.Variables.ContainsKey(DomainKey)) { result.Domain = HttpMockServer.Variables[DomainKey]; } } return result; } public GraphRbacManagementClient GetGraphClient(MockContext context, RecordedDelegatingHandler handler = null) { if (handler != null) { handler.IsPassThrough = true; } var client = handler == null ? context.GetGraphServiceClient<GraphRbacManagementClient>() : context.GetGraphServiceClient<GraphRbacManagementClient>(handlers: handler); client.TenantID = GetTenantAndDomain().TenantId; return client; } public KeyCredential CreateKeyCredential(string keyId = null) { X509Certificate applicationCertificate = new X509Certificate("SampleApplicationCredential.cer"); KeyCredential cred = new KeyCredential(); cred.StartDate = DateTime.Now; cred.EndDate = DateTime.Now.AddMonths(12); cred.KeyId = keyId ?? Guid.NewGuid().ToString(); cred.Value = Convert.ToBase64String(applicationCertificate.Export(X509ContentType.Cert)); cred.Type = "AsymmetricX509Cert"; cred.Usage = "Verify"; return cred; } public PasswordCredential CreatePasswordCredential(string keyId = null) { var bytes = new byte[32] { 1, 2 ,3 , 4, 5, 6, 7, 8, 9, 10, 1, 2 ,3 , 4, 5, 6, 7, 8, 9, 10, 1, 2 ,3 , 4, 5, 6, 7, 8, 9, 10, 1, 2 }; PasswordCredential cred = new PasswordCredential(); cred.StartDate = DateTime.Now; cred.EndDate = DateTime.Now.AddMonths(12); cred.KeyId = keyId ?? Guid.NewGuid().ToString(); cred.Value = Convert.ToBase64String(bytes); return cred; } public void UpdateAppKeyCredential(MockContext context, string appObjectId, KeyCredential credential) { GetGraphClient(context).Applications.UpdateKeyCredentials(appObjectId, new KeyCredentialsUpdateParameters(new List<KeyCredential>() { credential })); } public void UpdateAppKeyCredential(MockContext context, string appObjectId, List<KeyCredential> credentials) { GetGraphClient(context).Applications.UpdateKeyCredentials(appObjectId, new KeyCredentialsUpdateParameters(credentials)); } public void UpdateAppPasswordCredential(MockContext context, string appObjectId, PasswordCredential credential) { GetGraphClient(context).Applications.UpdatePasswordCredentials(appObjectId, new PasswordCredentialsUpdateParameters(new List<PasswordCredential>() { credential })); } public void UpdateAppPasswordCredential(MockContext context, string appObjectId, List<PasswordCredential> credentials) { GetGraphClient(context).Applications.UpdatePasswordCredentials(appObjectId, new PasswordCredentialsUpdateParameters(credentials)); } public void UpdateSpKeyCredential(MockContext context, string spObjectId, KeyCredential credential) { GetGraphClient(context).ServicePrincipals.UpdateKeyCredentials(spObjectId, new KeyCredentialsUpdateParameters(new List<KeyCredential>() { credential })); } public void UpdateSpKeyCredential(MockContext context, string spObjectId, List<KeyCredential> credentials) { GetGraphClient(context).ServicePrincipals.UpdateKeyCredentials(spObjectId, new KeyCredentialsUpdateParameters(credentials)); } public void UpdateSpPasswordCredential(MockContext context, string spObjectId, PasswordCredential credential) { GetGraphClient(context).ServicePrincipals.UpdatePasswordCredentials(spObjectId, new PasswordCredentialsUpdateParameters(new List<PasswordCredential>() { credential })); } public void UpdateSpPasswordCredential(MockContext context, string spObjectId, List<PasswordCredential> credentials) { GetGraphClient(context).ServicePrincipals.UpdatePasswordCredentials(spObjectId, new PasswordCredentialsUpdateParameters(credentials)); } public List<KeyCredential> GetAppKeyCredential(MockContext context, string appObjectId) { return GetGraphClient(context).Applications.ListKeyCredentials(appObjectId).ToList(); } public List<PasswordCredential> GetAppPasswordCredential(MockContext context, string appObjectId) { return GetGraphClient(context).Applications.ListPasswordCredentials(appObjectId).ToList(); } public List<KeyCredential> GetSpKeyCredential(MockContext context, string spObjectId) { return GetGraphClient(context).ServicePrincipals.ListKeyCredentials(spObjectId).ToList(); } public List<PasswordCredential> GetSpPasswordCredential(MockContext context, string spObjectId) { return GetGraphClient(context).ServicePrincipals.ListPasswordCredentials(spObjectId).ToList(); } public Application CreateApplication(MockContext context, PasswordCredential passwordCredential = null, KeyCredential keyCredential = null) { var appName = TestUtilities.GenerateName("adApplication"); var url = string.Format("http://{0}/home", appName); var parameters = new ApplicationCreateParameters(); parameters.AvailableToOtherTenants = false; parameters.DisplayName = appName; parameters.Homepage = url; parameters.IdentifierUris = new[] { url }; parameters.ReplyUrls = new[] { url }; if (passwordCredential != null) { parameters.PasswordCredentials = new PasswordCredential[] { passwordCredential }; } if(keyCredential != null) { parameters.KeyCredentials = new KeyCredential[] { keyCredential }; } return GetGraphClient(context).Applications.Create(parameters); } public string GetServicePrincipalsIdByAppId(MockContext context, Application application) { return GetGraphClient(context).Applications.GetServicePrincipalsIdByAppId(application.AppId).Value; } public void UpdateApplication(MockContext context, string applicaitonObjectId, string newDisplayName = null, string newIdentifierUri = null, PasswordCredential passwordCredential = null, KeyCredential keyCredential = null) { var parameters = new ApplicationUpdateParameters(); parameters.DisplayName = newDisplayName; if (!string.IsNullOrEmpty(newIdentifierUri)) { parameters.IdentifierUris = new[] { newIdentifierUri }; } if (passwordCredential != null) { parameters.PasswordCredentials = new PasswordCredential[] { passwordCredential }; } if (keyCredential != null) { parameters.KeyCredentials = new KeyCredential[] { keyCredential }; } GetGraphClient(context).Applications.Patch(applicaitonObjectId, parameters); } public void DeleteApplication(MockContext context, string appObjectId) { GetGraphClient(context).Applications.Delete(appObjectId); } public Application GetApplicationByObjectId(MockContext context, string appObjectId) { return GetGraphClient(context).Applications.Get(appObjectId); } public IEnumerable<Application> SearchApplication(MockContext context, ODataQuery<Application> odataQuery) { return GetGraphClient(context).Applications.List(odataQuery); } public ServicePrincipal CreateServicePrincipal(MockContext context, string appId) { var parameters = new ServicePrincipalCreateParameters { AccountEnabled = Boolean.Parse(bool.TrueString), AppId = appId }; return GetGraphClient(context).ServicePrincipals.Create(parameters); } public void DeleteServicePrincipal(MockContext context, string spObjectId) { GetGraphClient(context).ServicePrincipals.Delete(spObjectId); } public void SearchServicePrincipal(MockContext context, string spObjectId) { GetGraphClient(context).ServicePrincipals.Get(spObjectId); } public User CreateUser(MockContext context) { string username = TestUtilities.GenerateName("aduser"); string upn = username + "@" + GetTenantAndDomain().Domain; UserCreateParameters parameter = new UserCreateParameters(); parameter.UserPrincipalName = upn; parameter.DisplayName = username; parameter.AccountEnabled = true; parameter.MailNickname = username + "test"; parameter.PasswordProfile = new PasswordProfile(); parameter.PasswordProfile.ForceChangePasswordNextLogin = false; parameter.PasswordProfile.Password = "Test12345"; return GetGraphClient(context).Users.Create(parameter); } public void DeleteUser(MockContext context, string upnOrObjectId) { GetGraphClient(context).Users.Delete(upnOrObjectId); } public void SearchUser(MockContext context, string upnOrObjectId) { GetGraphClient(context).Users.Get(upnOrObjectId); } public ADGroup CreateGroup(MockContext context) { string groupname = TestUtilities.GenerateName("adgroup"); string mailNickName = groupname + "tester"; GroupCreateParameters parameters = new GroupCreateParameters(); parameters.DisplayName = groupname; parameters.MailNickname = mailNickName; return GetGraphClient(context).Groups.Create(parameters); } public void DeleteGroup(MockContext context, string objectId) { GetGraphClient(context).Groups.Delete(objectId); } public void SearchGroup(MockContext context, string objectId) { GetGraphClient(context).Groups.Get(objectId); } public void AddMember(MockContext context, ADGroup group, User user) { string memberUrl = string.Format("{0}{1}/directoryObjects/{2}", GetGraphClient(context).BaseUri.AbsoluteUri, GetGraphClient(context).TenantID, user.ObjectId); GetGraphClient(context).Groups.AddMember(group.ObjectId, new GroupAddMemberParameters(memberUrl)); } //return all groups the user is a member of (transitive) public IEnumerable<string> GetMemberGroups(MockContext context, User user) { return GetGraphClient(context).Users.GetMemberGroups(user.ObjectId, new UserGetMemberGroupsParameters(false)); } public void RemoveMember(MockContext context, ADGroup group, User user) { GetGraphClient(context).Groups.RemoveMember(group.ObjectId, user.ObjectId); } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using Matozap.Entities.Models.Generic; using Microsoft.Data.Entity.SqlServer.Metadata; namespace Matozap.Entities.Migrations { [DbContext(typeof(ApplicationContext))] partial class ApplicationContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .Annotation("ProductVersion", "7.0.0-beta7-15540") .Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn); modelBuilder.Entity("Matozap.Entities.Models.Custom.Actor", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<Guid>("MovieId"); b.Property<string>("Name") .Required(); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.Cinema", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name") .Required(); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.Country", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name") .Required(); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.Fixture", b => { b.Property<string>("Id"); b.Property<string>("AwayTeamId"); b.Property<string>("AwayTeamName"); b.Property<DateTime>("Date"); b.Property<int>("GoalsAwayTeam"); b.Property<int>("GoalsHomeTeam"); b.Property<string>("HomeTeamId"); b.Property<string>("HomeTeamName"); b.Property<int>("Matchday"); b.Property<string>("Status"); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.League", b => { b.Property<string>("Id"); b.Property<string>("Name") .Required(); b.Property<string>("Region"); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.LeagueTable", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Caption") .Required(); b.Property<int>("Matchday"); b.Property<int>("SeasonId"); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.LeagueTableStanding", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("GoalDifference"); b.Property<int>("Goals"); b.Property<int>("GoalsAgainst"); b.Property<int>("LeagueTableId"); b.Property<int>("PlayedGames"); b.Property<int>("Points"); b.Property<int>("Position"); b.Property<string>("TeamId"); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.Movie", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Director") .Required(); b.Property<DateTime>("ReleaseDate"); b.Property<decimal>("TicketPrice"); b.Property<string>("Title") .Required(); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.News", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Author"); b.Property<string>("Body"); b.Property<string>("ImageURL"); b.Property<string>("ReferenceURL"); b.Property<string>("Title") .Required(); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.Player", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("ContractUntil"); b.Property<DateTime>("DateOfBirth"); b.Property<string>("JerseryNumber"); b.Property<string>("MarketValue"); b.Property<string>("Name") .Required(); b.Property<string>("Nationality"); b.Property<string>("Position"); b.Property<string>("TeamId"); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.Season", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Caption") .Required(); b.Property<DateTime>("LastUpdated"); b.Property<string>("LeagueId"); b.Property<int>("NumberOfTeams"); b.Property<int>("Year"); b.Property<int>("numberOfGames"); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.SystemPreference", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Category"); b.Property<string>("Description"); b.Property<string>("Key") .Required() .Annotation("MaxLength", 500); b.Property<string>("Value") .Required(); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.Team", b => { b.Property<string>("Id"); b.Property<string>("Code"); b.Property<string>("CrestUrl"); b.Property<string>("Name") .Required(); b.Property<string>("ShortName"); b.Property<string>("SquadMarketValue"); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.UserPreference", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Category"); b.Property<string>("Description"); b.Property<string>("Key") .Required() .Annotation("MaxLength", 500); b.Property<int>("UserId"); b.Property<string>("Value") .Required(); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.UserProfile", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("BirthCountryCode"); b.Property<DateTime>("Birthday"); b.Property<string>("FistName") .Annotation("MaxLength", 250); b.Property<string>("Nickname") .Required() .Annotation("MaxLength", 250); b.Property<string>("Surname") .Annotation("MaxLength", 250); b.Property<int>("UserId"); b.Key("Id"); }); modelBuilder.Entity("Matozap.Entities.Models.Security.ApplicationRole", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken(); b.Property<bool>("Disabled"); b.Property<string>("Name") .Annotation("MaxLength", 256); b.Property<string>("NormalizedName") .Annotation("MaxLength", 256); b.Key("Id"); b.Index("NormalizedName") .Annotation("Relational:Name", "RoleNameIndex"); b.Annotation("Relational:TableName", "Roles"); }); modelBuilder.Entity("Matozap.Entities.Models.Security.ApplicationUser", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken(); b.Property<bool>("Disabled"); b.Property<string>("Email") .Annotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<string>("LastKnownIP"); b.Property<DateTime?>("LastLoginDate"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .Annotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .Annotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .Annotation("MaxLength", 256); b.Key("Id"); b.Index("NormalizedEmail") .Annotation("Relational:Name", "EmailIndex"); b.Index("NormalizedUserName") .Annotation("Relational:Name", "UserNameIndex"); b.Annotation("Relational:TableName", "Users"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<int>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<int>("RoleId"); b.Key("Id"); b.Annotation("Relational:TableName", "RoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<int>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<int>("UserId"); b.Key("Id"); b.Annotation("Relational:TableName", "UserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<int>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<int>("UserId"); b.Key("LoginProvider", "ProviderKey"); b.Annotation("Relational:TableName", "UserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<int>", b => { b.Property<int>("UserId"); b.Property<int>("RoleId"); b.Key("UserId", "RoleId"); b.Annotation("Relational:TableName", "UserRoles"); }); modelBuilder.Entity("Matozap.Entities.Models.Custom.Actor", b => { b.Reference("Matozap.Entities.Models.Custom.Movie") .InverseCollection() .ForeignKey("MovieId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<int>", b => { b.Reference("Matozap.Entities.Models.Security.ApplicationRole") .InverseCollection() .ForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<int>", b => { b.Reference("Matozap.Entities.Models.Security.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<int>", b => { b.Reference("Matozap.Entities.Models.Security.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<int>", b => { b.Reference("Matozap.Entities.Models.Security.ApplicationRole") .InverseCollection() .ForeignKey("RoleId"); b.Reference("Matozap.Entities.Models.Security.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. #nullable disable using System; using Scriban.Parsing; using Scriban.Runtime; namespace Scriban.Syntax { [ScriptSyntax("function statement", "func <variable> ... end")] #if SCRIBAN_PUBLIC public #else internal #endif partial class ScriptFunction : ScriptStatement, IScriptCustomFunction { private ScriptKeyword _funcToken; private ScriptNode _nameOrDoToken; private ScriptToken _openParen; private ScriptList<ScriptParameter> _parameters; private ScriptToken _closeParen; private ScriptToken _equalToken; private ScriptStatement _body; private bool _hasReturnType; private ScriptVarParamKind _varParamKind; private int _requiredParameterCount; public ScriptFunction() { _varParamKind = ScriptVarParamKind.Direct; } public ScriptKeyword FuncToken { get => _funcToken; set => ParentToThis(ref _funcToken, value); } public ScriptNode NameOrDoToken { get => _nameOrDoToken; set { if (value != null && (!(value is ScriptVariable || (value is ScriptKeyword token && token.Value == "do")))) { throw new ArgumentException($"Must be a {nameof(ScriptVariable)} or `do` {nameof(ScriptKeyword)}"); } ParentToThis(ref _nameOrDoToken, value); } } public ScriptToken OpenParen { get => _openParen; set => ParentToThis(ref _openParen, value); } public ScriptList<ScriptParameter> Parameters { get => _parameters; set { ParentToThis(ref _parameters, value); // Pre-calculate parameters _requiredParameterCount = _parameters?.Count ?? 0; _varParamKind = _parameters == null ? ScriptVarParamKind.Direct : ScriptVarParamKind.None; if (_parameters != null) { for (int i = 0; i < _parameters.Count; i++) { var param = _parameters[i]; var token = param.EqualOrTripleDotToken; if (token != null) { if (token.TokenType == TokenType.TripleDot) { _requiredParameterCount--; _varParamKind = ScriptVarParamKind.LastParameter; } if (token.TokenType == TokenType.Equal) { _requiredParameterCount--; } } } } } } public ScriptToken CloseParen { get => _closeParen; set => ParentToThis(ref _closeParen, value); } public ScriptToken EqualToken { get => _equalToken; set => ParentToThis(ref _equalToken, value); } public ScriptStatement Body { get => _body; set { ParentToThis(ref _body, value); UpdateReturnType(); } } public void UpdateReturnType() { _hasReturnType = Body is ScriptExpressionStatement || FindRetVisitor.HasRet(Body); } public bool IsAnonymous => !(NameOrDoToken is ScriptVariable); public bool HasParameters => Parameters != null; public override object Evaluate(TemplateContext context) { if (NameOrDoToken is ScriptVariable variable) { context.SetValue(variable, this); return null; } else { return this; } } public override bool CanHaveLeadingTrivia() { return NameOrDoToken != null; } public override void PrintTo(ScriptPrinter printer) { if (!IsAnonymous && Body is ScriptBlockStatement) { printer.Write(FuncToken).ExpectSpace(); } printer.Write(NameOrDoToken); if (OpenParen != null) printer.Write(OpenParen); if (HasParameters) { if (OpenParen != null) { printer.WriteListWithCommas(Parameters); } else { for (var i = 0; i < Parameters.Count; i++) { var param = Parameters[i]; if (i > 0) { printer.ExpectSpace(); } printer.Write(param); } } } if (CloseParen != null) printer.Write(CloseParen); if (Body is ScriptBlockStatement) { printer.ExpectEos(); printer.Write(Body); } else { printer.Write(EqualToken); printer.Write(Body); } if (!IsAnonymous) { printer.ExpectEos(); } } public object Invoke(TemplateContext context, ScriptNode callerContext, ScriptArray arguments, ScriptBlockStatement blockStatement) { bool hasParams = HasParameters; if (hasParams) { context.PushGlobal(new ScriptObject()); } else { context.PushLocal(); } try { if (NameOrDoToken is ScriptVariableLocal localVariable) { context.SetValue(localVariable, this); } context.SetValue(ScriptVariable.Arguments, arguments, true); if (hasParams) { var glob = context.CurrentGlobal; for (var i = 0; i < Parameters.Count; i++) { var param = Parameters[i]; glob.SetValue(param.Name.Name, arguments[i], false); } } // Set the block delegate if (blockStatement != null) { context.SetValue(ScriptVariable.BlockDelegate, blockStatement, true); } var result = context.Evaluate(Body); //if the result of the evaluation was a ScriptRange that depended on local variables //then we need to force the deferred enumerable inside the range to be evaluated right now //before we pop the variables out of the context! if (result is ScriptRange range) result = new ScriptArray(range); return result; } finally { if (hasParams) { context.PopGlobal(); } else { context.PopLocal(); } } } public int RequiredParameterCount => _requiredParameterCount; public int ParameterCount => Parameters?.Count ?? 0; public ScriptVarParamKind VarParamKind => _varParamKind; public Type ReturnType => _hasReturnType ? typeof(object) : typeof(void); public ScriptParameterInfo GetParameterInfo(int index) { if (Parameters == null) return new ScriptParameterInfo(typeof(object), string.Empty); var parameterCount = ParameterCount; if (index > parameterCount - 1) { index = parameterCount - 1; } var param = Parameters[index]; var name = param.Name.Name; var defaultValue = param.DefaultValue?.Value; return defaultValue != null ? new ScriptParameterInfo(typeof(object), name, defaultValue) : new ScriptParameterInfo(typeof(object), name); } /// <summary> /// Finds a <see cref="ScriptReturnStatement"/> in a tree. /// TODO: could be provided as a generic version /// </summary> private class FindRetVisitor : ScriptVisitor { [ThreadStatic] private static FindRetVisitor _instance; private FindRetVisitor(){} public static bool HasRet(ScriptNode node) { if (node == null) return false; var local = _instance ??= new FindRetVisitor(); local.Found = false; local.Visit(node); return local.Found; } public bool Found { get; private set; } public override void Visit(ScriptReturnStatement node) { Found = true; } protected override void DefaultVisit(ScriptNode node) { if (Found) return; if (node == null) return; var childrenCount = node.ChildrenCount; for(int i = 0; i < childrenCount; i++) { var child = node.GetChildren(i); Visit(child); if (Found) return; // early exit if found } } } } }
using System; using System.Collections.Generic; using System.Linq; using TiltBrush; using UnityEngine; public sealed class GlTF_Accessor : GlTF_ReferencedObject { public enum Type { SCALAR, VEC2, VEC3, VEC4 } public enum ComponentType { BYTE = 5120, UNSIGNED_BYTE = 5121, SHORT = 5122, USHORT = 5123, UNSIGNED_INT = 5125, FLOAT = 5126 } static int GetSize(ComponentType t) { switch (t) { case ComponentType.UNSIGNED_BYTE: case ComponentType.BYTE: return 1; case ComponentType.SHORT: case ComponentType.USHORT: return 2; case ComponentType.UNSIGNED_INT: return 4; case ComponentType.FLOAT: return 4; default: throw new InvalidOperationException($"Unknown {t}"); } } // The inverse of GetTypeForNumComponents static int GetNumComponents(Type t) { switch (t) { case Type.SCALAR: return 1; case Type.VEC2: return 2; case Type.VEC3: return 3; case Type.VEC4: return 4; default: throw new InvalidOperationException($"Unknown {t}"); } } // The inverse of GetNumComponents public static Type GetTypeForNumComponents(int size) { switch (size) { case 1: return Type.SCALAR; case 2: return Type.VEC2; case 3: return Type.VEC3; case 4: return Type.VEC4; default: throw new InvalidOperationException($"Cannot convert size {size}"); } } /// Returns an accessor that uses a differenttype. /// This is useful if you want to create (for example) a VEC2 view of a buffer that holds VEC4s. /// If the type is smaller, you get a new accessor that uses the same bufferview /// If the type is the same, you get the same accessor back. /// If the type is bigger, you get an exception public static GlTF_Accessor CloneWithDifferentType( GlTF_Globals G, GlTF_Accessor fromAccessor, Type newType) { if (newType == fromAccessor.type) { return fromAccessor; } var ret = new GlTF_Accessor(G, fromAccessor, newType); G.accessors.Add(ret); return ret; } // Instance API public readonly GlTF_BufferView bufferView;// "bufferView": "bufferView_30", public int byteStride;// ": 12, // GL enum vals ": BYTE (5120), UNSIGNED_BYTE (5121), SHORT (5122), UNSIGNED_SHORT (5123), FLOAT // (5126) public readonly Type type = Type.SCALAR; public readonly ComponentType componentType; private readonly bool m_normalized; // These are only assigned in Populate(), and only the most-ancestral gets populated. // All cloned accessors inherit these from their ancestor. private int? count; private long? byteOffset; // The 2.0 spec has this to say about min/max: // "While these properties are not required for all accessor usages, there are cases when minimum // and maximum must be defined. Refer to other sections of this specification for details." // // "POSITION accessor must have min and max properties defined." // // "Animation Sampler's input accessor must have min and max properties defined." // // There are no other references to other cases where they're required) // Not changing these to nullables because it would be a total pain. private bool m_haveMinMax = false; private Vector4 maxFloat; private Vector4 minFloat; private int minInt; private int maxInt; private GlTF_Accessor m_clonedFrom; private GlTF_Accessor Ancestor { get { if (m_clonedFrom != null) { Debug.Assert(count == null && byteOffset == null, "Clone must inherit from ancestor"); return m_clonedFrom.Ancestor; } return this; } } public int Count => Ancestor.count.Value; public long ByteOffset => Ancestor.byteOffset.Value; public Vector4 MaxFloat => Ancestor.maxFloat; public Vector4 MinFloat => Ancestor.minFloat; public int MinInt => Ancestor.minInt; public int MaxInt => Ancestor.maxInt; // Private to force people to use the better-named CloneWithDifferentType() method. private GlTF_Accessor(GlTF_Globals G, GlTF_Accessor fromAccessor, Type newType) : base(G) { m_clonedFrom = fromAccessor; if (newType >= fromAccessor.type) { throw new ArgumentException("newType must be smaller than fromAccessor.type"); } this.name = $"{fromAccessor.name}_{newType}"; this.bufferView = fromAccessor.bufferView; this.byteStride = fromAccessor.byteStride; this.type = newType; this.componentType = fromAccessor.componentType; // Leave these null; at serialization time, we "inherit" a value from m_clonedFrom // this.count = fromAccessor.count; // this.byteOffset = fromAccessor.byteOffset; // These aren't nullables because the purity isn't worth the pain, but at least poison them this.maxFloat = new Vector4(float.NaN, float.NaN, float.NaN, float.NaN); this.minFloat = new Vector4(float.NaN, float.NaN, float.NaN, float.NaN); this.minInt = 0x0D00B015; this.maxInt = 0x0D00B015; SanityCheckBufferViewStride(); } // Pass: // normalized - // true if integral values are intended to be values in [0, 1] // For convenience, this parameter is ignored if the ComponentType is non-integral. public GlTF_Accessor( GlTF_Globals globals, string n, Type t, ComponentType c, GlTF_BufferView bufferView, bool isNonVertexAttributeAccessor, bool normalized) : base(globals) { name = n; type = t; componentType = c; bool isIntegral = (c != ComponentType.FLOAT); m_normalized = isIntegral && normalized; this.bufferView = bufferView; // I think (but am not sure) that we can infer whether this is a vertex attribute or some // other kind of accessor by what the "target" of the bufferview is. // All bufferviews except for ushortBufferView use kTarget.ARRAY_BUFFER. // The old code used to look at Type (SCALAR implies non-vertex-attribute), but I // think vertexId is a counterexample of a scalar vertex attribute. Debug.Assert(isNonVertexAttributeAccessor == (bufferView.target == GlTF_BufferView.kTarget_ELEMENT_ARRAY_BUFFER)); int packedSize = GetSize(componentType) * GetNumComponents(type); if (isNonVertexAttributeAccessor) { // Gltf2 rule is that bufferView.byteStride may only be set if the accessor is for // a vertex attributes. I think gltf1 is the same way. byteStride = 0; } else if (type == Type.SCALAR && !G.Gltf2) { // Old gltf1 code used to use "packed" for anything of Type.SCALAR. // I'm going to replicate that odd behavior for ease of diffing old vs new .glb1. // As long as stride == packedSize then it's mostly safe to omit the stride, at least in gltf1 Debug.Assert(byteStride == 0 || byteStride == packedSize); byteStride = 0; } else { byteStride = packedSize; } SanityCheckBufferViewStride(); } private void SanityCheckBufferViewStride() { int packedSize = GetSize(componentType) * GetNumComponents(type); // Check that all Accessors that use this bufferview agree on the stride to use. // See docs on m_byteStride and m_packedSize. if (bufferView != null) { Debug.Assert(byteStride == (bufferView.m_byteStride ?? byteStride)); bufferView.m_byteStride = byteStride; if (byteStride == 0) { // Also check for agreement on packed size -- I am not sure how gltf could // tell if a SCALAR+UNSIGNED_SHORT and a SCALAR+UNSIGNED_INT accessor both // tried to use the same bufferview. Debug.Assert(packedSize == (bufferView.m_packedSize ?? packedSize)); bufferView.m_packedSize = packedSize; } } } public static string GetNameFromObject(ObjectName o, string name) { return "accessor_" + name + "_" + o.ToGltf1Name(); } private void InitMinMaxInt() { m_haveMinMax = true; maxInt = int.MinValue; minInt = int.MaxValue; } private void InitMinMaxFloat() { m_haveMinMax = true; float min = float.MinValue; float max = float.MaxValue; maxFloat = new Vector4(min, min, min, min); minFloat = new Vector4(max, max, max, max); } // Raises exception if our type does not match private void RequireType(Type t, ComponentType c) { if (this.type != t || this.componentType != c) { throw new InvalidOperationException($"Cannot write {t} {c} to {type} {componentType}"); } } public void Populate(List<Color32> colorList) { // gltf2 spec says that only position and animation inputs _require_ min/max // so I'm going to skip it. this.byteOffset = this.bufferView.currentOffset; this.count = colorList.Count; if (componentType == ComponentType.FLOAT) { RequireType(Type.VEC4, ComponentType.FLOAT); Color[] colorArray = colorList.Select(c32 => (Color)c32).ToArray(); this.bufferView.FastPopulate(colorArray, colorArray.Length); } else { RequireType(Type.VEC4, ComponentType.UNSIGNED_BYTE); this.bufferView.FastPopulate(colorList); } } public void PopulateUshort(int[] vs) { RequireType(Type.SCALAR, ComponentType.USHORT); byteOffset = bufferView.currentOffset; bufferView.PopulateUshort(vs); count = vs.Length; // TODO: try to remove if (count > 0) { InitMinMaxInt(); for (int i = 0; i < count; ++i) { maxInt = Mathf.Max(vs[i], maxInt); minInt = Mathf.Min(vs[i], minInt); } } } // flipY - // true if value.xy is a UV, and if a UV axis convention swap is needed // glTF defines uv axis conventions to be u right, v down -- origin top-left // Ref: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0, search for "uv" // Unity defines uv axis conventions to be u right, v up -- origin bottom-left // Ref: https://docs.unity3d.com/ScriptReference/Texture2D.GetPixelBilinear.html // calculateMinMax - // gltf2 spec says that only position and animation inputs _require_ min/max. // It's safe to pass false if it's neither of those things. // It's always safe to pass true, but it wastes CPU public void Populate(List<Vector2> v2s, bool flipY, bool calculateMinMax) { if (flipY) { v2s = v2s.Select(v => new Vector2(v.x, 1f - v.y)).ToList(); } RequireType(Type.VEC2, ComponentType.FLOAT); byteOffset = bufferView.currentOffset; count = v2s.Count; bufferView.FastPopulate(v2s); if (calculateMinMax && count > 0) { InitMinMaxFloat(); for (int i = 0; i < v2s.Count; i++) { maxFloat = Vector2.Max(v2s[i], maxFloat); minFloat = Vector2.Min(v2s[i], minFloat); } } } public void Populate(List<Vector3> v3s, bool flipY, bool calculateMinMax) { if (flipY) { v3s = v3s.Select(v => new Vector3(v.x, 1f - v.y, v.z)).ToList(); } RequireType(Type.VEC3, ComponentType.FLOAT); byteOffset = bufferView.currentOffset; count = v3s.Count; bufferView.FastPopulate(v3s); if (calculateMinMax && count > 0) { InitMinMaxFloat(); for (int i = 0; i < v3s.Count; i++) { maxFloat = Vector3.Max(v3s[i], maxFloat); minFloat = Vector3.Min(v3s[i], minFloat); } } } public void Populate(List<Vector4> v4s, bool flipY, bool calculateMinMax) { if (flipY) { v4s = v4s.Select(v => new Vector4(v.x, 1f - v.y, v.z, v.w)).ToList(); } RequireType(Type.VEC4, ComponentType.FLOAT); byteOffset = bufferView.currentOffset; count = v4s.Count; bufferView.FastPopulate(v4s); if (calculateMinMax && count > 0) { InitMinMaxFloat(); for (int i = 0; i < v4s.Count; i++) { maxFloat = Vector4.Max(v4s[i], maxFloat); minFloat = Vector4.Min(v4s[i], minFloat); } } } // Writes either the integral or floating-point value(s), based on type and componentType private void WriteNamedTypedValue(string name, int i, Vector4 fs) { string val = null; if (componentType == ComponentType.FLOAT) { switch (type) { case Type.SCALAR: val = $"{fs.x:G9}"; break; case Type.VEC2: val = $"{fs.x:G9}, {fs.y:G9}"; break; case Type.VEC3: val = $"{fs.x:G9}, {fs.y:G9}, {fs.z:G9}"; break; case Type.VEC4: val = $"{fs.x:G9}, {fs.y:G9}, {fs.z:G9}, {fs.w:G9}"; break; } } else if (componentType == ComponentType.USHORT) { if (type == Type.SCALAR) { val = i.ToString(); } } if (val == null) { throw new InvalidOperationException($"Unhandled: {type} {componentType}"); } jsonWriter.Write($"\"{name}\": [ {val} ]"); } public override IEnumerable<GlTF_ReferencedObject> IterReferences() { yield return G.Lookup(bufferView); } public override void WriteTopLevel() { BeginGltfObject(); G.CNI.WriteNamedReference("bufferView", bufferView); G.CNI.WriteNamedInt("byteOffset", ByteOffset); if (!G.Gltf2) { G.CNI.WriteNamedInt("byteStride", byteStride); } G.CNI.WriteNamedInt("componentType", (int)componentType); if (G.Gltf2 && m_normalized) { G.CNI.WriteNamedBool("normalized", m_normalized); } var inheritedCount = Count; G.CNI.WriteNamedInt("count", inheritedCount); // min and max are not well-defined if count == 0 if (m_haveMinMax && inheritedCount > 0) { G.CommaNL(); G.Indent(); WriteNamedTypedValue("max", MaxInt, MaxFloat); G.CommaNL(); G.Indent(); WriteNamedTypedValue("min", MinInt, MinFloat); } G.CNI.WriteNamedString("type", type.ToString()); EndGltfObject(); } }
using Aspose.HTML.Live.Demos.UI.Models; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Threading.Tasks; using System.IO; using System.IO.Compression; using System.Linq; using System.Net.Http; using System.Runtime.Remoting.Channels; using System.Text; using System.Text.RegularExpressions; using System.Web; using Aspose.HTML.Live.Demos.UI.Helpers; using Aspose.HTML.Live.Demos.UI.Services; using Aspose.HTML.Live.Demos.UI.Models.Common; using Newtonsoft.Json.Linq; using Path = System.IO.Path; namespace Aspose.HTML.Live.Demos.UI.Models { ///<Summary> /// AsposeHTMLBase class ///</Summary> public class AsposeHTMLBase : ModelBase { /// <summary> /// Maximum number of files which can be uploaded for MVC Aspose.Pdf apps /// </summary> protected static int MaximumUploadFiles = 10; /// <summary> /// Original file format SaveAs option for multiple files uploading. By default, "-" /// </summary> protected const string SaveAsOriginalName = ".-"; /// <summary> /// Response when uploaded files exceed the limits /// </summary> protected Response MaximumFileLimitsResponse = new Response() { Status = $"Number of files should be equal or less {MaximumUploadFiles}", StatusCode = 500 }; /// <summary> /// Response when uploaded files exceed the limits /// </summary> protected Response BadDocumentResponse = new Response() { Status = "Some of your documents are corrupted", StatusCode = 500 }; private static string[] inExtensions = { ".htm", ".html", ".xhtml", ".mhtml", ".mht", ".epub", ".svg", ".zip", ".md" }; public class Options { ///<Summary> /// AppName ///</Summary> public string AppName; ///<Summary> /// FolderName ///</Summary> public string FolderName; /// <summary> /// File Names /// </summary> public string[] FileNames; ///<Summary> /// FileName ///</Summary> public string FileName => (FileNames != null && FileNames.Length > 0) ? FileNames[0] : ""; private string _outputType; /// <summary> /// By default, it is the extension of FileName - e.g. ".docx" /// </summary> public string OutputType { get => _outputType; set { if (!value.StartsWith(".")) value = "." + value; _outputType = value.ToLower(); } } ///<Summary> /// ResultFileName ///</Summary> public string ResultFileName = ""; ///<Summary> /// MethodName ///</Summary> public string MethodName; ///<Summary> /// ModelName ///</Summary> public string ModelName; ///<Summary> /// CreateZip ///</Summary> public bool CreateZip = false; ///<Summary> /// CheckNumberOfPages ///</Summary> public bool CheckNumberOfPages = false; ///<Summary> /// DeleteSourceFolder ///</Summary> public bool DeleteSourceFolder = false; /// <summary> /// Output zip filename (without '.zip'), if CreateZip property is true /// By default, FileName + AppName /// </summary> public string ZipFileName; /// <summary> /// If there are multiple input files, create a single result file (if result format allows it) if True; /// else process each input file separately and return a zip archive /// </summary> public bool MergeMultiple = false; /// <summary> /// Container for additional parameters being passed in the API URL query /// </summary> private Dictionary<string, string> m_queryParams = null; /// <summary> /// AppSettings.WorkingDirectory + FolderName + "/" + FileName /// </summary> //public string WorkingFileName //{ // get // { // if (System.IO.File.Exists(AppSettings.WorkingDirectory + FolderName + "/" + FileName)) // return AppSettings.WorkingDirectory + FolderName + "/" + FileName; // return AppSettings.OutputDirectory + FolderName + "/" + FileName; // } //} /// <summary> /// Check if 'key' parameter has been specified in the request. /// </summary> /// <param name="key"></param> /// <returns></returns> public bool HasCustomParameter(string key) { return m_queryParams != null && m_queryParams.ContainsKey(key); } /// <summary> /// Extract parameters from the query string of HTTP request. /// </summary> /// <param name="request"></param> public void SetupCustomQueryParameters(HttpRequestMessage request) { if (m_queryParams == null) { m_queryParams = request.GetQueryNameValuePairs() .ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase); } } /// <summary> /// Get 'key' query parameter value (as string), if it has been specified, or null /// </summary> /// <param name="key"></param> /// <returns></returns> public string GetCustomParameter(string key) { if (m_queryParams.ContainsKey(key)) return m_queryParams[key]; return null; } } /// <summary> /// Obsolete method /// </summary> /// <param name="action"></param> /// <returns></returns> protected Response ProcessTask(ActionDelegate action) { string productName = "AsposeHTML" + Opts.AppName; string methodName = Opts.MethodName; string folderName = Opts.FolderName; string fileName = Opts.FileName; string guid = Guid.NewGuid().ToString(); string outFolder = ""; string sourceFolder; if (!string.IsNullOrEmpty(folderName) && Path.IsPathRooted(folderName)) sourceFolder = folderName; else sourceFolder = Config.Configuration.WorkingDirectory + folderName; string _logFileName = fileName; if (!Path.IsPathRooted(fileName)) fileName = sourceFolder + "/" + fileName; string fileExtension = Path.GetExtension(fileName).ToLower(); string outfileName = Path.GetFileNameWithoutExtension(fileName) + Opts.OutputType; string outPath = ""; string zipOutFolder = Config.Configuration.OutputDirectory + guid; string zipOutfileName, zipOutPath; if (string.IsNullOrEmpty(Opts.ZipFileName)) { zipOutfileName = guid + ".zip"; zipOutPath = Config.Configuration.OutputDirectory + zipOutfileName; } else { var guid2 = Guid.NewGuid().ToString(); outFolder = guid2; zipOutfileName = Opts.ZipFileName + ".zip"; zipOutPath = Config.Configuration.OutputDirectory + guid2; Directory.CreateDirectory(zipOutPath); zipOutPath += "/" + zipOutfileName; } if (Opts.CreateZip) { outfileName = Path.GetFileNameWithoutExtension(fileName) + Opts.OutputType; outPath = zipOutFolder + "/" + outfileName; Directory.CreateDirectory(zipOutFolder); } else { outFolder = guid; outPath = Config.Configuration.OutputDirectory + outFolder; Directory.CreateDirectory(outPath); outPath += "/" + outfileName; } string statusValue = "OK"; int statusCodeValue = 200; try { action(fileName, outPath, zipOutFolder); if (Opts.CreateZip) { ZipFile.CreateFromDirectory(zipOutFolder, zipOutPath); Directory.Delete(zipOutFolder, true); outfileName = zipOutfileName; } if (Opts.DeleteSourceFolder) { System.GC.Collect(); System.GC.WaitForPendingFinalizers(); Directory.Delete(sourceFolder, true); } } catch (Exception ex) { statusCodeValue = 500; statusValue = "500 " + ex.Message; } return new Response { FileName = outfileName, FolderName = outFolder, Status = statusValue, StatusCode = statusCodeValue, }; } /// <summary> /// Method version used by new MVC-based implementation. /// </summary> /// <param name="fileNames"></param> /// <param name="action"></param> /// <returns></returns> protected Response ProcessTask_(string[] fileNames, HtmlActionDelegate action) { string productName = "AsposeHTML" + Opts.AppName; string methodName = Opts.MethodName; string folderName = Opts.FolderName; string sourceFolder; if (!string.IsNullOrEmpty(folderName) && Path.IsPathRooted(folderName)) sourceFolder = folderName; else sourceFolder = Config.Configuration.WorkingDirectory + folderName; string guid = Guid.NewGuid().ToString(); string zipTmpFolder = Config.Configuration.OutputDirectory + guid; string zipOutfileName, zipOutPath = ""; string outFolder = "", outFolderPath = "", outfileName = ""; //string outPath; if (Opts.CreateZip) { if (string.IsNullOrEmpty(Opts.ZipFileName)) { zipOutfileName = guid + ".zip"; zipOutPath = Config.Configuration.OutputDirectory + zipOutfileName; } else { var guid2 = Guid.NewGuid().ToString(); outFolder = guid2; zipOutfileName = Opts.ZipFileName + ".zip"; zipOutPath = Config.Configuration.OutputDirectory + guid2; Directory.CreateDirectory(zipOutPath); zipOutPath += "/" + zipOutfileName; } outfileName = Opts.ZipFileName + Opts.OutputType; Directory.CreateDirectory(zipTmpFolder); } else { outfileName = Opts.ResultFileName + Opts.OutputType; outFolder = guid; outFolderPath = Config.Configuration.OutputDirectory + outFolder; Directory.CreateDirectory(outFolderPath); } string statusValue = "OK"; int statusCodeValue = 200; try { if (Opts.CreateZip) { foreach (var fn in fileNames) { var outFile = Path.GetFileNameWithoutExtension(fn) + Opts.OutputType; var outPath = zipTmpFolder + "/" + outFile; action(new string[] { fn }, outPath, ""); } ZipFile.CreateFromDirectory(zipTmpFolder, zipOutPath); Directory.Delete(zipTmpFolder, true); outfileName = Path.GetFileName(zipOutPath); } else { var outPath = $"{outFolderPath}/{outfileName}"; action(fileNames, outPath, ""); //if(fileNames.Length == 1) //{ // if(!System.IO.File.Exists(outPath)) // { // DirectoryInfo dir = new DirectoryInfo(outFolderPath); // var pattern = $"{Path.GetFileNameWithoutExtension(outfileName)}"; // var ff = dir.GetFiles(pattern); // if (ff.Length > 0 && outfileName != ff[0].Name) // { // outfileName = ff[0].Name; // } // } //} } #region REM //if (Opts.MergeMultiple || !Opts.CreateZip) //{ // var outPath = $"{outFolderPath}/{outfileName}"; // action(fileNames, outPath, ""); //} //else //{ // foreach(var fn in fileNames) // { // var outFile = Path.GetFileNameWithoutExtension(fn) + Opts.OutputType; // var outPath = zipTmpFolder + "/" + outFile; // action(new string[] { fn }, outPath, ""); // } // if (Opts.CreateZip) // { // ZipFile.CreateFromDirectory(zipTmpFolder, zipOutPath); // Directory.Delete(zipTmpFolder, true); // outfileName = Path.GetFileName(zipOutPath); // } //} #endregion if (Opts.DeleteSourceFolder) { System.GC.Collect(); System.GC.WaitForPendingFinalizers(); Directory.Delete(sourceFolder, true); } } catch (Exception ex) { statusCodeValue = 500; statusValue = "500 " + ex.Message; } return new Response { FileName = outfileName, FolderName = outFolder, Status = statusValue, StatusCode = statusCodeValue, }; } /// <summary> /// init Options /// </summary> protected Options Opts = new Options(); /// <summary> /// UTF8WithoutBom /// </summary> protected static readonly Encoding UTF8WithoutBom = new UTF8Encoding(false); private object Lock1 = new object(); private object Lock2 = new object(); /// <summary> /// PageBase /// </summary> public AsposeHTMLBase() { Opts.ModelName = GetType().Name; } /// <summary> /// PageBase /// </summary> static AsposeHTMLBase() { Aspose.HTML.Live.Demos.UI.Models.License.SetAsposeHTMLLicense(); } ///<Summary> /// Prepare Archive file (mainly zipped HTML with local resources) to processing ///</Summary> public void ProcessZipArchiveFile(ref string fileName, string folderName) { //If the input file is not zip file then return; if (Path.GetExtension(fileName).ToLower() != ".zip") { return; } //Extract zip file contents and prepare them for conversion. string destinationDirectoryName; if (Path.IsPathRooted(folderName)) destinationDirectoryName = $"{folderName.Replace('\\', '/')}/"; else destinationDirectoryName = $"{Path.Combine(Config.Configuration.WorkingDirectory, folderName).Replace('\\', '/')}/"; string sourceArchiveFileName; ; if (Path.IsPathRooted(fileName)) sourceArchiveFileName = fileName; else sourceArchiveFileName = destinationDirectoryName + Path.GetFileName(fileName); destinationDirectoryName = Path.Combine(Config.Configuration.WorkingDirectory.Replace('/', '\\'), Guid.NewGuid().ToString()); System.IO.Compression.ZipFile.ExtractToDirectory(sourceArchiveFileName, destinationDirectoryName); string sourceFileName = ""; string[] dirFiles = System.IO.Directory.GetFiles(destinationDirectoryName); for (int i = 0; i < dirFiles.Length; i++) { sourceFileName = dirFiles[i]; string fileExt = Path.GetExtension(sourceFileName).ToLower(); if (inExtensions.Contains(fileExt)) { break; } } fileName = sourceFileName; } protected string CheckInputType(MultipartFormDataStreamProviderSafe uploadProvider, string _inputType) { if (uploadProvider.FileData[0] != null) { string inputFileName = uploadProvider.FileData[0].LocalFileName; string actualInputType = inputFileName.Substring(inputFileName.LastIndexOf('.') + 1); if (!_inputType.Equals(actualInputType)) _inputType = actualInputType; } return _inputType; } /// <summary> /// /// </summary> /// <param name="docs"></param> protected void SetDefaultOptions(InputFiles inputFiles, string outputType) { if (inputFiles.Count > 0) { SetDefaultOptions(inputFiles[0].FileName, outputType); Opts.CreateZip = inputFiles.Count > 1 && !Opts.MergeMultiple; /*|| (Opts.IsPicture)*/ } } /// <summary> /// Set default parameters into Opts /// </summary> /// <param name="filename"></param> private void SetDefaultOptions(string filename, string outputType) { Opts.ResultFileName = filename; //Opts.FileName = Path.GetFileName(filename); //var query = Request.GetQueryNameValuePairs().ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase); //string outputType = null; //if (query.ContainsKey("outputType")) // outputType = query["outputType"]; Opts.OutputType = !string.IsNullOrEmpty(outputType) ? outputType : Path.GetExtension(Opts.FileName); Opts.ResultFileName = Opts.OutputType == SaveAsOriginalName ? Opts.FileName : Path.GetFileNameWithoutExtension(Opts.FileName) + Opts.OutputType; } protected Response Process(HtmlAsyncActionDelegate action) { if (string.IsNullOrEmpty(Opts.OutputType) && !string.IsNullOrEmpty(Opts.FileName)) Opts.OutputType = Path.GetExtension(Opts.FileName); if (!(Opts.OutputType == ".pdf" || Opts.OutputType == ".xps" || Opts.OutputType == ".tiff" || Opts.OutputType == ".tif")) Opts.CreateZip = true; // Opts.FileNames.Length > 1; // && !Opts.MergeMultiple); if (string.IsNullOrEmpty(Opts.ZipFileName)) Opts.ZipFileName = Path.GetFileNameWithoutExtension(Opts.FileName) + Opts.AppName; return action(Opts.FileNames, Opts.FolderName, Opts.OutputType); } #region Common /// <summary> /// IsValidRegex /// </summary> public static bool IsValidRegex(string pattern) { if (string.IsNullOrEmpty(pattern)) return false; try { Regex.Match("", pattern); } catch (ArgumentException) { return false; } return true; } #endregion } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Collections; namespace LineChart { /// <summary> /// Summary description for Line2D. /// </summary> public class Line2D { private int m_Width; //Width of the rectangle container for graph. private int m_Height; //Height of the rectangle container for graph. private ArrayList m_XAxis; //X-axis for the graph. private ArrayList m_YAxis; //Y-Axis for the graph. private Color m_graphColor = Color.Red; //Color of the line graph. private float m_XSlice = 1; //Slice for X Axis. private float m_YSlice = 1; //Slice for Y Axis. private Graphics objGraphics; private Bitmap objBitmap; private string m_XAxisText = "X"; private string m_YAxisText = "Y"; private string m_Title; private Color m_TitleBackColor = Color.Cyan; private Color m_TitleForeColor = Color.Green; //Sets or Gets the Width for the rectangle container of graph. public int Width { get { return m_Width;} set { m_Width = value; } } //Sets or Gets the Height for the rectangle container of graph. public int Height { get { return m_Height;} set { m_Height = value; } } //Sets or Gets the X-Axis pixels for the graph. public ArrayList XAxis { set { m_XAxis = value; } get { return m_XAxis;} } //Sets or Gets the Y-Axis pixels for the graph. public ArrayList YAxis { set { m_YAxis = value;} get { return m_YAxis;} } //Sets or Gets the Color of the line Graph. public Color GraphColor { set { m_graphColor = value;} get { return m_graphColor;} } //Sets or Gets the X Axis Slice. public float XSlice { set { m_XSlice = value;} get { return m_XSlice;} } //Sets or Gets the Y Axis Slice. public float YSlice { set { m_YSlice = value;} get { return m_YSlice;} } //Sets or Gets the X-Axis Test. public string XAxisText { get { return m_XAxisText;} set { m_XAxisText = value;} } //Sets or Gets the Y-Axis Test. public string YAxisText { get { return m_YAxisText;} set { m_YAxisText = value;} } //Sets or Gets the title for the Graph. public string Title { get { return m_Title;} set { m_Title = value;} } //Sets or Gets the title Backcolor. public Color TitleBackColor { get { return m_TitleBackColor;} set { m_TitleBackColor = value;} } //Sets or Gets the Title ForeColor. public Color TitleForeColor { get { return m_TitleForeColor;} set { m_TitleForeColor = value;} } //Default constructor. public Line2D() { } /****************************************************************************************** * Method : Public InitializeGraph * Purpose : Initialises the Graph.Draws rectangle region and fills the region. * Draws X-Axis line and Y-Axis line. * Draws Origin (0,0) point.Sets Axis Text and creates Title. * *****************************************************************************************/ public void InitializeGraph() { //Creating a bitmap image with given height and width. objBitmap = new Bitmap(Width,Height); //Getting the bitmap image into the graphics portion of the screen. objGraphics = Graphics.FromImage(objBitmap); //Filling the rectangle portion of the graphics with custom color. objGraphics.FillRectangle(new SolidBrush(Color.Black),0,0,Width,Height); //Drawing X-Axis line. //objGraphics.DrawLine(new Pen(new SolidBrush(Color.YellowGreen),2),0,Height - 10,Width - 10,Height - 100); //Drawing Y-Axis line. //objGraphics.DrawLine(new Pen(new SolidBrush(Color.YellowGreen),2),100,Height - 100,100,10); //Plotting Origin(0,0). //objGraphics.DrawString("0",new Font("Arial",8),new SolidBrush(Color.Black),100,Height - 90); //Sets Axis text. //SetAxisText(ref objGraphics); //Sets the title for the Graph. //CreateTitle(ref objGraphics); } /****************************************************************************************** * Method : Public CreateGraph * Purpose : Calls SetPixel function to draw line in the rectangle region. * Input : Color of the line Graph. * *****************************************************************************************/ public void CreateGraph(Color _GraphColor) { GraphColor = _GraphColor; //Plotting the pixels. SetPixels(ref objGraphics); } /****************************************************************************************** * Method : Public Draw2D. * Purpose : Creates 2D graph for the given X and Y Axis. * Returns : (Bitmap) reference of the graphics portions. * *****************************************************************************************/ public Bitmap GetGraph() { //Creating X-Axis slices. SetXAxis(ref objGraphics,XSlice); //Creating Y-Axis slices. SetYAxis(ref objGraphics,YSlice); return objBitmap; } /****************************************************************************************** * Method : Public PlotGraph. * Purpose : Draws Axis Line. * Input : Graphics object,X Axis, Y Axis for both points. ******************************************************************************************/ private void PlotGraph(ref Graphics objGraphics,float x1,float y1,float x2,float y2) { objGraphics.DrawLine(new Pen(new SolidBrush(Color.Lime),1),x1, y1 ,x2,y2); } /****************************************************************************************** * Method : Public SetXAxis. * Purpose : Draws X-Axis Slices. * Input : Graphics object, Slices for the XAxis. ******************************************************************************************/ private void SetXAxis(ref Graphics objGraphics,float iSlices) { float x1 = 0,y1 = Height - 110,x2 = 0,y2 = Height - 90; for(int iIndex = 0;iIndex<Height - 200;iIndex+=10) { objGraphics.DrawLine(new Pen(new SolidBrush(Color.YellowGreen)),x1+iIndex,y1+5,x2+iIndex,y2-5); } } /****************************************************************************************** * Method : Public SetYAxis. * Purpose : Draws Y-Axis Slices. * Input : Graphics object, Slices for the axis. ******************************************************************************************/ private void SetYAxis(ref Graphics objGraphics,float iSlices) { int x1 = 95; int y1 = Height - 110; int x2 = 105; int y2 = Height - 110; for(int iIndex = 0;iIndex<Height - 200;iIndex+=10) { objGraphics.DrawLine(new Pen(new SolidBrush(Color.YellowGreen)), x1, (y1 - iIndex),x2,(y2 - iIndex)); } } /****************************************************************************************** * Method : Public SetPixels. * Purpose : Plots pixels. * Input : Graphics object. ******************************************************************************************/ private void SetPixels(ref Graphics objGraphics) { float X1 = float.Parse(XAxis[0].ToString()); float Y1 = float.Parse(YAxis[0].ToString()); if(XAxis.Count == YAxis.Count) { for(int iXaxis = 0,iYaxis =0;(iXaxis < XAxis.Count - 1 && iYaxis < YAxis.Count - 1);iXaxis++,iYaxis++) { PlotGraph(ref objGraphics,X1,Y1,float.Parse(XAxis[iXaxis + 1].ToString()),float.Parse(YAxis[iYaxis + 1].ToString())); X1 = float.Parse(XAxis[iXaxis + 1].ToString()); Y1 = float.Parse(YAxis[iYaxis + 1].ToString()); } // objGraphics.DrawRectangle(new Pen(Color.Black), 0, 108, Width, 20); // objGraphics.DrawString(Y1.ToString()+"%", new Font("Courier New", 10), new SolidBrush(Color.GreenYellow), 10, 108); } else { //X and Y axis length should be same. } } /****************************************************************************************** * Method : Private SetAxisText. * Purpose : Sets the Axis text. * Input : Graphics object. ******************************************************************************************/ private void SetAxisText(ref Graphics objGraphics) { objGraphics.DrawString(XAxisText,new Font("Arial",9),new SolidBrush(Color.SaddleBrown), Width / 2 - 50,Height - 50); int X = 30; int Y = (Height / 2 ) - 50; for(int iIndex = 0;iIndex < YAxisText.Length;iIndex++) { objGraphics.DrawString(YAxisText[iIndex].ToString(),new Font("Arial",9),new SolidBrush(Color.SaddleBrown), X,Y); Y += 10; } } /****************************************************************************************** * Method : Public CreateTitle. * Purpose : Creates title for the graph. * Input : Graphics object. ******************************************************************************************/ private void CreateTitle(ref Graphics objGraphics) { objGraphics.FillRectangle(new SolidBrush(Color.Green),Height - 100,20,Height - 200,20); Rectangle rect = new Rectangle(Height - 100,20,Height - 200,20); objGraphics.DrawString(Title,new Font("Verdana",10),new SolidBrush(TitleForeColor),rect); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Cursor; using osu.Framework.Graphics.OpenGL.Textures; using osu.Framework.Graphics.OpenGL.Vertices; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Framework.Utils; using osuTK; using osuTK.Graphics; namespace osu.Framework.Graphics.Visualisation { internal class TextureVisualiser : ToolWindow { private readonly FillFlowContainer<TexturePanel> atlasFlow; private readonly FillFlowContainer<TexturePanel> textureFlow; public TextureVisualiser() : base("Textures", "(Ctrl+F3 to toggle)") { ScrollContent.Child = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { new SpriteText { Text = "Atlases", Padding = new MarginPadding(5), Font = FrameworkFont.Condensed.With(weight: "Bold") }, atlasFlow = new FillFlowContainer<TexturePanel> { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Spacing = new Vector2(22), Padding = new MarginPadding(10), }, new SpriteText { Text = "Textures", Padding = new MarginPadding(5), Font = FrameworkFont.Condensed.With(weight: "Bold") }, textureFlow = new FillFlowContainer<TexturePanel> { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Spacing = new Vector2(22), Padding = new MarginPadding(10), } } }; } protected override void PopIn() { base.PopIn(); foreach (var tex in TextureGLSingle.GetAllTextures()) addTexture(tex); TextureGLSingle.TextureCreated += addTexture; } protected override void PopOut() { base.PopOut(); atlasFlow.Clear(); textureFlow.Clear(); TextureGLSingle.TextureCreated -= addTexture; } private void addTexture(TextureGLSingle texture) => Schedule(() => { var target = texture is TextureGLAtlas ? atlasFlow : textureFlow; if (target.Any(p => p.Texture == texture)) return; target.Add(new TexturePanel(texture)); }); private class TexturePanel : CompositeDrawable { private readonly WeakReference<TextureGLSingle> textureReference; public TextureGLSingle Texture => textureReference.TryGetTarget(out var tex) ? tex : null; private readonly SpriteText titleText; private readonly SpriteText footerText; private readonly UsageBackground usage; public TexturePanel(TextureGLSingle texture) { textureReference = new WeakReference<TextureGLSingle>(texture); Size = new Vector2(100, 132); InternalChild = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Children = new Drawable[] { titleText = new SpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Font = FrameworkFont.Regular.With(size: 16) }, new Container { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { usage = new UsageBackground(textureReference) { Size = new Vector2(100) }, }, }, footerText = new SpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Font = FrameworkFont.Regular.With(size: 16), }, } }; } protected override void Update() { base.Update(); try { var texture = Texture; if (texture?.Available != true) { Expire(); return; } titleText.Text = $"{texture.TextureId}. {texture.Width}x{texture.Height} "; footerText.Text = Precision.AlmostBigger(usage.AverageUsagesPerFrame, 1) ? $"{usage.AverageUsagesPerFrame:N0} binds" : string.Empty; } catch { } } } private class UsageBackground : Box, IHasTooltip { private readonly WeakReference<TextureGLSingle> textureReference; private ulong lastBindCount; public float AverageUsagesPerFrame { get; private set; } public UsageBackground(WeakReference<TextureGLSingle> textureReference) { this.textureReference = textureReference; } protected override DrawNode CreateDrawNode() => new UsageBackgroundDrawNode(this); private class UsageBackgroundDrawNode : SpriteDrawNode { protected new UsageBackground Source => (UsageBackground)base.Source; private ColourInfo drawColour; private WeakReference<TextureGLSingle> textureReference; public UsageBackgroundDrawNode(Box source) : base(source) { } public override void ApplyState() { base.ApplyState(); textureReference = Source.textureReference; } public override void Draw(Action<TexturedVertex2D> vertexAction) { if (!textureReference.TryGetTarget(out var texture)) return; if (!texture.Available) return; ulong delta = texture.BindCount - Source.lastBindCount; Source.AverageUsagesPerFrame = Source.AverageUsagesPerFrame * 0.9f + delta * 0.1f; drawColour = DrawColourInfo.Colour; drawColour.ApplyChild( Precision.AlmostBigger(Source.AverageUsagesPerFrame, 1) ? Interpolation.ValueAt(Source.AverageUsagesPerFrame, Color4.DarkGray, Color4.Red, 0, 200) : Color4.Transparent); base.Draw(vertexAction); // intentionally after draw to avoid counting our own bind. Source.lastBindCount = texture.BindCount; } protected override void Blit(Action<TexturedVertex2D> vertexAction) { if (!textureReference.TryGetTarget(out var texture)) return; const float border_width = 4; // border DrawQuad(Texture, ScreenSpaceDrawQuad, drawColour, null, vertexAction); var shrunkenQuad = ScreenSpaceDrawQuad.AABBFloat.Shrink(border_width); // background DrawQuad(Texture, shrunkenQuad, Color4.Black, null, vertexAction); float aspect = (float)texture.Width / texture.Height; if (aspect > 1) { float newHeight = shrunkenQuad.Height / aspect; shrunkenQuad.Y += (shrunkenQuad.Height - newHeight) / 2; shrunkenQuad.Height = newHeight; } else if (aspect < 1) { float newWidth = shrunkenQuad.Width / (1 / aspect); shrunkenQuad.X += (shrunkenQuad.Width - newWidth) / 2; shrunkenQuad.Width = newWidth; } // texture texture.Bind(); DrawQuad(texture, shrunkenQuad, Color4.White, null, vertexAction); } protected internal override bool CanDrawOpaqueInterior => false; } public LocalisableString TooltipText { get { if (!textureReference.TryGetTarget(out var texture)) return string.Empty; return $"type: {texture.GetType().Name}, size: {(float)texture.GetByteSize() / 1024 / 1024:N2}mb"; } } } } }
namespace InsectCatalog.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitialCreate : DbMigration { public override void Up() { CreateTable( "dbo.Authors", c => new { AuthorId = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), URL = c.String(), }) .PrimaryKey(t => t.AuthorId); CreateTable( "dbo.Hosts", c => new { HostId = c.Int(nullable: false, identity: true), CommonName = c.String(nullable: false), Name = c.String(nullable: false), URL = c.String(), }) .PrimaryKey(t => t.HostId); CreateTable( "dbo.Images", c => new { ImageId = c.Int(nullable: false, identity: true), S3Id = c.String(nullable: false), Caption = c.String(nullable: false), Display = c.Boolean(nullable: false), Photographer_PersonId = c.Int(nullable: false), Insect_InsectId = c.Int(), }) .PrimaryKey(t => t.ImageId) .ForeignKey("dbo.People", t => t.Photographer_PersonId, cascadeDelete: true) .ForeignKey("dbo.Insects", t => t.Insect_InsectId) .Index(t => t.Photographer_PersonId) .Index(t => t.Insect_InsectId); CreateTable( "dbo.People", c => new { PersonId = c.Int(nullable: false, identity: true), Email = c.String(), FirstName = c.String(nullable: false), MiddleName = c.String(), LastName = c.String(nullable: false), URL = c.String(), }) .PrimaryKey(t => t.PersonId); CreateTable( "dbo.Insects", c => new { InsectId = c.Int(nullable: false, identity: true), Family = c.String(nullable: false), Tribe = c.String(nullable: false), Genus = c.String(nullable: false), Species = c.String(nullable: false), Subspecies = c.String(nullable: false), CommonName = c.String(nullable: false), County = c.String(nullable: false), CollectionDate = c.DateTime(nullable: false), Description = c.String(nullable: false), Author_AuthorId = c.Int(nullable: false), Collector_PersonId = c.Int(nullable: false), Host_HostId = c.Int(nullable: false), Identifier_PersonId = c.Int(), Location_LocationId = c.Int(nullable: false), Method_MethodId = c.Int(nullable: false), }) .PrimaryKey(t => t.InsectId) .ForeignKey("dbo.Authors", t => t.Author_AuthorId, cascadeDelete: true) .ForeignKey("dbo.People", t => t.Collector_PersonId, cascadeDelete: true) .ForeignKey("dbo.Hosts", t => t.Host_HostId, cascadeDelete: true) .ForeignKey("dbo.People", t => t.Identifier_PersonId) .ForeignKey("dbo.Locations", t => t.Location_LocationId, cascadeDelete: true) .ForeignKey("dbo.Methods", t => t.Method_MethodId, cascadeDelete: true) .Index(t => t.Author_AuthorId) .Index(t => t.Collector_PersonId) .Index(t => t.Host_HostId) .Index(t => t.Identifier_PersonId) .Index(t => t.Location_LocationId) .Index(t => t.Method_MethodId); CreateTable( "dbo.Locations", c => new { LocationId = c.Int(nullable: false, identity: true), Latitude = c.Double(nullable: false), Longitude = c.Double(nullable: false), Name = c.String(nullable: false), }) .PrimaryKey(t => t.LocationId); CreateTable( "dbo.Methods", c => new { MethodId = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), URL = c.String(), }) .PrimaryKey(t => t.MethodId); CreateTable( "dbo.AspNetRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId) .Index(t => t.RoleId); CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), Email = c.String(maxLength: 256), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.UserName, unique: true, name: "UserNameIndex"); CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(nullable: false, maxLength: 128), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); } public override void Down() { DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); DropForeignKey("dbo.Insects", "Method_MethodId", "dbo.Methods"); DropForeignKey("dbo.Insects", "Location_LocationId", "dbo.Locations"); DropForeignKey("dbo.Images", "Insect_InsectId", "dbo.Insects"); DropForeignKey("dbo.Insects", "Identifier_PersonId", "dbo.People"); DropForeignKey("dbo.Insects", "Host_HostId", "dbo.Hosts"); DropForeignKey("dbo.Insects", "Collector_PersonId", "dbo.People"); DropForeignKey("dbo.Insects", "Author_AuthorId", "dbo.Authors"); DropForeignKey("dbo.Images", "Photographer_PersonId", "dbo.People"); DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); DropIndex("dbo.AspNetUsers", "UserNameIndex"); DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); DropIndex("dbo.AspNetRoles", "RoleNameIndex"); DropIndex("dbo.Insects", new[] { "Method_MethodId" }); DropIndex("dbo.Insects", new[] { "Location_LocationId" }); DropIndex("dbo.Insects", new[] { "Identifier_PersonId" }); DropIndex("dbo.Insects", new[] { "Host_HostId" }); DropIndex("dbo.Insects", new[] { "Collector_PersonId" }); DropIndex("dbo.Insects", new[] { "Author_AuthorId" }); DropIndex("dbo.Images", new[] { "Insect_InsectId" }); DropIndex("dbo.Images", new[] { "Photographer_PersonId" }); DropTable("dbo.AspNetUserLogins"); DropTable("dbo.AspNetUserClaims"); DropTable("dbo.AspNetUsers"); DropTable("dbo.AspNetUserRoles"); DropTable("dbo.AspNetRoles"); DropTable("dbo.Methods"); DropTable("dbo.Locations"); DropTable("dbo.Insects"); DropTable("dbo.People"); DropTable("dbo.Images"); DropTable("dbo.Hosts"); DropTable("dbo.Authors"); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // (C) 2002 Ville Palo // (C) 2003 Martin Willemoes Hansen // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.Data.SqlTypes; using System.Globalization; using System.IO; using System.Xml; using System.Xml.Serialization; using Xunit; namespace System.Data.Tests.SqlTypes { public class SqlDoubleTest : IDisposable { private CultureInfo _originalCulture; public SqlDoubleTest() { _originalCulture = CultureInfo.CurrentCulture; ; CultureInfo.CurrentCulture = new CultureInfo("en-US"); } public void Dispose() { CultureInfo.CurrentCulture = _originalCulture; } // Test constructor [Fact] public void Create() { SqlDouble Test = new SqlDouble(34.87); Assert.Equal(34.87D, Test.Value); Test = new SqlDouble(-9000.6543); Assert.Equal(-9000.6543D, Test.Value); } // Test public fields [Fact] public void PublicFields() { Assert.Equal(1.7976931348623157e+308, SqlDouble.MaxValue.Value); Assert.Equal(-1.7976931348623157e+308, SqlDouble.MinValue.Value); Assert.True(SqlDouble.Null.IsNull); Assert.Equal(0d, SqlDouble.Zero.Value); } // Test properties [Fact] public void Properties() { SqlDouble Test5443 = new SqlDouble(5443e12); SqlDouble Test1 = new SqlDouble(1); Assert.True(SqlDouble.Null.IsNull); Assert.Equal(5443e12, Test5443.Value); Assert.Equal(1, Test1.Value); } // PUBLIC METHODS [Fact] public void ArithmeticMethods() { SqlDouble Test0 = new SqlDouble(0); SqlDouble Test1 = new SqlDouble(15E+108); SqlDouble Test2 = new SqlDouble(-65E+64); SqlDouble Test3 = new SqlDouble(5E+64); SqlDouble Test4 = new SqlDouble(5E+108); SqlDouble TestMax = new SqlDouble(SqlDouble.MaxValue.Value); // Add() Assert.Equal(15E+108, SqlDouble.Add(Test1, Test0).Value); Assert.Equal(1.5E+109, SqlDouble.Add(Test1, Test2).Value); try { SqlDouble test = SqlDouble.Add(SqlDouble.MaxValue, SqlDouble.MaxValue); Assert.False(true); } catch (OverflowException e) { Assert.Equal(typeof(OverflowException), e.GetType()); } // Divide() Assert.Equal(3, SqlDouble.Divide(Test1, Test4)); Assert.Equal(-13d, SqlDouble.Divide(Test2, Test3).Value); try { SqlDouble test = SqlDouble.Divide(Test1, Test0).Value; Assert.False(true); } catch (DivideByZeroException e) { Assert.Equal(typeof(DivideByZeroException), e.GetType()); } // Multiply() Assert.Equal(75E+216, SqlDouble.Multiply(Test1, Test4).Value); Assert.Equal(0, SqlDouble.Multiply(Test1, Test0).Value); try { SqlDouble test = SqlDouble.Multiply(TestMax, Test1); Assert.False(true); } catch (OverflowException e) { Assert.Equal(typeof(OverflowException), e.GetType()); } // Subtract() Assert.Equal(1.5E+109, SqlDouble.Subtract(Test1, Test3).Value); try { SqlDouble test = SqlDouble.Subtract(SqlDouble.MinValue, SqlDouble.MaxValue); Assert.False(true); } catch (OverflowException e) { Assert.Equal(typeof(OverflowException), e.GetType()); } } [Fact] public void CompareTo() { SqlDouble Test1 = new SqlDouble(4e64); SqlDouble Test11 = new SqlDouble(4e64); SqlDouble Test2 = new SqlDouble(-9e34); SqlDouble Test3 = new SqlDouble(10000); SqlString TestString = new SqlString("This is a test"); Assert.True(Test1.CompareTo(Test3) > 0); Assert.True(Test2.CompareTo(Test3) < 0); Assert.True(Test1.CompareTo(Test11) == 0); Assert.True(Test11.CompareTo(SqlDouble.Null) > 0); try { Test1.CompareTo(TestString); Assert.False(true); } catch (ArgumentException e) { Assert.Equal(typeof(ArgumentException), e.GetType()); } } [Fact] public void EqualsMethods() { SqlDouble Test0 = new SqlDouble(0); SqlDouble Test1 = new SqlDouble(1.58e30); SqlDouble Test2 = new SqlDouble(1.8e180); SqlDouble Test22 = new SqlDouble(1.8e180); Assert.True(!Test0.Equals(Test1)); Assert.True(!Test1.Equals(Test2)); Assert.True(!Test2.Equals(new SqlString("TEST"))); Assert.True(Test2.Equals(Test22)); // Static Equals()-method Assert.True(SqlDouble.Equals(Test2, Test22).Value); Assert.True(!SqlDouble.Equals(Test1, Test2).Value); } [Fact] public void GetHashCodeTest() { SqlDouble Test15 = new SqlDouble(15); // FIXME: Better way to test HashCode Assert.Equal(Test15.GetHashCode(), Test15.GetHashCode()); } [Fact] public void GetTypeTest() { SqlDouble Test = new SqlDouble(84); Assert.Equal("System.Data.SqlTypes.SqlDouble", Test.GetType().ToString()); Assert.Equal("System.Double", Test.Value.GetType().ToString()); } [Fact] public void Greaters() { SqlDouble Test1 = new SqlDouble(1e100); SqlDouble Test11 = new SqlDouble(1e100); SqlDouble Test2 = new SqlDouble(64e164); // GreateThan () Assert.True(!SqlDouble.GreaterThan(Test1, Test2).Value); Assert.True(SqlDouble.GreaterThan(Test2, Test1).Value); Assert.True(!SqlDouble.GreaterThan(Test1, Test11).Value); // GreaterTharOrEqual () Assert.True(!SqlDouble.GreaterThanOrEqual(Test1, Test2).Value); Assert.True(SqlDouble.GreaterThanOrEqual(Test2, Test1).Value); Assert.True(SqlDouble.GreaterThanOrEqual(Test1, Test11).Value); } [Fact] public void Lessers() { SqlDouble Test1 = new SqlDouble(1.8e100); SqlDouble Test11 = new SqlDouble(1.8e100); SqlDouble Test2 = new SqlDouble(64e164); // LessThan() Assert.True(!SqlDouble.LessThan(Test1, Test11).Value); Assert.True(!SqlDouble.LessThan(Test2, Test1).Value); Assert.True(SqlDouble.LessThan(Test11, Test2).Value); // LessThanOrEqual () Assert.True(SqlDouble.LessThanOrEqual(Test1, Test2).Value); Assert.True(!SqlDouble.LessThanOrEqual(Test2, Test1).Value); Assert.True(SqlDouble.LessThanOrEqual(Test11, Test1).Value); Assert.True(SqlDouble.LessThanOrEqual(Test11, SqlDouble.Null).IsNull); } [Fact] public void NotEquals() { SqlDouble Test1 = new SqlDouble(1280000000001); SqlDouble Test2 = new SqlDouble(128e10); SqlDouble Test22 = new SqlDouble(128e10); Assert.True(SqlDouble.NotEquals(Test1, Test2).Value); Assert.True(SqlDouble.NotEquals(Test2, Test1).Value); Assert.True(SqlDouble.NotEquals(Test22, Test1).Value); Assert.True(!SqlDouble.NotEquals(Test22, Test2).Value); Assert.True(!SqlDouble.NotEquals(Test2, Test22).Value); Assert.True(SqlDouble.NotEquals(SqlDouble.Null, Test22).IsNull); Assert.True(SqlDouble.NotEquals(SqlDouble.Null, Test22).IsNull); } [Fact] public void Parse() { try { SqlDouble.Parse(null); Assert.False(true); } catch (ArgumentNullException e) { Assert.Equal(typeof(ArgumentNullException), e.GetType()); } try { SqlDouble.Parse("not-a-number"); Assert.False(true); } catch (FormatException e) { Assert.Equal(typeof(FormatException), e.GetType()); } try { SqlDouble.Parse("9e400"); Assert.False(true); } catch (OverflowException e) { Assert.Equal(typeof(OverflowException), e.GetType()); } Assert.Equal(150, SqlDouble.Parse("150").Value); } [Fact] public void Conversions() { SqlDouble Test0 = new SqlDouble(0); SqlDouble Test1 = new SqlDouble(250); SqlDouble Test2 = new SqlDouble(64e64); SqlDouble Test3 = new SqlDouble(64e164); SqlDouble TestNull = SqlDouble.Null; // ToSqlBoolean () Assert.True(Test1.ToSqlBoolean().Value); Assert.True(!Test0.ToSqlBoolean().Value); Assert.True(TestNull.ToSqlBoolean().IsNull); // ToSqlByte () Assert.Equal((byte)250, Test1.ToSqlByte().Value); Assert.Equal((byte)0, Test0.ToSqlByte().Value); try { SqlByte b = (byte)Test2.ToSqlByte(); Assert.False(true); } catch (OverflowException e) { Assert.Equal(typeof(OverflowException), e.GetType()); } // ToSqlDecimal () Assert.Equal(250.00000000000000M, Test1.ToSqlDecimal().Value); Assert.Equal(0, Test0.ToSqlDecimal().Value); try { SqlDecimal test = Test3.ToSqlDecimal().Value; Assert.False(true); } catch (OverflowException e) { Assert.Equal(typeof(OverflowException), e.GetType()); } // ToSqlInt16 () Assert.Equal((short)250, Test1.ToSqlInt16().Value); Assert.Equal((short)0, Test0.ToSqlInt16().Value); try { SqlInt16 test = Test2.ToSqlInt16().Value; Assert.False(true); } catch (OverflowException e) { Assert.Equal(typeof(OverflowException), e.GetType()); } // ToSqlInt32 () Assert.Equal(250, Test1.ToSqlInt32().Value); Assert.Equal(0, Test0.ToSqlInt32().Value); try { SqlInt32 test = Test2.ToSqlInt32().Value; Assert.False(true); } catch (OverflowException e) { Assert.Equal(typeof(OverflowException), e.GetType()); } // ToSqlInt64 () Assert.Equal(250, Test1.ToSqlInt64().Value); Assert.Equal(0, Test0.ToSqlInt64().Value); try { SqlInt64 test = Test2.ToSqlInt64().Value; Assert.False(true); } catch (OverflowException e) { Assert.Equal(typeof(OverflowException), e.GetType()); } // ToSqlMoney () Assert.Equal(250.0000M, Test1.ToSqlMoney().Value); Assert.Equal(0, Test0.ToSqlMoney().Value); try { SqlMoney test = Test2.ToSqlMoney().Value; Assert.False(true); } catch (OverflowException e) { Assert.Equal(typeof(OverflowException), e.GetType()); } // ToSqlSingle () Assert.Equal(250, Test1.ToSqlSingle().Value); Assert.Equal(0, Test0.ToSqlSingle().Value); try { SqlSingle test = Test2.ToSqlSingle().Value; Assert.False(true); } catch (OverflowException e) { Assert.Equal(typeof(OverflowException), e.GetType()); } // ToSqlString () Assert.Equal("250", Test1.ToSqlString().Value); Assert.Equal("0", Test0.ToSqlString().Value); Assert.Equal("6.4E+65", Test2.ToSqlString().Value); // ToString () Assert.Equal("250", Test1.ToString()); Assert.Equal("0", Test0.ToString()); Assert.Equal("6.4E+65", Test2.ToString()); } // OPERATORS [Fact] public void ArithmeticOperators() { SqlDouble Test0 = new SqlDouble(0); SqlDouble Test1 = new SqlDouble(24E+100); SqlDouble Test2 = new SqlDouble(64E+164); SqlDouble Test3 = new SqlDouble(12E+100); SqlDouble Test4 = new SqlDouble(1E+10); SqlDouble Test5 = new SqlDouble(2E+10); // "+"-operator Assert.Equal(3E+10, Test4 + Test5); try { SqlDouble test = SqlDouble.MaxValue + SqlDouble.MaxValue; Assert.False(true); } catch (OverflowException e) { Assert.Equal(typeof(OverflowException), e.GetType()); } // "/"-operator Assert.Equal(2, Test1 / Test3); try { SqlDouble test = Test3 / Test0; Assert.False(true); } catch (DivideByZeroException e) { Assert.Equal(typeof(DivideByZeroException), e.GetType()); } // "*"-operator Assert.Equal(2e20, Test4 * Test5); try { SqlDouble test = SqlDouble.MaxValue * Test1; Assert.False(true); } catch (OverflowException e) { Assert.Equal(typeof(OverflowException), e.GetType()); } // "-"-operator Assert.Equal(12e100, Test1 - Test3); try { SqlDouble test = SqlDouble.MinValue - SqlDouble.MaxValue; Assert.False(true); } catch (OverflowException e) { Assert.Equal(typeof(OverflowException), e.GetType()); } } [Fact] public void ThanOrEqualOperators() { SqlDouble Test1 = new SqlDouble(1E+164); SqlDouble Test2 = new SqlDouble(9.7E+100); SqlDouble Test22 = new SqlDouble(9.7E+100); SqlDouble Test3 = new SqlDouble(2E+200); // == -operator Assert.True((Test2 == Test22).Value); Assert.True(!(Test1 == Test2).Value); Assert.True((Test1 == SqlDouble.Null).IsNull); // != -operator Assert.True(!(Test2 != Test22).Value); Assert.True((Test2 != Test3).Value); Assert.True((Test1 != Test3).Value); Assert.True((Test1 != SqlDouble.Null).IsNull); // > -operator Assert.True((Test1 > Test2).Value); Assert.True(!(Test1 > Test3).Value); Assert.True(!(Test2 > Test22).Value); Assert.True((Test1 > SqlDouble.Null).IsNull); // >= -operator Assert.True(!(Test1 >= Test3).Value); Assert.True((Test3 >= Test1).Value); Assert.True((Test2 >= Test22).Value); Assert.True((Test1 >= SqlDouble.Null).IsNull); // < -operator Assert.True(!(Test1 < Test2).Value); Assert.True((Test1 < Test3).Value); Assert.True(!(Test2 < Test22).Value); Assert.True((Test1 < SqlDouble.Null).IsNull); // <= -operator Assert.True((Test1 <= Test3).Value); Assert.True(!(Test3 <= Test1).Value); Assert.True((Test2 <= Test22).Value); Assert.True((Test1 <= SqlDouble.Null).IsNull); } [Fact] public void UnaryNegation() { SqlDouble Test = new SqlDouble(2000000001); SqlDouble TestNeg = new SqlDouble(-3000); SqlDouble Result = -Test; Assert.Equal(-2000000001, Result.Value); Result = -TestNeg; Assert.Equal(3000, Result.Value); } [Fact] public void SqlBooleanToSqlDouble() { SqlBoolean TestBoolean = new SqlBoolean(true); SqlDouble Result; Result = (SqlDouble)TestBoolean; Assert.Equal(1, Result.Value); Result = (SqlDouble)SqlBoolean.Null; Assert.True(Result.IsNull); } [Fact] public void SqlDoubleToDouble() { SqlDouble Test = new SqlDouble(12e12); double Result = (double)Test; Assert.Equal(12e12, Result); } [Fact] public void SqlStringToSqlDouble() { SqlString TestString = new SqlString("Test string"); SqlString TestString100 = new SqlString("100"); Assert.Equal(100, ((SqlDouble)TestString100).Value); try { SqlDouble test = (SqlDouble)TestString; Assert.False(true); } catch (FormatException e) { Assert.Equal(typeof(FormatException), e.GetType()); } } [Fact] public void DoubleToSqlDouble() { double Test1 = 5e64; SqlDouble Result = Test1; Assert.Equal(5e64, Result.Value); } [Fact] public void ByteToSqlDouble() { short TestShort = 14; Assert.Equal(14, ((SqlDouble)TestShort).Value); } [Fact] public void SqlDecimalToSqlDouble() { SqlDecimal TestDecimal64 = new SqlDecimal(64); Assert.Equal(64, ((SqlDouble)TestDecimal64).Value); Assert.Equal(SqlDouble.Null, SqlDecimal.Null); } [Fact] public void SqlIntToSqlDouble() { SqlInt16 Test64 = new SqlInt16(64); SqlInt32 Test640 = new SqlInt32(640); SqlInt64 Test64000 = new SqlInt64(64000); Assert.Equal(64, ((SqlDouble)Test64).Value); Assert.Equal(640, ((SqlDouble)Test640).Value); Assert.Equal(64000, ((SqlDouble)Test64000).Value); } [Fact] public void SqlMoneyToSqlDouble() { SqlMoney TestMoney64 = new SqlMoney(64); Assert.Equal(64, ((SqlDouble)TestMoney64).Value); } [Fact] public void SqlSingleToSqlDouble() { SqlSingle TestSingle64 = new SqlSingle(64); Assert.Equal(64, ((SqlDouble)TestSingle64).Value); } [Fact] public void GetXsdTypeTest() { XmlQualifiedName qualifiedName = SqlDouble.GetXsdType(null); Assert.Equal("double", qualifiedName.Name); } internal void ReadWriteXmlTestInternal(string xml, double testval, string unit_test_id) { SqlDouble test; SqlDouble test1; XmlSerializer ser; StringWriter sw; XmlTextWriter xw; StringReader sr; XmlTextReader xr; test = new SqlDouble(testval); ser = new XmlSerializer(typeof(SqlDouble)); sw = new StringWriter(); xw = new XmlTextWriter(sw); ser.Serialize(xw, test); // Assert.Equal (xml, sw.ToString ()); sr = new StringReader(xml); xr = new XmlTextReader(sr); test1 = (SqlDouble)ser.Deserialize(xr); Assert.Equal(testval, test1.Value); } [Fact] //[Category ("MobileNotWorking")] public void ReadWriteXmlTest() { string xml1 = "<?xml version=\"1.0\" encoding=\"utf-16\"?><double>4556.99999999999999999988</double>"; string xml2 = "<?xml version=\"1.0\" encoding=\"utf-16\"?><double>-6445.8888888888899999999</double>"; string xml3 = "<?xml version=\"1.0\" encoding=\"utf-16\"?><double>0x455687AB3E4D56F</double>"; double test1 = 4556.99999999999999999988; double test2 = -6445.8888888888899999999; double test3 = 0x4F56; ReadWriteXmlTestInternal(xml1, test1, "BA01"); ReadWriteXmlTestInternal(xml2, test2, "BA02"); try { ReadWriteXmlTestInternal(xml3, test3, "BA03"); Assert.False(true); } catch (InvalidOperationException e) { Assert.Equal(typeof(FormatException), e.InnerException.GetType()); } } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlTypes; public partial class Backoffice_Controls_EditRegistrasiKUBT : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } public void Draw(string RawatJalanId) { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.RawatJalanId = Int64.Parse(RawatJalanId); DataTable dt = myObj.SelectOne(); if (dt.Rows.Count > 0) { DataRow row = dt.Rows[0]; HFRegistrasiId.Value = row["RegistrasiId"].ToString(); HFRawatJalanId.Value = row["RawatJalanId"].ToString(); HFPasienId.Value = row["PasienId"].ToString(); HFStatusRawatJalan.Value = row["StatusRawatJalan"].ToString(); HFPenjaminId.Value = row["PenjaminId"].ToString() == "" ? "0" : row["PenjaminId"].ToString(); lblNoRM.Text = row["NoRM"].ToString(); lblNamaPasien.Text = row["Nama"].ToString(); //Data Registrasi lblNoRegistrasi.Text = row["NoRegistrasi"].ToString(); txtNoRegistrasi.Text = row["NoRegistrasi"].ToString(); txtTanggalRegistrasi.Text = row["TanggalBerobat"].ToString() != "" ? ((DateTime)row["TanggalBerobat"]).ToString("dd/MM/yyyy") : ""; txtNomorTunggu.Text = row["NomorTunggu"].ToString(); GetListJenisPenjamin(row["JenisPenjaminId"].ToString()); string JenisPenjaminId = row["JenisPenjaminId"].ToString(); GetListHubungan(row["HubunganId"].ToString()); GetListAgama(row["AgamaIdPenjamin"].ToString()); GetListPendidikan(row["PendidikanIdPenjamin"].ToString()); GetListStatus(row["StatusIdPenjamin"].ToString()); GetListPangkatPenjamin(row["PangkatIdPenjamin"].ToString()); if (JenisPenjaminId == "2") { tblPenjaminKeluarga.Visible = true; tblPenjaminPerusahaan.Visible = false; //Data Keluarga Penjamin txtNamaPenjamin.Text = row["NamaPenjamin"].ToString(); txtUmurPenjamin.Text = row["UmurPenjamin"].ToString(); txtAlamatPenjamin.Text = row["AlamatPenjamin"].ToString(); txtTeleponPenjamin.Text = row["TeleponPenjamin"].ToString(); txtNRPPenjamin.Text = row["NRPPenjamin"].ToString(); txtJabatanPenjamin.Text = row["JabatanPenjamin"].ToString(); txtKesatuanPenjamin.Text = row["KesatuanPenjamin"].ToString(); txtAlamatKesatuanPenjamin.Text = row["AlamatKesatuan"].ToString(); txtNoKTPPenjamin.Text = row["NoKTPPenjamin"].ToString(); txtGolDarahPenjamin.Text = row["GolDarahPenjamin"].ToString(); txtKeteranganPenjamin.Text = row["KeteranganPenjamin"].ToString(); } else if (JenisPenjaminId == "3" || JenisPenjaminId == "4") { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = true; txtNamaPerusahaan.Text = row["NamaPenjamin"].ToString(); txtNamaKontak.Text = row["NamaKontakPenjamin"].ToString(); txtAlamatPerusahaan.Text = row["AlamatPenjamin"].ToString(); txtTeleponPerusahaan.Text = row["TeleponPenjamin"].ToString(); txtFAXPerusahaan.Text = row["FaxPenjamin"].ToString(); txtKeteranganPerusahaan.Text = row["KeteranganPenjamin"].ToString(); } else { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = false; } } } public void GetListStatus(string StatusId) { SIMRS.DataAccess.RS_Status myObj = new SIMRS.DataAccess.RS_Status(); DataTable dt = myObj.GetList(); cmbStatusPenjamin.Items.Clear(); int i = 0; cmbStatusPenjamin.Items.Add(""); cmbStatusPenjamin.Items[i].Text = ""; cmbStatusPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbStatusPenjamin.Items.Add(""); cmbStatusPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbStatusPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == StatusId) { cmbStatusPenjamin.SelectedIndex = i; } i++; } } public void GetListPangkatPenjamin(string PangkatId) { SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat(); if (cmbStatusPenjamin.SelectedIndex > 0) myObj.StatusId = int.Parse(cmbStatusPenjamin.SelectedItem.Value); DataTable dt = myObj.GetListByStatusId(); cmbPangkatPenjamin.Items.Clear(); int i = 0; cmbPangkatPenjamin.Items.Add(""); cmbPangkatPenjamin.Items[i].Text = ""; cmbPangkatPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPangkatPenjamin.Items.Add(""); cmbPangkatPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbPangkatPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PangkatId) { cmbPangkatPenjamin.SelectedIndex = i; } i++; } } public void GetNomorTunggu() { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.PoliklinikId = 26;//KUBT myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); txtNomorTunggu.Text = myObj.GetNomorTunggu().ToString(); } public void GetListAgama(string AgamaId) { BkNet.DataAccess.Agama myObj = new BkNet.DataAccess.Agama(); DataTable dt = myObj.GetList(); cmbAgamaPenjamin.Items.Clear(); int i = 0; cmbAgamaPenjamin.Items.Add(""); cmbAgamaPenjamin.Items[i].Text = ""; cmbAgamaPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbAgamaPenjamin.Items.Add(""); cmbAgamaPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbAgamaPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == AgamaId) cmbAgamaPenjamin.SelectedIndex = i; i++; } } public void GetListPendidikan(string PendidikanId) { BkNet.DataAccess.Pendidikan myObj = new BkNet.DataAccess.Pendidikan(); DataTable dt = myObj.GetList(); cmbPendidikanPenjamin.Items.Clear(); int i = 0; cmbPendidikanPenjamin.Items.Add(""); cmbPendidikanPenjamin.Items[i].Text = ""; cmbPendidikanPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPendidikanPenjamin.Items.Add(""); cmbPendidikanPenjamin.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString(); cmbPendidikanPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PendidikanId) cmbPendidikanPenjamin.SelectedIndex = i; i++; } } public void GetListJenisPenjamin(string JenisPenjaminId) { SIMRS.DataAccess.RS_JenisPenjamin myObj = new SIMRS.DataAccess.RS_JenisPenjamin(); DataTable dt = myObj.GetList(); cmbJenisPenjamin.Items.Clear(); int i = 0; foreach (DataRow dr in dt.Rows) { cmbJenisPenjamin.Items.Add(""); cmbJenisPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbJenisPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == JenisPenjaminId) cmbJenisPenjamin.SelectedIndex = i; i++; } } public void GetListHubungan(string HubunganId) { SIMRS.DataAccess.RS_Hubungan myObj = new SIMRS.DataAccess.RS_Hubungan(); DataTable dt = myObj.GetList(); cmbHubungan.Items.Clear(); int i = 0; cmbHubungan.Items.Add(""); cmbHubungan.Items[i].Text = ""; cmbHubungan.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbHubungan.Items.Add(""); cmbHubungan.Items[i].Text = dr["Nama"].ToString(); cmbHubungan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == HubunganId) cmbHubungan.SelectedIndex = i; i++; } } public void GetNomorRegistrasi() { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.PoliklinikId = 26;//KUBT myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); txtNoRegistrasi.Text = myObj.GetNomorRegistrasi(); } public bool OnSave() { bool result = false; lblError.Text = ""; if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (!Page.IsValid) { return false; } SIMRS.DataAccess.RS_Penjamin myPenj = new SIMRS.DataAccess.RS_Penjamin(); myPenj.PenjaminId = Int64.Parse(HFPenjaminId.Value); myPenj.SelectOne(); if (cmbJenisPenjamin.SelectedIndex > 0) { //Input Data Penjamin if (cmbJenisPenjamin.SelectedIndex == 1) { if (cmbHubungan.SelectedIndex > 0) myPenj.HubunganId = int.Parse(cmbHubungan.SelectedItem.Value); myPenj.Nama = txtNamaPenjamin.Text; myPenj.Umur = txtUmurPenjamin.Text; myPenj.Alamat = txtAlamatPenjamin.Text; myPenj.Telepon = txtTeleponPenjamin.Text; if (cmbAgamaPenjamin.SelectedIndex > 0) myPenj.AgamaId = int.Parse(cmbAgamaPenjamin.SelectedItem.Value); if (cmbPendidikanPenjamin.SelectedIndex > 0) myPenj.PendidikanId = int.Parse(cmbPendidikanPenjamin.SelectedItem.Value); if (cmbStatusPenjamin.SelectedIndex > 0) myPenj.StatusId = int.Parse(cmbStatusPenjamin.SelectedItem.Value); if (cmbPangkatPenjamin.SelectedIndex > 0) myPenj.PangkatId = int.Parse(cmbPangkatPenjamin.SelectedItem.Value); myPenj.NRP = txtNRPPenjamin.Text; myPenj.Jabatan = txtJabatanPenjamin.Text; myPenj.Kesatuan = txtKesatuanPenjamin.Text; myPenj.AlamatKesatuan = txtAlamatKesatuanPenjamin.Text; myPenj.NoKTP = txtNoKTPPenjamin.Text; myPenj.GolDarah = txtGolDarahPenjamin.Text; myPenj.Keterangan = txtKeteranganPenjamin.Text; } else { myPenj.Nama = txtNamaPerusahaan.Text; myPenj.NamaKontak = txtNamaKontak.Text; myPenj.Alamat = txtAlamatPerusahaan.Text; myPenj.Telepon = txtTeleponPerusahaan.Text; myPenj.Fax = txtFAXPerusahaan.Text; } if (HFPenjaminId.Value == "0") { myPenj.CreatedBy = UserId; myPenj.CreatedDate = DateTime.Now; result = myPenj.Insert(); } else { myPenj.ModifiedBy = UserId; myPenj.ModifiedDate = DateTime.Now; result = myPenj.Update(); } HFPenjaminId.Value = myPenj.PenjaminId.ToString(); } else { if (HFPenjaminId.Value != "0") myPenj.Delete(); HFPenjaminId.Value = "0"; } //Input Data Registrasi SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi(); myReg.RegistrasiId = Int64.Parse(HFRegistrasiId.Value); myReg.SelectOne(); //GetNomorRegistrasi(); myReg.NoRegistrasi = txtNoRegistrasi.Text; myReg.JenisRegistrasiId = 1; myReg.TanggalRegistrasi = DateTime.Parse(txtTanggalRegistrasi.Text); myReg.JenisPenjaminId = int.Parse(cmbJenisPenjamin.SelectedItem.Value); if (cmbJenisPenjamin.SelectedIndex > 0) myReg.PenjaminId = Int64.Parse(HFPenjaminId.Value); else myReg.PenjaminId = SqlInt64.Null; myReg.ModifiedBy = UserId; myReg.ModifiedDate = DateTime.Now; result = myReg.Update(); //Update Data Rawat Jalan SIMRS.DataAccess.RS_RawatJalan myRJ = new SIMRS.DataAccess.RS_RawatJalan(); myRJ.RawatJalanId = Int64.Parse(HFRawatJalanId.Value); myRJ.SelectOne(); myRJ.RegistrasiId = myReg.RegistrasiId; myRJ.PoliklinikId = 26;//KUBT myRJ.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); //GetNomorTunggu(); if (txtNomorTunggu.Text != "") myRJ.NomorTunggu = int.Parse(txtNomorTunggu.Text); myRJ.Status = 0;//Baru daftar myRJ.ModifiedBy = UserId; myRJ.ModifiedDate = DateTime.Now; result = myRJ.Update(); return result; //string CurrentPage = ""; //if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") // CurrentPage = Request.QueryString["CurrentPage"].ToString(); //Response.Redirect("RJView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + myRJ.RawatJalanId); } public void OnCancel() { //string CurrentPage = ""; //if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") // CurrentPage = Request.QueryString["CurrentPage"].ToString(); //Response.Redirect("RJList.aspx?CurrentPage=" + CurrentPage); } protected void cmbJenisPenjamin_SelectedIndexChanged(object sender, EventArgs e) { if (cmbJenisPenjamin.SelectedIndex == 1) { tblPenjaminKeluarga.Visible = true; tblPenjaminPerusahaan.Visible = false; } else if (cmbJenisPenjamin.SelectedIndex == 2 || cmbJenisPenjamin.SelectedIndex == 3) { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = true; } else { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = false; } } protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e) { GetNomorTunggu(); GetNomorRegistrasi(); } protected void cmbStatusPenjamin_SelectedIndexChanged(object sender, EventArgs e) { GetListPangkatPenjamin(""); } }
using Microsoft.Win32.SafeHandles; using System; using System.Data; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; /* The following code is adapted from "generichid_cs_46" USB application example by Jan Axelson for more information see see http://www.lvr.com/hidpage.htm */ /// <summary> /// For communicating with HID-class USB devices. /// The ReportIn class handles Input reports and Feature reports that carry data to the host. /// The ReportOut class handles Output reports and Feature reports that that carry data to the device. /// Other routines retrieve information about and configure the HID. /// </summary> /// using TrackRoamer.Robotics.Utility.LibSystem; namespace TrackRoamer.Robotics.Utility.LibLvrGenericHid { public class AsyncInputReportArgs : EventArgs { public byte[] InputBuffer; } public sealed partial class Hid { // Used in error messages. private const String MODULE_NAME = "Hid"; public HIDP_CAPS Capabilities; public HIDD_ATTRIBUTES DeviceAttributes; // For viewing results of API calls in debug.write statements: public static Debugging MyDebugging = new Debugging(); /// <summary> /// For reports the device sends to the host. /// </summary> public abstract class ReportIn { /// <summary> /// Each class that handles reading reports defines a Read method for reading /// a type of report. Read is declared as a Sub rather /// than as a Function because asynchronous reads use a callback method /// that can access parameters passed by ByRef but not Function return values. /// </summary> public abstract void Read(SafeFileHandle hidHandle, SafeFileHandle readHandle, SafeFileHandle writeHandle, ref Boolean myDeviceDetected, ref Byte[] readBuffer, ref Boolean success); // An event that clients can use to be notified whenever the Read() delivered a buffer: public event EventHandler<AsyncInputReportArgs> HasReadData; // Invoke the HasReadData event; called whenever the Read completes: protected virtual void OnDataReadComplete(AsyncInputReportArgs e) { if (HasReadData != null) { HasReadData(this, e); } } } /// <summary> /// For reading Feature reports. /// </summary> public class InFeatureReport : ReportIn { /// <summary> /// reads a Feature report from the device. /// </summary> /// /// <param name="hidHandle"> the handle for learning about the device and exchanging Feature reports. </param> /// <param name="readHandle"> the handle for reading Input reports from the device. </param> /// <param name="writeHandle"> the handle for writing Output reports to the device. </param> /// <param name="myDeviceDetected"> tells whether the device is currently attached.</param> /// <param name="inFeatureReportBuffer"> contains the requested report.</param> /// <param name="success"> read success</param> public override void Read(SafeFileHandle hidHandle, SafeFileHandle readHandle, SafeFileHandle writeHandle, ref Boolean myDeviceDetected, ref Byte[] inFeatureReportBuffer, ref Boolean success) { try { // *** // API function: HidD_GetFeature // Attempts to read a Feature report from the device. // Requires: // A handle to a HID // A pointer to a buffer containing the report ID and report // The size of the buffer. // Returns: true on success, false on failure. // *** success = HidD_GetFeature(hidHandle, inFeatureReportBuffer, inFeatureReportBuffer.Length); Tracer.Trace( "HidD_GetFeature success = " + success ); } catch ( Exception ex ) { DisplayException( MODULE_NAME, ex ); throw ; } } } /// <summary> /// For reading Input reports via control transfers /// </summary> public class InputReportViaControlTransfer : ReportIn { /// <summary> /// reads an Input report from the device using a control transfer. /// </summary> /// /// <param name="hidHandle"> the handle for learning about the device and exchanging Feature reports. </param> /// <param name="readHandle"> the handle for reading Input reports from the device. </param> /// <param name="writeHandle"> the handle for writing Output reports to the device. </param> /// <param name="myDeviceDetected"> tells whether the device is currently attached. </param> /// <param name="inputReportBuffer"> contains the requested report. </param> /// <param name="success"> read success </param> public override void Read(SafeFileHandle hidHandle, SafeFileHandle readHandle, SafeFileHandle writeHandle, ref Boolean myDeviceDetected, ref Byte[] inputReportBuffer, ref Boolean success) { try { // *** // API function: HidD_GetInputReport // Purpose: Attempts to read an Input report from the device using a control transfer. // Supported under Windows XP and later only. // Requires: // A handle to a HID // A pointer to a buffer containing the report ID and report // The size of the buffer. // Returns: true on success, false on failure. // *** success = HidD_GetInputReport(hidHandle, inputReportBuffer, inputReportBuffer.Length + 1); Tracer.Trace("HidD_GetInputReport success = " + success); } catch ( Exception ex ) { DisplayException( MODULE_NAME, ex ); throw ; } } } /// <summary> /// For reading Input reports. /// </summary> public class InputReportViaInterruptTransfer : ReportIn { /// <summary> /// closes open handles to a device. /// </summary> /// /// <param name="hidHandle"> the handle for learning about the device and exchanging Feature reports. </param> /// <param name="readHandle"> the handle for reading Input reports from the device. </param> /// <param name="writeHandle"> the handle for writing Output reports to the device. </param> public void CancelTransfer(SafeFileHandle hidHandle, SafeFileHandle readHandle, SafeFileHandle writeHandle, IntPtr eventObject) { try { // *** // API function: CancelIo // Purpose: Cancels a call to ReadFile // Accepts: the device handle. // Returns: True on success, False on failure. // *** FileIO.CancelIo(readHandle); Tracer.Error("************ReadFile error*************"); String functionName = "CancelIo"; Tracer.Trace(MyDebugging.ResultOfAPICall(functionName)); // The failure may have been because the device was removed, // so close any open handles and // set myDeviceDetected=False to cause the application to // look for the device on the next attempt. if ( ( !( hidHandle.IsInvalid ) ) ) { hidHandle.Close(); } if ( ( !( readHandle.IsInvalid ) ) ) { readHandle.Close(); } if ( ( !( writeHandle.IsInvalid ) ) ) { writeHandle.Close(); } } catch ( Exception ex ) { DisplayException( MODULE_NAME, ex ); throw ; } } /// <summary> /// Creates an event object for the overlapped structure used with ReadFile. /// </summary> /// /// <param name="hidOverlapped"> the overlapped structure </param> /// <param name="eventObject"> the event object </param> public void PrepareForOverlappedTransfer(ref NativeOverlapped hidOverlapped, ref IntPtr eventObject) { try { // *** // API function: CreateEvent // Purpose: Creates an event object for the overlapped structure used with ReadFile. // Accepts: // A security attributes structure or IntPtr.Zero. // Manual Reset = False (The system automatically resets the state to nonsignaled // after a waiting thread has been released.) // Initial state = False (not signaled) // An event object name (optional) // Returns: a handle to the event object // *** eventObject = FileIO.CreateEvent(IntPtr.Zero, false, false, ""); // Set the members of the overlapped structure. hidOverlapped.OffsetLow = 0; hidOverlapped.OffsetHigh = 0; hidOverlapped.EventHandle = eventObject; } catch ( Exception ex ) { DisplayException( MODULE_NAME, ex ); throw ; } } /// <summary> /// reads an Input report from the device using interrupt transfers. /// </summary> /// /// <param name="hidHandle"> the handle for learning about the device and exchanging Feature reports. </param> /// <param name="readHandle"> the handle for reading Input reports from the device. </param> /// <param name="writeHandle"> the handle for writing Output reports to the device. </param> /// <param name="myDeviceDetected"> tells whether the device is currently attached. </param> /// <param name="inputReportBuffer"> contains the requested report. </param> /// <param name="success"> read success </param> public override void Read(SafeFileHandle hidHandle, SafeFileHandle readHandle, SafeFileHandle writeHandle, ref Boolean myDeviceDetected, ref Byte[] inputReportBuffer, ref Boolean success) { IntPtr eventObject = IntPtr.Zero; NativeOverlapped HidOverlapped = new NativeOverlapped(); IntPtr nonManagedBuffer = IntPtr.Zero; IntPtr nonManagedOverlapped = IntPtr.Zero; Int32 numberOfBytesRead = 0; Int32 result = 0; try { // Set up the overlapped structure for ReadFile. PrepareForOverlappedTransfer( ref HidOverlapped, ref eventObject ); // Allocate memory for the input buffer and overlapped structure. nonManagedBuffer = Marshal.AllocHGlobal(inputReportBuffer.Length); nonManagedOverlapped = Marshal.AllocHGlobal(Marshal.SizeOf(HidOverlapped)); Marshal.StructureToPtr(HidOverlapped, nonManagedOverlapped, false); // *** // API function: ReadFile // Purpose: Attempts to read an Input report from the device. // Accepts: // A device handle returned by CreateFile // (for overlapped I/O, CreateFile must have been called with FILE_FLAG_OVERLAPPED), // A pointer to a buffer for storing the report. // The Input report length in bytes returned by HidP_GetCaps, // A pointer to a variable that will hold the number of bytes read. // An overlapped structure whose hEvent member is set to an event object. // Returns: the report in ReadBuffer. // The overlapped call returns immediately, even if the data hasn't been received yet. // To read multiple reports with one ReadFile, increase the size of ReadBuffer // and use NumberOfBytesRead to determine how many reports were returned. // Use a larger buffer if the application can't keep up with reading each report // individually. // *** success = FileIO.ReadFile(readHandle, nonManagedBuffer, inputReportBuffer.Length, ref numberOfBytesRead, nonManagedOverlapped); if (!success) { //Tracer.Trace("waiting for ReadFile"); // API function: WaitForSingleObject // Purpose: waits for at least one report or a timeout. // Used with overlapped ReadFile. // Accepts: // An event object created with CreateEvent // A timeout value in milliseconds. // Returns: A result code. result = FileIO.WaitForSingleObject(eventObject, 3000); // Find out if ReadFile completed or timeout. switch (result) { case (System.Int32)FileIO.WAIT_OBJECT_0: // ReadFile has completed success = true; //Tracer.Trace("ReadFile completed successfully."); // Get the number of bytes read. // API function: GetOverlappedResult // Purpose: gets the result of an overlapped operation. // Accepts: // A device handle returned by CreateFile. // A pointer to an overlapped structure. // A pointer to a variable to hold the number of bytes read. // False to return immediately. // Returns: non-zero on success and the number of bytes read. FileIO.GetOverlappedResult(readHandle, nonManagedOverlapped, ref numberOfBytesRead, false); break; case FileIO.WAIT_TIMEOUT: // Cancel the operation on timeout CancelTransfer(hidHandle, readHandle, writeHandle, eventObject); Tracer.Error("Readfile timeout"); success = false; myDeviceDetected = false; break; default: // Cancel the operation on other error. CancelTransfer(hidHandle, readHandle, writeHandle, eventObject); Tracer.Error("Readfile undefined error"); success = false; myDeviceDetected = false; break; } } if (success) { // A report was received. // Copy the received data to inputReportBuffer for the application to use. Marshal.Copy(nonManagedBuffer, inputReportBuffer, 0, numberOfBytesRead); AsyncInputReportArgs args = new AsyncInputReportArgs(); args.InputBuffer = inputReportBuffer; OnDataReadComplete(args); } } catch ( Exception ex ) { DisplayException( MODULE_NAME, ex ); throw ; } } } /// <summary> /// For reports the host sends to the device. /// </summary> public abstract class ReportOut { /// <summary> /// Each class that handles writing reports defines a Write method for /// writing a type of report. /// </summary> /// /// <param name="reportBuffer"> contains the report ID and report data. </param> /// <param name="deviceHandle"> handle to the device. </param> /// /// <returns> /// True on success. False on failure. /// </returns> public abstract Boolean Write(Byte[] reportBuffer, SafeFileHandle deviceHandle); } /// <summary> /// For Feature reports the host sends to the device. /// </summary> public class OutFeatureReport : ReportOut { /// <summary> /// writes a Feature report to the device. /// </summary> /// /// <param name="outFeatureReportBuffer"> contains the report ID and report data. </param> /// <param name="hidHandle"> handle to the device. </param> /// /// <returns> /// True on success. False on failure. /// </returns> public override Boolean Write(Byte[] outFeatureReportBuffer, SafeFileHandle hidHandle) { Boolean success = false; try { // *** // API function: HidD_SetFeature // Purpose: Attempts to send a Feature report to the device. // Accepts: // A handle to a HID // A pointer to a buffer containing the report ID and report // The size of the buffer. // Returns: true on success, false on failure. // *** success = HidD_SetFeature(hidHandle, outFeatureReportBuffer, outFeatureReportBuffer.Length); Debug.Print( "HidD_SetFeature success = " + success ); return success; } catch ( Exception ex ) { DisplayException( MODULE_NAME, ex ); throw ; } } } /// <summary> /// For writing Output reports via control transfers /// </summary> public class OutputReportViaControlTransfer : ReportOut { /// <summary> /// writes an Output report to the device using a control transfer. /// </summary> /// /// <param name="outputReportBuffer"> contains the report ID and report data. </param> /// <param name="hidHandle"> handle to the device. </param> /// /// <returns> /// True on success. False on failure. /// </returns> public override Boolean Write(Byte[] outputReportBuffer, SafeFileHandle hidHandle) { Boolean success = false; try { // *** // API function: HidD_SetOutputReport // Purpose: // Attempts to send an Output report to the device using a control transfer. // Requires Windows XP or later. // Accepts: // A handle to a HID // A pointer to a buffer containing the report ID and report // The size of the buffer. // Returns: true on success, false on failure. // *** success = HidD_SetOutputReport(hidHandle, outputReportBuffer, outputReportBuffer.Length + 1); Debug.Print( "HidD_SetOutputReport success = " + success ); return success; } catch ( Exception ex ) { DisplayException( MODULE_NAME, ex ); throw ; } } } /// <summary> /// For Output reports the host sends to the device. /// Uses interrupt or control transfers depending on the device and OS. /// </summary> public class OutputReportViaInterruptTransfer : ReportOut { /// <summary> /// writes an Output report to the device. /// </summary> /// /// <param name="outputReportBuffer"> contains the report ID and report data. </param> /// <param name="writeHandle"> handle to the device. </param> /// /// <returns> /// True on success. False on failure. /// </returns> public override Boolean Write(Byte[] outputReportBuffer, SafeFileHandle writeHandle) { Int32 numberOfBytesWritten = 0; Boolean success = false; try { // The host will use an interrupt transfer if the the HID has an interrupt OUT // endpoint (requires USB 1.1 or later) AND the OS is NOT Windows 98 Gold (original version). // Otherwise the the host will use a control transfer. // The application doesn't have to know or care which type of transfer is used. numberOfBytesWritten = 0; // *** // API function: WriteFile // Purpose: writes an Output report to the device. // Accepts: // A handle returned by CreateFile // An integer to hold the number of bytes written. // Returns: True on success, False on failure. // *** success = FileIO.WriteFile(writeHandle, outputReportBuffer, outputReportBuffer.Length, ref numberOfBytesWritten, IntPtr.Zero); Debug.Print( "WriteFile success = " + success ); if ( !( ( success ) ) ) { if ( ( !( writeHandle.IsInvalid ) ) ) { writeHandle.Close(); } } return success; } catch ( Exception ex ) { DisplayException( MODULE_NAME, ex ); throw ; } } } /// <summary> /// Remove any Input reports waiting in the buffer. /// </summary> /// /// <param name="hidHandle"> a handle to a device. </param> /// /// <returns> /// True on success, False on failure. /// </returns> public Boolean FlushQueue(SafeFileHandle hidHandle) { Boolean success = false; try { // *** // API function: HidD_FlushQueue // Purpose: Removes any Input reports waiting in the buffer. // Accepts: a handle to the device. // Returns: True on success, False on failure. // *** success = HidD_FlushQueue( hidHandle ); return success; } catch ( Exception ex ) { DisplayException( MODULE_NAME, ex ); throw ; } } /// <summary> /// Retrieves a structure with information about a device's capabilities. /// </summary> /// /// <param name="hidHandle"> a handle to a device. </param> /// /// <returns> /// An HIDP_CAPS structure. /// </returns> public HIDP_CAPS GetDeviceCapabilities(SafeFileHandle hidHandle) { IntPtr preparsedData = new System.IntPtr(); Int32 result = 0; Boolean success = false; //Byte[] valueCaps = new Byte[ 1024 ]; // (the array size is a guess) try { // *** // API function: HidD_GetPreparsedData // Purpose: retrieves a pointer to a buffer containing information about the device's capabilities. // HidP_GetCaps and other API functions require a pointer to the buffer. // Requires: // A handle returned by CreateFile. // A pointer to a buffer. // Returns: // True on success, False on failure. // *** success = HidD_GetPreparsedData(hidHandle, ref preparsedData); // *** // API function: HidP_GetCaps // Purpose: find out a device's capabilities. // For standard devices such as joysticks, you can find out the specific // capabilities of the device. // For a custom device where the software knows what the device is capable of, // this call may be unneeded. // Accepts: // A pointer returned by HidD_GetPreparsedData // A pointer to a HIDP_CAPS structure. // Returns: True on success, False on failure. // *** result = HidP_GetCaps(preparsedData, ref Capabilities); if ((result != 0)) { Tracer.Trace(" Usage: " + Convert.ToString(Capabilities.Usage, 16) + "\r\n Usage Page: " + Convert.ToString(Capabilities.UsagePage, 16) + "\r\n Input Report Byte Length: " + Capabilities.InputReportByteLength + "\r\n Output Report Byte Length: " + Capabilities.OutputReportByteLength + "\r\n Feature Report Byte Length: " + Capabilities.FeatureReportByteLength + "\r\n Number of Link Collection Nodes: " + Capabilities.NumberLinkCollectionNodes + "\r\n Number of Input Button Caps: " + Capabilities.NumberInputButtonCaps + "\r\n Number of Input Value Caps: " + Capabilities.NumberInputValueCaps + "\r\n Number of Input Data Indices: " + Capabilities.NumberInputDataIndices + "\r\n Number of Output Button Caps: " + Capabilities.NumberOutputButtonCaps + "\r\n Number of Output Value Caps: " + Capabilities.NumberOutputValueCaps + "\r\n Number of Output Data Indices: " + Capabilities.NumberOutputDataIndices + "\r\n Number of Feature Button Caps: " + Capabilities.NumberFeatureButtonCaps + "\r\n Number of Feature Value Caps: " + Capabilities.NumberFeatureValueCaps + "\r\n Number of Feature Data Indices: " + Capabilities.NumberFeatureDataIndices); // *** // API function: HidP_GetValueCaps // Purpose: retrieves a buffer containing an array of HidP_ValueCaps structures. // Each structure defines the capabilities of one value. // This application doesn't use this data. // Accepts: // A report type enumerator from hidpi.h, // A pointer to a buffer for the returned array, // The NumberInputValueCaps member of the device's HidP_Caps structure, // A pointer to the PreparsedData structure returned by HidD_GetPreparsedData. // Returns: True on success, False on failure. // *** Int32 vcSize = Capabilities.NumberInputValueCaps; Byte[] valueCaps = new Byte[vcSize]; result = HidP_GetValueCaps(HidP_Input, valueCaps, ref vcSize, preparsedData); //result = HidP_GetValueCaps(HidP_Input, ref valueCaps[0], ref Capabilities.NumberInputValueCaps, preparsedData); // (To use this data, copy the ValueCaps byte array into an array of structures.) } } catch (Exception ex) { DisplayException(MODULE_NAME, ex); throw; } finally { // *** // API function: HidD_FreePreparsedData // Purpose: frees the buffer reserved by HidD_GetPreparsedData. // Accepts: A pointer to the PreparsedData structure returned by HidD_GetPreparsedData. // Returns: True on success, False on failure. // *** if (preparsedData != IntPtr.Zero) { success = HidD_FreePreparsedData(preparsedData); } } return Capabilities; } /// <summary> /// Creates a 32-bit Usage from the Usage Page and Usage ID. /// Determines whether the Usage is a system mouse or keyboard. /// Can be modified to detect other Usages. /// </summary> /// /// <param name="MyCapabilities"> a HIDP_CAPS structure retrieved with HidP_GetCaps. </param> /// /// <returns> /// A String describing the Usage. /// </returns> public String GetHidUsage(HIDP_CAPS MyCapabilities) { Int32 usage = 0; String usageDescription = ""; try { // Create32-bit Usage from Usage Page and Usage ID. usage = MyCapabilities.UsagePage * 256 + MyCapabilities.Usage; if ( usage == Convert.ToInt32( 0X102 ) ) { usageDescription = "mouse"; } if ( usage == Convert.ToInt32( 0X106 ) ) { usageDescription = "keyboard"; } } catch ( Exception ex ) { DisplayException( MODULE_NAME, ex ); throw ; } return usageDescription; } /// <summary> /// Retrieves the number of Input reports the host can store. /// </summary> /// /// <param name="hidDeviceObject"> a handle to a device </param> /// <param name="numberOfInputBuffers"> an integer to hold the returned value. </param> /// /// <returns> /// True on success, False on failure. /// </returns> public Boolean GetNumberOfInputBuffers(SafeFileHandle hidDeviceObject, ref Int32 numberOfInputBuffers) { Boolean success = false; try { // *** // API function: HidD_GetNumInputBuffers // Purpose: retrieves the number of Input reports the host can store. // Not supported by Windows 98 Gold. // If the buffer is full and another report arrives, the host drops the // ldest report. // Accepts: a handle to a device and an integer to hold the number of buffers. // Returns: True on success, False on failure. // *** success = HidD_GetNumInputBuffers(hidDeviceObject, ref numberOfInputBuffers); return success; } catch (Exception ex) { DisplayException( MODULE_NAME, ex ); throw ; } } /// <summary> /// sets the number of input reports the host will store. /// Requires Windows XP or later. /// </summary> /// /// <param name="hidDeviceObject"> a handle to the device.</param> /// <param name="numberBuffers"> the requested number of input reports. </param> /// /// <returns> /// True on success. False on failure. /// </returns> public Boolean SetNumberOfInputBuffers(SafeFileHandle hidDeviceObject, Int32 numberBuffers) { try { // *** // API function: HidD_SetNumInputBuffers // Purpose: Sets the number of Input reports the host can store. // If the buffer is full and another report arrives, the host drops the // oldest report. // Requires: // A handle to a HID // An integer to hold the number of buffers. // Returns: true on success, false on failure. // *** HidD_SetNumInputBuffers( hidDeviceObject, numberBuffers ); return true; } catch ( Exception ex ) { DisplayException( MODULE_NAME, ex ); throw ; } } /// <summary> /// Find out if the current operating system is Windows XP or later. /// (Windows XP or later is required for HidD_GetInputReport and HidD_SetInputReport.) /// </summary> public Boolean IsWindowsXpOrLater() { try { OperatingSystem myEnvironment = Environment.OSVersion; // Windows XP is version 5.1. System.Version versionXP = new System.Version( 5, 1 ); if (myEnvironment.Version >= versionXP) { Debug.Write( "The OS is Windows XP or later." ); return true; } else { Debug.Write( "The OS is earlier than Windows XP." ); return false; } } catch ( Exception ex ) { DisplayException( MODULE_NAME, ex ); throw ; } } /// <summary> /// Provides a central mechanism for exception handling. /// Displays a message box that describes the exception. /// </summary> /// /// <param name="moduleName"> the module where the exception occurred. </param> /// <param name="e"> the exception </param> public static void DisplayException(String moduleName, Exception e) { Tracer.Error(e); String message = null; String caption = null; // Create an error message. message = "Exception: " + e.Message + "\r\nModule: " + moduleName + "\r\nMethod: " + e.TargetSite.Name; caption = "Unexpected Exception"; MessageBox.Show( message, caption, MessageBoxButtons.OK ); } } }
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 WebApplication2.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; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update { using Microsoft.Azure.Management.Network.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Update; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using Microsoft.Azure.Management.Network.Fluent.NicIPConfiguration.Update; using Microsoft.Azure.Management.Network.Fluent.NicIPConfiguration.UpdateDefinition; /// <summary> /// The template for an update operation, containing all the settings that /// can be modified. /// </summary> public interface IUpdate : Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IAppliable<Microsoft.Azure.Management.Network.Fluent.INetworkInterface>, Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Update.IUpdateWithTags<Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate>, Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IWithPrimaryNetworkSubnet, Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IWithPrimaryPrivateIP, Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IWithPrimaryPublicIPAddress, Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IWithNetworkSecurityGroup, Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IWithIPForwarding, Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IWithDnsServer, Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IWithIPConfiguration, Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IWithLoadBalancer, Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IWithAcceleratedNetworking { } /// <summary> /// The stage of the network interface definition allowing to disable accelerated networking. /// </summary> public interface IWithAcceleratedNetworking { /// <summary> /// Disables accelerated networking. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithoutAcceleratedNetworking(); } /// <summary> /// The stage of the network interface update allowing to specify private IP address within /// a virtual network subnet. /// </summary> public interface IWithPrimaryPrivateIP { /// <summary> /// Enables dynamic private IP address allocation within the specified existing virtual network /// subnet for the network interface's primary IP configuration. /// </summary> /// <return>The next stage of network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithPrimaryPrivateIPAddressDynamic(); /// <summary> /// Assigns the specified static private IP address within the specified existing virtual network /// subnet to the network interface's primary IP configuration. /// </summary> /// <param name="staticPrivateIPAddress"> /// The static IP address within the specified subnet to assign to /// the primary IP configuration. /// </param> /// <return>The next stage of network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithPrimaryPrivateIPAddressStatic(string staticPrivateIPAddress); } /// <summary> /// The stage of the network interface update allowing to associate public IP address with it's primary /// IP configuration. /// </summary> public interface IWithPrimaryPublicIPAddress { /// <summary> /// Associates an existing public IP address with the network interface's primary IP configuration. /// if there is an existing public IP association then that will be removed in favour of this. /// </summary> /// <param name="publicIPAddress">An existing public IP address.</param> /// <return>The next stage of the network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithExistingPrimaryPublicIPAddress(IPublicIPAddress publicIPAddress); /// <summary> /// Create a new public IP address to associate the network interface's primary IP configuration, /// based on the provided definition. /// if there is public IP associated with the primary IP configuration then that will be removed in /// favour of this. /// </summary> /// <param name="creatable">A creatable definition for a new public IP.</param> /// <return>The next stage of the network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithNewPrimaryPublicIPAddress(ICreatable<Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress> creatable); /// <summary> /// Creates a new public IP address in the same region and group as the resource and associate it /// with the network interface's primary IP configuration. /// the internal name and DNS label for the public IP address will be derived from the network interface name, /// if there is an existing public IP association then that will be removed in favour of this. /// </summary> /// <return>The next stage of the network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithNewPrimaryPublicIPAddress(); /// <summary> /// Creates a new public IP address in the same region and group as the resource, with the specified DNS label /// and associate it with the network interface's primary IP configuration. /// the internal name for the public IP address will be derived from the DNS label, if there is an existing /// public IP association then that will be removed in favour of this. /// </summary> /// <param name="leafDnsLabel">The leaf domain label.</param> /// <return>The next stage of the network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithNewPrimaryPublicIPAddress(string leafDnsLabel); /// <summary> /// Specifies that remove any public IP associated with the network interface's primary IP configuration. /// </summary> /// <return>The next stage of the network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithoutPrimaryPublicIPAddress(); } /// <summary> /// The stage of the network interface update allowing to configure IP configuration. /// </summary> public interface IWithIPConfiguration { /// <summary> /// Starts definition of a secondary IP configuration. /// </summary> /// <param name="name">Name for the IP configuration.</param> /// <return>The first stage of the update.</return> Microsoft.Azure.Management.Network.Fluent.NicIPConfiguration.UpdateDefinition.IBlank<Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate> DefineSecondaryIPConfiguration(string name); /// <summary> /// Starts update of an IP configuration. /// </summary> /// <param name="name">Name of the IP configuration.</param> /// <return>The first stage of the update.</return> Microsoft.Azure.Management.Network.Fluent.NicIPConfiguration.Update.IUpdate UpdateIPConfiguration(string name); /// <summary> /// Removes the specified IP configuration. /// </summary> /// <param name="name">The name of an existing IP configuration.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithoutIPConfiguration(string name); } /// <summary> /// The stage of the network interface update allowing to enable or disable IP forwarding. /// </summary> public interface IWithIPForwarding { /// <summary> /// Enable IP forwarding in the network interface. /// </summary> /// <return>The next stage of the network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithIPForwarding(); /// <summary> /// Disable IP forwarding in the network interface. /// </summary> /// <return>The next stage of the network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithoutIPForwarding(); } /// <summary> /// The stage of the network interface update allowing to associate network security group. /// </summary> public interface IWithNetworkSecurityGroup { /// <summary> /// Specifies that remove any network security group associated with the network interface. /// </summary> /// <return>The next stage of the network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithoutNetworkSecurityGroup(); /// <summary> /// Create a new network security group to associate with network interface, based on the provided definition. /// </summary> /// <param name="creatable">A creatable definition for a new network security group.</param> /// <return>The next stage of the network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithNewNetworkSecurityGroup(ICreatable<Microsoft.Azure.Management.Network.Fluent.INetworkSecurityGroup> creatable); /// <summary> /// Associates an existing network security group with the network interface. /// </summary> /// <param name="networkSecurityGroup">An existing network security group.</param> /// <return>The next stage of the network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithExistingNetworkSecurityGroup(INetworkSecurityGroup networkSecurityGroup); } /// <summary> /// The stage of the network interface update allowing to specify DNS servers. /// </summary> public interface IWithDnsServer { /// <summary> /// Specifies the IP address of the custom DNS server to associate with the network interface. /// Note this method's effect is additive, i.e. each time it is used, the new dns server is /// added to the network interface. /// </summary> /// <param name="ipAddress">The IP address of the DNS server.</param> /// <return>The next stage of the network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithDnsServer(string ipAddress); /// <summary> /// Removes a DNS server associated with the network interface. /// </summary> /// <param name="ipAddress">The IP address of the DNS server.</param> /// <return>The next stage of the network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithoutDnsServer(string ipAddress); /// <summary> /// Specifies to use the default Azure DNS server for the network interface. /// Using azure DNS server will remove any custom DNS server associated with this network interface. /// </summary> /// <return>The next stage of the network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithAzureDnsServer(); } /// <summary> /// The stage of the network interface update allowing to associate it with a load balancer. /// </summary> public interface IWithLoadBalancer { /// <summary> /// Associates the network interface's primary IP configuration with a backend of an existing load balancer. /// </summary> /// <param name="loadBalancer">An existing load balancer.</param> /// <param name="backendName">The name of an existing backend on that load balancer.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithExistingLoadBalancerBackend(ILoadBalancer loadBalancer, string backendName); /// <summary> /// Associates the network interface's primary IP configuration with an inbound NAT rule of an existing load balancer. /// </summary> /// <param name="loadBalancer">An existing load balancer.</param> /// <param name="inboundNatRuleName">The name of an existing inbound NAT rule on the selected load balancer.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithExistingLoadBalancerInboundNatRule(ILoadBalancer loadBalancer, string inboundNatRuleName); /// <summary> /// Removes all the existing associations with any load balancer inbound NAT rules. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithoutLoadBalancerInboundNatRules(); /// <summary> /// Removes all the existing associations with any load balancer backends. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithoutLoadBalancerBackends(); } /// <summary> /// The stage of the network interface update allowing to specify subnet. /// </summary> public interface IWithPrimaryNetworkSubnet { /// <summary> /// Associate a subnet with the network interface. /// </summary> /// <param name="name">The subnet name.</param> /// <return>The next stage of the network interface update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update.IUpdate WithSubnet(string name); } }
using UnityEngine; using System.Collections.Generic; using Pathfinding.Util; namespace Pathfinding { [AddComponentMenu("Pathfinding/Modifiers/Funnel")] [System.Serializable] /** Simplifies paths on navmesh graphs using the funnel algorithm. * The funnel algorithm is an algorithm which can, given a path corridor with nodes in the path where the nodes have an area, like triangles, it can find the shortest path inside it. * This makes paths on navmeshes look much cleaner and smoother. * \image html images/funnelModifier_on.png * \ingroup modifiers */ [HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_funnel_modifier.php")] public class FunnelModifier : MonoModifier { #if UNITY_EDITOR [UnityEditor.MenuItem("CONTEXT/Seeker/Add Funnel Modifier")] public static void AddComp (UnityEditor.MenuCommand command) { (command.context as Component).gameObject.AddComponent(typeof(FunnelModifier)); } #endif public override int Order { get { return 10; } } public override void Apply (Path p) { List<GraphNode> path = p.path; List<Vector3> vectorPath = p.vectorPath; if (path == null || path.Count == 0 || vectorPath == null || vectorPath.Count == 0) { return; } List<Vector3> funnelPath = ListPool<Vector3>.Claim(); // Claim temporary lists and try to find lists with a high capacity List<Vector3> left = ListPool<Vector3>.Claim(path.Count+1); List<Vector3> right = ListPool<Vector3>.Claim(path.Count+1); AstarProfiler.StartProfile("Construct Funnel"); // Add start point left.Add(vectorPath[0]); right.Add(vectorPath[0]); // Loop through all nodes in the path (except the last one) for (int i = 0; i < path.Count-1; i++) { // Get the portal between path[i] and path[i+1] and add it to the left and right lists bool portalWasAdded = path[i].GetPortal(path[i+1], left, right, false); if (!portalWasAdded) { // Fallback, just use the positions of the nodes left.Add((Vector3)path[i].position); right.Add((Vector3)path[i].position); left.Add((Vector3)path[i+1].position); right.Add((Vector3)path[i+1].position); } } // Add end point left.Add(vectorPath[vectorPath.Count-1]); right.Add(vectorPath[vectorPath.Count-1]); if (!RunFunnel(left, right, funnelPath)) { // If funnel algorithm failed, degrade to simple line funnelPath.Add(vectorPath[0]); funnelPath.Add(vectorPath[vectorPath.Count-1]); } // Release lists back to the pool ListPool<Vector3>.Release(p.vectorPath); p.vectorPath = funnelPath; ListPool<Vector3>.Release(left); ListPool<Vector3>.Release(right); } /** Calculate a funnel path from the \a left and \a right portal lists. * The result will be appended to \a funnelPath */ public static bool RunFunnel (List<Vector3> left, List<Vector3> right, List<Vector3> funnelPath) { if (left == null) throw new System.ArgumentNullException("left"); if (right == null) throw new System.ArgumentNullException("right"); if (funnelPath == null) throw new System.ArgumentNullException("funnelPath"); if (left.Count != right.Count) throw new System.ArgumentException("left and right lists must have equal length"); if (left.Count < 3) { return false; } //Remove identical vertices while (left[1] == left[2] && right[1] == right[2]) { //System.Console.WriteLine ("Removing identical left and right"); left.RemoveAt(1); right.RemoveAt(1); if (left.Count <= 3) { return false; } } Vector3 swPoint = left[2]; if (swPoint == left[1]) { swPoint = right[2]; } //Test while (VectorMath.IsColinearXZ(left[0], left[1], right[1]) || VectorMath.RightOrColinearXZ(left[1], right[1], swPoint) == VectorMath.RightOrColinearXZ(left[1], right[1], left[0])) { left.RemoveAt(1); right.RemoveAt(1); if (left.Count <= 3) { return false; } swPoint = left[2]; if (swPoint == left[1]) { swPoint = right[2]; } } //Switch left and right to really be on the "left" and "right" sides /** \todo The colinear check should not be needed */ if (!VectorMath.IsClockwiseXZ(left[0], left[1], right[1]) && !VectorMath.IsColinearXZ(left[0], left[1], right[1])) { //System.Console.WriteLine ("Wrong Side 2"); List<Vector3> tmp = left; left = right; right = tmp; } funnelPath.Add(left[0]); Vector3 portalApex = left[0]; Vector3 portalLeft = left[1]; Vector3 portalRight = right[1]; int apexIndex = 0; int rightIndex = 1; int leftIndex = 1; for (int i = 2; i < left.Count; i++) { if (funnelPath.Count > 2000) { Debug.LogWarning("Avoiding infinite loop. Remove this check if you have this long paths."); break; } Vector3 pLeft = left[i]; Vector3 pRight = right[i]; /*Debug.DrawLine (portalApex,portalLeft,Color.red); * Debug.DrawLine (portalApex,portalRight,Color.yellow); * Debug.DrawLine (portalApex,left,Color.cyan); * Debug.DrawLine (portalApex,right,Color.cyan);*/ if (VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalRight, pRight) >= 0) { if (portalApex == portalRight || VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalLeft, pRight) <= 0) { portalRight = pRight; rightIndex = i; } else { funnelPath.Add(portalLeft); portalApex = portalLeft; apexIndex = leftIndex; portalLeft = portalApex; portalRight = portalApex; leftIndex = apexIndex; rightIndex = apexIndex; i = apexIndex; continue; } } if (VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalLeft, pLeft) <= 0) { if (portalApex == portalLeft || VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalRight, pLeft) >= 0) { portalLeft = pLeft; leftIndex = i; } else { funnelPath.Add(portalRight); portalApex = portalRight; apexIndex = rightIndex; portalLeft = portalApex; portalRight = portalApex; leftIndex = apexIndex; rightIndex = apexIndex; i = apexIndex; continue; } } } funnelPath.Add(left[left.Count-1]); return true; } } }
#region Copyright (c) 2014 Atif Aziz. All rights reserved. // // Copyright (c) 2014 Atif Aziz. 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 #region Imports using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; #endregion // ReSharper disable once PartialTypeWithSinglePart partial interface IXlTableDataFactory<out T> { T Blank { get; } T Skip { get; } T Table (int rows, int cols); T Float (double value); T String(string value); T Bool (bool value); T Error (int value); T Int (int value); } // ReSharper disable once PartialTypeWithSinglePart sealed partial class XlTableDataFactory<T> { public T Blank { get; set; } public T Skip { get; set; } public Func<int, int, T> Table { get; set; } public Func<double, T> Float { get; set; } public Func<string, T> String { get; set; } public Func<bool, T> Bool { get; set; } public Func<int, T> Error { get; set; } public Func<int, T> Int { get; set; } public IXlTableDataFactory<T> Bind() { return new Closure(this); } sealed class Closure : IXlTableDataFactory<T> { readonly T _blank; readonly T _skip; readonly Func<int, int, T> _table; readonly Func<double, T> _float; readonly Func<string, T> _string; readonly Func<bool, T> _bool; readonly Func<int, T> _error; readonly Func<int, T> _int; public Closure(XlTableDataFactory<T> factory) { _blank = factory.Blank; _skip = factory.Skip; _table = factory.Table ?? delegate { return default(T); }; _float = factory.Float ?? delegate { return default(T); }; _string = factory.String ?? delegate { return default(T); }; _bool = factory.Bool ?? delegate { return default(T); }; _error = factory.Error ?? delegate { return default(T); }; _int = factory.Int ?? delegate { return default(T); }; } T IXlTableDataFactory<T>.Blank { get { return _blank; } } T IXlTableDataFactory<T>.Skip { get { return _skip; } } T IXlTableDataFactory<T>.Table(int rows, int cols) { return _table(rows, cols); } T IXlTableDataFactory<T>.Float(double value) { return _float(value); } T IXlTableDataFactory<T>.String(string value) { return _string(value); } T IXlTableDataFactory<T>.Bool(bool value) { return _bool(value); } T IXlTableDataFactory<T>.Error(int value) { return _error(value); } T IXlTableDataFactory<T>.Int(int value) { return _int(value); } } } // ReSharper disable once PartialTypeWithSinglePart static partial class XlTableFormat { public static readonly IXlTableDataFactory<object> DefaultDataFactory = new XlTableDataFactory<object> { Blank = null, Skip = Missing.Value, Table = (rows, cols) => new[] { rows, cols }, Float = v => v, String = v => v, Bool = v => v, Error = v => new ErrorWrapper(v), Int = v => v, } .Bind(); public static T Read<T>(byte[] data, Func<int, int, object[], T> resultor) { using (var ms = new MemoryStream(data)) return Read(ms, resultor); } public static T Read<T>(Stream stream, Func<int, int, object[], T> resultor) { if (stream == null) throw new ArgumentNullException("stream"); if (resultor == null) throw new ArgumentNullException("resultor"); using (var e = Read(stream, DefaultDataFactory)) { if (!e.MoveNext()) throw new FormatException(); var size = (int[]) e.Current; var rows = size[0]; var cols = size[1]; var cells = new object[rows * cols]; for (var i = 0; e.MoveNext(); i++) cells[i] = e.Current; return resultor(rows, cols, cells); } } public static IEnumerable<object> Read(byte[] data) { return Read(data, DefaultDataFactory); } public static IEnumerable<T> Read<T>(byte[] data, IXlTableDataFactory<T> factory) { if (data == null) throw new ArgumentNullException("data"); if (factory == null) throw new ArgumentNullException("factory"); return ReadImpl(data, factory); } static IEnumerable<T> ReadImpl<T>(byte[] data, IXlTableDataFactory<T> factory) { using (var ms = new MemoryStream(data)) using (var e = Read(ms, factory)) while (e.MoveNext()) yield return e.Current; } public static IEnumerator<object> Read(Stream stream) { return Read(stream, DefaultDataFactory); } public static IEnumerator<T> Read<T>(Stream stream, IXlTableDataFactory<T> factory) { if (stream == null) throw new ArgumentNullException("stream"); if (factory == null) throw new ArgumentNullException("factory"); return ReadImpl(stream, factory); } static IEnumerator<T> ReadImpl<T>(Stream stream, IXlTableDataFactory<T> factory) { using (var reader = new BinaryReader(stream)) { if (XlTableDataType.Table != (XlTableDataType) reader.ReadUInt16()) throw new FormatException(); var size = reader.ReadUInt16(); if (size != 4) throw new FormatException(); var rows = reader.ReadUInt16(); var cols = reader.ReadUInt16(); yield return factory.Table(rows, cols); var cells = rows * cols; while (cells > 0) { var type = (XlTableDataType) reader.ReadUInt16(); size = reader.ReadUInt16(); if (type == XlTableDataType.String) { while (size > 0) { var str = Encoding.Default.GetString(reader.ReadBytes(reader.ReadByte())); yield return factory.String(str); cells--; size -= (ushort) (1 + checked((byte) str.Length)); } } else { int count; Func<BinaryReader, IXlTableDataFactory<T>, T> rf; switch (type) { case XlTableDataType.Float: if (size % 8 != 0) throw new FormatException(); count = size / 8; rf = (r, f) => f.Float(r.ReadDouble()); break; case XlTableDataType.Skip: if (size != 2) throw new FormatException(); count = reader.ReadUInt16(); rf = (r, f) => f.Skip; break; case XlTableDataType.Blank: if (size != 2) throw new FormatException(); count = reader.ReadUInt16(); rf = (r, f) => f.Blank; break; case XlTableDataType.Error: if (size % 2 != 0) throw new FormatException(); count = size / 2; rf = (r, f) => f.Error(r.ReadUInt16()); break; case XlTableDataType.Bool: if (size % 2 != 0) throw new FormatException(); count = size / 2; rf = (r, f) => f.Bool(r.ReadUInt16() != 0); break; case XlTableDataType.Int: if (size % 2 != 0) throw new FormatException(); count = size / 2; rf = (r, f) => f.Int(r.ReadUInt16()); break; default: throw new FormatException(); } for (var j = 0; j < count; j++) yield return rf(reader, factory); cells -= count; } } } } [Serializable] enum XlTableDataType { Table = 16, Float = 1, String = 2, Bool = 3, Error = 4, Blank = 5, Int = 6, Skip = 7, } }
using System; using NUnit.Framework; using System.Drawing; using System.Text.RegularExpressions; using OpenQA.Selenium.Environment; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium.Interactions { [TestFixture] public class DragAndDropTest : DriverTestFixture { [SetUp] public void SetupTest() { IActionExecutor actionExecutor = driver as IActionExecutor; if (actionExecutor != null) { actionExecutor.ResetInputState(); } } [Test] public void DragAndDropRelative() { driver.Url = dragAndDropPage; IWebElement img = driver.FindElement(By.Id("test1")); Point expectedLocation = drag(img, img.Location, 150, 200); Assert.AreEqual(expectedLocation, img.Location); expectedLocation = drag(img, img.Location, -50, -25); Assert.AreEqual(expectedLocation, img.Location); expectedLocation = drag(img, img.Location, 0, 0); Assert.AreEqual(expectedLocation, img.Location); expectedLocation = drag(img, img.Location, 1, -1); Assert.AreEqual(expectedLocation, img.Location); } [Test] public void DragAndDropToElement() { driver.Url = dragAndDropPage; IWebElement img1 = driver.FindElement(By.Id("test1")); IWebElement img2 = driver.FindElement(By.Id("test2")); Actions actionProvider = new Actions(driver); actionProvider.DragAndDrop(img2, img1).Perform(); Assert.AreEqual(img1.Location, img2.Location); } [Test] public void DragAndDropToElementInIframe() { driver.Url = iframePage; IWebElement iframe = driver.FindElement(By.TagName("iframe")); ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].src = arguments[1]", iframe, dragAndDropPage); driver.SwitchTo().Frame(0); IWebElement img1 = WaitFor<IWebElement>(() => { try { IWebElement element1 = driver.FindElement(By.Id("test1")); return element1; } catch (NoSuchElementException) { return null; } }, "Element with ID 'test1' not found"); IWebElement img2 = driver.FindElement(By.Id("test2")); new Actions(driver).DragAndDrop(img2, img1).Perform(); Assert.AreEqual(img1.Location, img2.Location); } [Test] public void DragAndDropElementWithOffsetInIframeAtBottom() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("iframeAtBottom.html"); IWebElement iframe = driver.FindElement(By.TagName("iframe")); driver.SwitchTo().Frame(iframe); IWebElement img1 = driver.FindElement(By.Id("test1")); Point initial = img1.Location; new Actions(driver).DragAndDropToOffset(img1, 20, 20).Perform(); initial.Offset(20, 20); Assert.AreEqual(initial, img1.Location); } [Test] [IgnoreBrowser(Browser.Firefox, "Moving outside of view port throws exception in spec-compliant driver")] [IgnoreBrowser(Browser.IE, "Moving outside of view port throws exception in spec-compliant driver")] public void DragAndDropElementWithOffsetInScrolledDiv() { if (TestUtilities.IsFirefox(driver) && TestUtilities.IsNativeEventsEnabled(driver)) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("dragAndDropInsideScrolledDiv.html"); IWebElement el = driver.FindElement(By.Id("test1")); Point initial = el.Location; new Actions(driver).DragAndDropToOffset(el, 3700, 3700).Perform(); initial.Offset(3700, 3700); Assert.AreEqual(initial, el.Location); } [Test] public void ElementInDiv() { driver.Url = dragAndDropPage; IWebElement img = driver.FindElement(By.Id("test3")); Point startLocation = img.Location; Point expectedLocation = drag(img, startLocation, 100, 100); Point endLocation = img.Location; Assert.AreEqual(expectedLocation, endLocation); } [Test] [IgnoreBrowser(Browser.IE, "Dragging too far in IE causes the element not to move, instead of moving to 0,0.")] public void DragTooFar() { driver.Url = dragAndDropPage; IWebElement img = driver.FindElement(By.Id("test1")); // Dragging too far left and up does not move the element. It will be at // its original location after the drag. Point originalLocation = new Point(0, 0); Actions actionProvider = new Actions(driver); actionProvider.DragAndDropToOffset(img, int.MinValue, int.MinValue).Perform(); Point newLocation = img.Location; Assert.That(newLocation.X, Is.LessThanOrEqualTo(0)); Assert.That(newLocation.Y, Is.LessThanOrEqualTo(0)); // TODO(jimevans): re-enable this test once moveto does not exceed the // coordinates accepted by the browsers (Firefox in particular). At the // moment, even though the maximal coordinates are limited, mouseUp // fails because it cannot get the element at the given coordinates. //actionProvider.DragAndDropToOffset(img, int.MaxValue, int.MaxValue).Perform(); //We don't know where the img is dragged to , but we know it's not too //far, otherwise this function will not return for a long long time } [Test] [IgnoreBrowser(Browser.Firefox, "Problem with drag off viewport. See issue #1771")] [IgnoreBrowser(Browser.IE, "Moving outside of view port throws exception in spec-compliant driver")] public void ShouldAllowUsersToDragAndDropToElementsOffTheCurrentViewPort() { driver.Url = dragAndDropPage; IJavaScriptExecutor js = (IJavaScriptExecutor)driver; int height = Convert.ToInt32(js.ExecuteScript("return window.outerHeight;")); int width = Convert.ToInt32(js.ExecuteScript("return window.outerWidth;")); bool mustUseOffsetHeight = width == 0 && height == 0; if (mustUseOffsetHeight) { width = Convert.ToInt32(js.ExecuteScript("return document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;")); height = Convert.ToInt32(js.ExecuteScript("return document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;")); } js.ExecuteScript("window.resizeTo(300, 300);"); if (mustUseOffsetHeight) { width = width + 300 - Convert.ToInt32(js.ExecuteScript("return document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;")); height = height + 300 - Convert.ToInt32(js.ExecuteScript("return document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;")); } try { driver.Url = dragAndDropPage; IWebElement img = driver.FindElement(By.Id("test3")); Point expectedLocation = drag(img, img.Location, 100, 100); Assert.AreEqual(expectedLocation, img.Location); } finally { js.ExecuteScript("window.resizeTo(arguments[0], arguments[1]);", width, height); } } [Test] public void DragAndDropOnJQueryItems() { driver.Url = droppableItems; IWebElement toDrag = driver.FindElement(By.Id("draggable")); IWebElement dropInto = driver.FindElement(By.Id("droppable")); // Wait until all event handlers are installed. System.Threading.Thread.Sleep(500); Actions actionProvider = new Actions(driver); actionProvider.DragAndDrop(toDrag, dropInto).Perform(); string text = dropInto.FindElement(By.TagName("p")).Text; DateTime endTime = DateTime.Now.Add(TimeSpan.FromSeconds(15)); while (text != "Dropped!" && (DateTime.Now < endTime)) { System.Threading.Thread.Sleep(200); text = dropInto.FindElement(By.TagName("p")).Text; } Assert.AreEqual("Dropped!", text); IWebElement reporter = driver.FindElement(By.Id("drop_reports")); // Assert that only one mouse click took place and the mouse was moved // during it. string reporterText = reporter.Text; Assert.That(reporterText, Does.Match("start( move)* down( move)+ up")); Assert.AreEqual(1, Regex.Matches(reporterText, "down").Count, "Reporter text:" + reporterText); Assert.AreEqual(1, Regex.Matches(reporterText, "up").Count, "Reporter text:" + reporterText); Assert.That(reporterText, Does.Contain("move")); } [Test] [IgnoreBrowser(Browser.Opera, "Untested")] [IgnoreBrowser(Browser.Firefox, "Moving outside of view port throws exception in spec-compliant driver")] [IgnoreBrowser(Browser.IE, "Moving outside of view port throws exception in spec-compliant driver")] public void CanDragAnElementNotVisibleInTheCurrentViewportDueToAParentOverflow() { driver.Url = dragDropOverflowPage; IWebElement toDrag = driver.FindElement(By.Id("time-marker")); IWebElement dragTo = driver.FindElement(By.Id("11am")); Point srcLocation = toDrag.Location; Point targetLocation = dragTo.Location; int yOffset = targetLocation.Y - srcLocation.Y; Assert.AreNotEqual(0, yOffset); new Actions(driver).DragAndDropToOffset(toDrag, 0, yOffset).Perform(); Assert.AreEqual(dragTo.Location, toDrag.Location); } //------------------------------------------------------------------ // Tests below here are not included in the Java test suite //------------------------------------------------------------------ [Test] public void DragAndDropRelativeAndToElement() { driver.Url = dragAndDropPage; IWebElement img1 = driver.FindElement(By.Id("test1")); IWebElement img2 = driver.FindElement(By.Id("test2")); Actions actionProvider = new Actions(driver); actionProvider.DragAndDropToOffset(img1, 100, 100).DragAndDrop(img2, img1).Perform(); Assert.AreEqual(img1.Location, img2.Location); } private Point drag(IWebElement elem, Point initialLocation, int moveRightBy, int moveDownBy) { Point expectedLocation = new Point(initialLocation.X, initialLocation.Y); expectedLocation.Offset(moveRightBy, moveDownBy); Actions actionProvider = new Actions(driver); actionProvider.DragAndDropToOffset(elem, moveRightBy, moveDownBy).Perform(); return expectedLocation; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Xunit; #pragma warning disable 1998 // Async method with no "await" operators. namespace System.Threading.Tests { public static class AsyncLocalTests { [Fact] public static async Task ValueProperty() { AsyncLocal<int> local = new AsyncLocal<int>(); Assert.Equal(local.Value, 0); local.Value = 1; Assert.Equal(local.Value, 1); local.Value = 0; Assert.Equal(local.Value, 0); } [Fact] public static async Task CaptureAndRestore() { AsyncLocal<int> local = new AsyncLocal<int>(); local.Value = 42; ExecutionContext ec = ExecutionContext.Capture(); local.Value = 12; ExecutionContext.Run( ec, _ => { Assert.Equal(local.Value, 42); local.Value = 56; }, null); Assert.Equal(local.Value, 12); } [Fact] public static async Task CaptureAndRestoreEmptyContext() { AsyncLocal<int> local = new AsyncLocal<int>(); ExecutionContext ec = ExecutionContext.Capture(); local.Value = 12; ExecutionContext.Run( ec, _ => { Assert.Equal(local.Value, 0); local.Value = 56; }, null); Assert.Equal(local.Value, 12); } [Fact] public static async Task NotifyOnValuePropertyChange() { bool expectThreadContextChange = false; int expectedPreviousValue = 0; int expectedCurrentValue = 1; bool gotNotification = false; bool expectNotification = false; AsyncLocal<int> local = new AsyncLocal<int>( args => { gotNotification = true; Assert.True(expectNotification); expectNotification = false; Assert.Equal(args.ThreadContextChanged, expectThreadContextChange); Assert.Equal(args.PreviousValue, expectedPreviousValue); Assert.Equal(args.CurrentValue, expectedCurrentValue); }); expectNotification = true; local.Value = 1; Assert.True(gotNotification); expectNotification = true; expectThreadContextChange = true; expectedPreviousValue = local.Value; expectedCurrentValue = 0; return; } [Fact] public static async Task NotifyOnThreadContextChange() { bool expectThreadContextChange = false; int expectedPreviousValue = 0; int expectedCurrentValue = 1; bool gotNotification = false; bool expectNotification = false; AsyncLocal<int> local = new AsyncLocal<int>( args => { gotNotification = true; Assert.True(expectNotification); expectNotification = false; Assert.Equal(args.ThreadContextChanged, expectThreadContextChange); Assert.Equal(args.PreviousValue, expectedPreviousValue); Assert.Equal(args.CurrentValue, expectedCurrentValue); }); expectNotification = true; local.Value = 1; Assert.True(gotNotification); gotNotification = false; ExecutionContext ec = ExecutionContext.Capture(); expectNotification = true; expectedPreviousValue = 1; expectedCurrentValue = 2; local.Value = 2; Assert.True(gotNotification); gotNotification = false; expectNotification = true; expectedPreviousValue = 2; expectedCurrentValue = 1; expectThreadContextChange = true; ExecutionContext.Run( ec, _ => { Assert.True(gotNotification); gotNotification = false; Assert.Equal(local.Value, 1); expectNotification = true; expectedPreviousValue = 1; expectedCurrentValue = 3; expectThreadContextChange = false; local.Value = 3; Assert.True(gotNotification); gotNotification = false; expectNotification = true; expectedPreviousValue = 3; expectedCurrentValue = 2; expectThreadContextChange = true; return; }, null); Assert.True(gotNotification); gotNotification = false; Assert.Equal(local.Value, 2); expectNotification = true; expectThreadContextChange = true; expectedPreviousValue = local.Value; expectedCurrentValue = 0; return; } [Fact] public static async Task NotifyOnThreadContextChangeWithOneEmptyContext() { bool expectThreadContextChange = false; int expectedPreviousValue = 0; int expectedCurrentValue = 1; bool gotNotification = false; bool expectNotification = false; AsyncLocal<int> local = new AsyncLocal<int>( args => { gotNotification = true; Assert.True(expectNotification); expectNotification = false; Assert.Equal(args.ThreadContextChanged, expectThreadContextChange); Assert.Equal(args.PreviousValue, expectedPreviousValue); Assert.Equal(args.CurrentValue, expectedCurrentValue); }); ExecutionContext ec = ExecutionContext.Capture(); expectNotification = true; expectedPreviousValue = 0; expectedCurrentValue = 1; local.Value = 1; Assert.True(gotNotification); gotNotification = false; expectNotification = true; expectedPreviousValue = 1; expectedCurrentValue = 0; expectThreadContextChange = true; ExecutionContext.Run( ec, _ => { Assert.True(gotNotification); gotNotification = false; Assert.Equal(local.Value, 0); expectNotification = true; expectedPreviousValue = 0; expectedCurrentValue = 1; expectThreadContextChange = true; return; }, null); Assert.True(gotNotification); gotNotification = false; Assert.Equal(local.Value, 1); expectNotification = true; expectThreadContextChange = true; expectedPreviousValue = local.Value; expectedCurrentValue = 0; return; } // helper to make it easy to start an anonymous async method on the current thread. private static Task Run(Func<Task> func) { return func(); } [Fact] public static async Task AsyncMethodNotifications() { // // Define thread-local and async-local values. The async-local value uses its notification // to keep the thread-local value in sync with the async-local value. // ThreadLocal<int> tls = new ThreadLocal<int>(); AsyncLocal<int> als = new AsyncLocal<int>(args => { tls.Value = args.CurrentValue; }); Assert.Equal(tls.Value, als.Value); als.Value = 1; Assert.Equal(tls.Value, als.Value); als.Value = 2; Assert.Equal(tls.Value, als.Value); await Run(async () => { Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 2); als.Value = 3; Assert.Equal(tls.Value, als.Value); Task t = Run(async () => { Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 3); als.Value = 4; Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 4); await Task.Run(() => { Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 4); als.Value = 5; Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 5); }); Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 4); als.Value = 6; Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 6); }); Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 3); await Task.Yield(); Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 3); await t; Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 3); }); Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 2); } [Fact] public static async Task SetValueFromNotification() { int valueToSet = 0; AsyncLocal<int> local = null; local = new AsyncLocal<int>(args => { if (args.ThreadContextChanged) local.Value = valueToSet; }); valueToSet = 2; local.Value = 1; Assert.Equal(local.Value, 1); await Run(async () => { local.Value = 3; valueToSet = 4; }); Assert.Equal(local.Value, 4); } [Fact] public static async Task ExecutionContextCopyOnWrite() { AsyncLocal<int> local = new AsyncLocal<int>(); local.Value = 42; await Run(async () => { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); Assert.Equal(42, local.Value); local.Value = 12; }); Assert.Equal(local.Value, 42); } [Fact] public static async Task AddAndUpdateManyLocals_ValueType() { var locals = new AsyncLocal<int>[40]; for (int i = 0; i < locals.Length; i++) { locals[i] = new AsyncLocal<int>(); locals[i].Value = i; for (int j = 0; j <= i; j++) { Assert.Equal(j, locals[j].Value); locals[j].Value = j + 1; Assert.Equal(j + 1, locals[j].Value); locals[j].Value = j; Assert.Equal(j, locals[j].Value); } } } [Fact] public static async Task AddUpdateAndRemoveManyLocals_ReferenceType() { var locals = new AsyncLocal<string>[40]; for (int i = 0; i < locals.Length; i++) { locals[i] = new AsyncLocal<string>(); locals[i].Value = i.ToString(); for (int j = 0; j <= i; j++) { Assert.Equal(j.ToString(), locals[j].Value); locals[j].Value = (j + 1).ToString(); Assert.Equal((j + 1).ToString(), locals[j].Value); locals[j].Value = j.ToString(); Assert.Equal(j.ToString(), locals[j].Value); } } for (int i = 0; i < locals.Length; i++) { locals[i].Value = null; Assert.Null(locals[i].Value); for (int j = i + 1; j < locals.Length; j++) { Assert.Equal(j.ToString(), locals[j].Value); } } } } }
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; namespace DalSic { /// <summary> /// Controller class for Guardia_Antecedentes /// </summary> [System.ComponentModel.DataObject] public partial class GuardiaAntecedenteController { // Preload our schema.. GuardiaAntecedente thisSchemaLoad = new GuardiaAntecedente(); private string userName = String.Empty; protected string UserName { get { if (userName.Length == 0) { if (System.Web.HttpContext.Current != null) { userName=System.Web.HttpContext.Current.User.Identity.Name; } else { userName=System.Threading.Thread.CurrentPrincipal.Identity.Name; } } return userName; } } [DataObjectMethod(DataObjectMethodType.Select, true)] public GuardiaAntecedenteCollection FetchAll() { GuardiaAntecedenteCollection coll = new GuardiaAntecedenteCollection(); Query qry = new Query(GuardiaAntecedente.Schema); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public GuardiaAntecedenteCollection FetchByID(object Id) { GuardiaAntecedenteCollection coll = new GuardiaAntecedenteCollection().Where("id", Id).Load(); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public GuardiaAntecedenteCollection FetchByQuery(Query qry) { GuardiaAntecedenteCollection coll = new GuardiaAntecedenteCollection(); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Delete, true)] public bool Delete(object Id) { return (GuardiaAntecedente.Delete(Id) == 1); } [DataObjectMethod(DataObjectMethodType.Delete, false)] public bool Destroy(object Id) { return (GuardiaAntecedente.Destroy(Id) == 1); } /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Insert, true)] public void Insert(int Id,bool? Asma,string AsmaText,bool? Irc,string IrcText,bool? Cirugias,string CirugiasText,bool? Hta,string HtaText,bool? Infectologicas,string InfectologicasText,bool? Alergias,string AlergiasText,bool? Adicciones,string AdiccionesText,bool? Convulsiones,string ConvulsionesText,bool? Epoc,string EpocText,bool? Cardiopatia,string CardiopatiaText,bool? Neoplasias,string NeoplasiasText,bool? Traumatismos,string TraumatismosText,bool? Vacunas,string VacunasText,bool? Endocrinologia,string EndocrinologiaText,bool? Respiratorios,string RespiratoriosText,bool? Inmunodeficiencia,string InmunodeficienciaText,bool? RetrasoMaduativo,string RetrasoMadurativoText,bool? Malformaciones,string MalformacionesText,bool? AlteracionesSistemaNervioso,string AlteracionesSistemaNerviosoText,bool? Otras,string OtrasText) { GuardiaAntecedente item = new GuardiaAntecedente(); item.Id = Id; item.Asma = Asma; item.AsmaText = AsmaText; item.Irc = Irc; item.IrcText = IrcText; item.Cirugias = Cirugias; item.CirugiasText = CirugiasText; item.Hta = Hta; item.HtaText = HtaText; item.Infectologicas = Infectologicas; item.InfectologicasText = InfectologicasText; item.Alergias = Alergias; item.AlergiasText = AlergiasText; item.Adicciones = Adicciones; item.AdiccionesText = AdiccionesText; item.Convulsiones = Convulsiones; item.ConvulsionesText = ConvulsionesText; item.Epoc = Epoc; item.EpocText = EpocText; item.Cardiopatia = Cardiopatia; item.CardiopatiaText = CardiopatiaText; item.Neoplasias = Neoplasias; item.NeoplasiasText = NeoplasiasText; item.Traumatismos = Traumatismos; item.TraumatismosText = TraumatismosText; item.Vacunas = Vacunas; item.VacunasText = VacunasText; item.Endocrinologia = Endocrinologia; item.EndocrinologiaText = EndocrinologiaText; item.Respiratorios = Respiratorios; item.RespiratoriosText = RespiratoriosText; item.Inmunodeficiencia = Inmunodeficiencia; item.InmunodeficienciaText = InmunodeficienciaText; item.RetrasoMaduativo = RetrasoMaduativo; item.RetrasoMadurativoText = RetrasoMadurativoText; item.Malformaciones = Malformaciones; item.MalformacionesText = MalformacionesText; item.AlteracionesSistemaNervioso = AlteracionesSistemaNervioso; item.AlteracionesSistemaNerviosoText = AlteracionesSistemaNerviosoText; item.Otras = Otras; item.OtrasText = OtrasText; item.Save(UserName); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Update, true)] public void Update(int Id,bool? Asma,string AsmaText,bool? Irc,string IrcText,bool? Cirugias,string CirugiasText,bool? Hta,string HtaText,bool? Infectologicas,string InfectologicasText,bool? Alergias,string AlergiasText,bool? Adicciones,string AdiccionesText,bool? Convulsiones,string ConvulsionesText,bool? Epoc,string EpocText,bool? Cardiopatia,string CardiopatiaText,bool? Neoplasias,string NeoplasiasText,bool? Traumatismos,string TraumatismosText,bool? Vacunas,string VacunasText,bool? Endocrinologia,string EndocrinologiaText,bool? Respiratorios,string RespiratoriosText,bool? Inmunodeficiencia,string InmunodeficienciaText,bool? RetrasoMaduativo,string RetrasoMadurativoText,bool? Malformaciones,string MalformacionesText,bool? AlteracionesSistemaNervioso,string AlteracionesSistemaNerviosoText,bool? Otras,string OtrasText) { GuardiaAntecedente item = new GuardiaAntecedente(); item.MarkOld(); item.IsLoaded = true; item.Id = Id; item.Asma = Asma; item.AsmaText = AsmaText; item.Irc = Irc; item.IrcText = IrcText; item.Cirugias = Cirugias; item.CirugiasText = CirugiasText; item.Hta = Hta; item.HtaText = HtaText; item.Infectologicas = Infectologicas; item.InfectologicasText = InfectologicasText; item.Alergias = Alergias; item.AlergiasText = AlergiasText; item.Adicciones = Adicciones; item.AdiccionesText = AdiccionesText; item.Convulsiones = Convulsiones; item.ConvulsionesText = ConvulsionesText; item.Epoc = Epoc; item.EpocText = EpocText; item.Cardiopatia = Cardiopatia; item.CardiopatiaText = CardiopatiaText; item.Neoplasias = Neoplasias; item.NeoplasiasText = NeoplasiasText; item.Traumatismos = Traumatismos; item.TraumatismosText = TraumatismosText; item.Vacunas = Vacunas; item.VacunasText = VacunasText; item.Endocrinologia = Endocrinologia; item.EndocrinologiaText = EndocrinologiaText; item.Respiratorios = Respiratorios; item.RespiratoriosText = RespiratoriosText; item.Inmunodeficiencia = Inmunodeficiencia; item.InmunodeficienciaText = InmunodeficienciaText; item.RetrasoMaduativo = RetrasoMaduativo; item.RetrasoMadurativoText = RetrasoMadurativoText; item.Malformaciones = Malformaciones; item.MalformacionesText = MalformacionesText; item.AlteracionesSistemaNervioso = AlteracionesSistemaNervioso; item.AlteracionesSistemaNerviosoText = AlteracionesSistemaNerviosoText; item.Otras = Otras; item.OtrasText = OtrasText; item.Save(UserName); } } }
using System; using System.Collections.Generic; using System.Text; using UnityEngine; using Object = UnityEngine.Object; namespace InAudioSystem.ExtensionMethods.Repeat { public static class Repeater { public static void Repeat(int n, Action action) { for (int i = 0; i < n; i++) { action(); } } } } namespace InAudioSystem.ExtensionMethods { public static class AudioSourceExtension { public static float ExactLength(this AudioClip clip) { return clip.samples / (float)clip.frequency; } public static double ExactTimeLength(this AudioSource source) { return (source.clip.samples - source.timeSamples) / (double)source.clip.frequency; } public static bool UnloadIfPossible(this AudioClip clip) { if (clip.preloadAudioData) return false; clip.UnloadAudioData(); return true; } public static bool LoadIfPossible(this AudioClip clip) { if (clip.preloadAudioData) return false; clip.LoadAudioData(); return true; } /// <summary> /// Returns how far along a source is with playing /// </summary> /// <param name="source"></param> /// <returns></returns> public static double ExactPosition(this AudioSource source) { return source.timeSamples / (double)source.clip.frequency; } } public static class ArrayExtension { public static List<UnityEngine.Object> CombineToObjectList(params List<UnityEngine.Object>[] lists) { List<UnityEngine.Object> newList = new List<Object>(); for (int i = 0; i < lists[i].Count; i++) { newList.AddRange(lists[i]); } return newList; } public static void CopyTo<T>(this List<T> from, List<T> to) { to.Clear(); for (int i = 0; i < from.Count; i++) { to.Add(from[i]); } } public static bool AnyNull<T>(this T[] objs) where T : Object { for (int i = 0; i < objs.Length; i++) { if (objs[i] == null) return true; } return false; } public static T FindFirstNonNull<T>(this List<T> from) where T : class { for (int i = 0; i < from.Count; i++) { if (from[i] != null) { return from[i]; } } return default(T); } public static T[] TakeNonNulls<T>(this T[] arr) where T : UnityEngine.Object { int nullCount = 0; for (int i = 0; i < arr.Length; ++i) { if (arr[i] == null) { nullCount += 1; } } if (nullCount > 0) { T[] nonNull = new T[arr.Length - nullCount]; int lastIndex = 0; for (int i = 0; i < arr.Length; ++i) { if (arr[i] != null) { nonNull[lastIndex] = arr[i]; lastIndex++; } } return nonNull; } else return arr; } public static void ForEach<T>(this T[] source, Action<T> action) { for (int i = 0; i < source.Length; ++i) { action(source[i]); } } /// <summary> /// Returns a list of all objects that match a certain condition and is not nulls /// </summary> public static T[] FindAllNoNulls<T>(this IList<T> source, Func<T, bool> action) { List<T> list = new List<T>(); for (int i = 0; i < source.Count; ++i) { if (source[i] != null && action(source[i])) { list.Add(source[i]); } } return list.ToArray(); } public static void ForEachAssign<T>(this T[] source, Func<T, T> action) { for (int i = 0; i < source.Length; ++i) { source[i] = action(source[i]); } } public static U[] Convert<T, U>(this T[] source, Func<T, U> action) { U[] newArr = new U[source.Length]; for (int i = 0; i < source.Length; ++i) { newArr[i] = action(source[i]); } return newArr; } public static T[] Add<T>(this T[] source, params T[] objs) { var arr = new T[source.Length + objs.Length]; int i = 0; for (; i < source.Length; i++) { arr[i] = source[i]; } for (int j = 0; i < source.Length + objs.Length; ) { arr[i] = objs[j]; ++i; ++j; } return arr; } public static Object[] AddObj(this Object[] source, params Object[] objs) { List<Object> arr = new List<Object>(); for (int i = 0; i < source.Length; i++) { arr.Add(source[i]); } for (int i = 0; i < objs.Length; i++) { arr.Add(objs[i]); } return arr.ToArray(); } } public static class IListExtension { public static bool TrueForAny<T>(this IList<T> list, Func<T, bool> trueForElement) { for (int i = 0; i < list.Count; i++) { if (trueForElement(list[i])) return true; } return false; } public static bool TrueForAll<T>(this IList<T> list, Func<T, bool> trueForElement) { int isTrue = 0; for (int i = 0; i < list.Count; i++) { if (trueForElement(list[i])) { isTrue++; } } return isTrue == list.Count; } } public static class ListExtension { public static void Move<T>(this List<T> list, int oldIndex, int newIndex) { T item = list[oldIndex]; list.RemoveAt(oldIndex); list.Insert(newIndex, item); } public static void AddIfNotContains<T>(this List<T> list, T item) { if(!list.Contains(item)) list.Add(item); } public static void SwapRemoveAt<T>(this IList<T> list, ref int i) { list[i] = list[list.Count - 1]; list.RemoveAt(list.Count - 1); i -= 1; } public static void SwapRemoveAt<T>(this IList<T> list, int i) { list[i] = list[list.Count - 1]; list.RemoveAt(list.Count - 1); } public static void SafeRemoveAt<T>(this IList<T> list, ref int i) { list[i] = list[list.Count - 1]; list.RemoveAt(list.Count - 1); i -= 1; } public static T FindFirst<T>(this IList<T> list, Func<T, bool> func) { if (list == null || func == null) return default(T); for (int i = 0; i < list.Count; i++) { if (func(list[i])) { return list[i]; } } return default(T); } public static int FindIndex<T>(this List<T> list, T toFind) where T : class { for (int i = 0; i < list.Count; ++i) { var item = list[i]; if (toFind == null && item == null) return i; if(item != null && item.Equals(toFind)) return i; } return -1; } public static void RemoveLast<T>(this List<T> list) { list.RemoveAt(list.Count - 1); } /// <summary> /// Finds an element in a list, removes it by swapping with the last element and decreases the size of the list /// </summary> /// <param name="list">The list to work on</param> /// <param name="toFind">The object to find in the list</param> /// <returns>Returns true if an element was removed</returns> public static bool FindSwapRemove<T>(this List<T> list, T toFind) where T : class { int index = FindIndex(list, toFind); if(index == -1) return false; list[index] = list[list.Count - 1]; list.RemoveAt(list.Count - 1); return true; } public static List<T> SwapAtIndexes<T>(this List<T> list, int i, int j) { var temp = list[i]; list[i] = list[j]; list[j] = temp; return list; } public static T TryGet<T>(this List<T> list, int index) { if (index < list.Count) return list[index]; return default(T); } //public static void ForEach<T>(this EventList<T> source, Action<T> action) //{ // for (int i = 0; i < source.Count; ++i) // { // action(source[i]); // } //} public static void ThrowIfNull(this UnityEngine.Object obj) { if(obj == null) throw new NullReferenceException(""); } public static int CountIf<T>(this IList<T> objs, Func<T, bool> predicate) { int count = 0; for (int i = 0; i < objs.Count; i++) { if (predicate(objs[i])) count++; } return count; } public static void ThrowIfNull<T>(this T obj) where T : class { if (obj == null) throw new NullReferenceException(typeof(T).FullName); } //public static List<U> ConvertList<T, U>(this List<T> toConvert) where T : UnityEngine.Object where U : class //{ // List<U> newList = new List<U>(toConvert.Count); // for (int i = 0; i < toConvert.Count; ++i) // { // newList.Add(toConvert[i] as U); // } // return newList; //} public static List<U> ConvertList<T, U>(this List<T> toConvert) where T : class where U : class { List<U> newList = new List<U>(toConvert.Count); for (int i = 0; i < toConvert.Count; ++i) { newList.Add(toConvert[i] as U); } return newList; } } public static class EnumUtil { public static IEnumerable<T> GetValues<T>() { return (T[])Enum.GetValues(typeof(T)); } public static string FormatedName(this Enum someEnum) { return someEnum.ToString().AddSpacesToSentence(); } } public static class StringUtil { public static string AddSpacesToSentence(this string text, bool preserveAcronyms = false) { StringBuilder newText = new StringBuilder(text.Length*2); newText.Append(text[0]); for (int i = 1; i < text.Length; i++) { if (char.IsUpper(text[i])) if ((text[i - 1] != ' ' && !char.IsUpper(text[i - 1])) || (preserveAcronyms && char.IsUpper(text[i - 1]) && i < text.Length - 1 && !char.IsUpper(text[i + 1]))) newText.Append(' '); newText.Append(text[i]); } return newText.ToString(); } public static bool IsNullOrWhiteSpace(this string value) { if (value != null) { for (int i = 0; i < value.Length; i++) { if (!char.IsWhiteSpace(value[i])) { return false; } } } return true; } } public static class EventUtil { public static bool IsDragging(this Event unityEvent) { return unityEvent.type == EventType.DragUpdated || unityEvent.type == EventType.DragPerform; } public static bool ClickedWithin(this Event unityEvent, Rect area) { return unityEvent.type == EventType.MouseDown && area.Contains(unityEvent.mousePosition) && GUIUtility.hotControl == 0; } public static bool ClickedWithin(this Event unityEvent, Rect area, int button) { return unityEvent.type == EventType.MouseDown && area.Contains(unityEvent.mousePosition) && GUIUtility.hotControl == 0 && Event.current.button == button; } public static bool MouseUpWithin(this Event unityEvent, Rect area, int button) { return unityEvent.type == EventType.MouseUp && area.Contains(unityEvent.mousePosition) && GUIUtility.hotControl == 0 && Event.current.button == button; } public static bool ActionWithin(this Event unityEvent, Rect area, EventType type) { return unityEvent.type == type && area.Contains(unityEvent.mousePosition) && GUIUtility.hotControl == 0; } public static bool DraggedWithin(this Event unityEvent, Rect area) { return IsDragging(unityEvent) && area.Contains(unityEvent.mousePosition) && GUIUtility.hotControl == 0; } public static bool Contains(this Event unityEvent, Rect area) { return area.Contains(unityEvent.mousePosition) && GUIUtility.hotControl == 0; } public static bool MouseUpWithin(this Event unityEvent, Rect area) { return unityEvent.type == EventType.MouseUp && area.Contains(unityEvent.mousePosition) && GUIUtility.hotControl == 0; } public static bool ClickedWithin(this Event unityEvent, Rect area, Vector2 mouse) { return unityEvent.type == EventType.MouseDown && area.Contains(mouse) && GUIUtility.hotControl == 0; } public static bool IsKeyDown(this Event unityEvent, KeyCode code) { if (unityEvent == null) return false; return Event.current.type == EventType.keyDown && Event.current.keyCode == code; } } public static class RectUtil { public static bool Intersect(this Rect a, Rect b) { FlipNegative( ref a ); FlipNegative( ref b ); bool c1 = a.xMin < b.xMax; bool c2 = a.xMax > b.xMin; bool c3 = a.yMin < b.yMax; bool c4 = a.yMax > b.yMin; return c1 && c2 && c3 && c4; } public static bool WithinWidth(this Rect a, Vector2 pos) { if (pos.x > a.x && pos.x < a.x + a.width) return true; return false; } public static void FlipNegative(ref Rect r) { if (r.width < 0) r.x -= (r.width *= -1); if (r.height < 0) r.y -= (r.height *= -1); } public static Rect Add(this Rect a, Rect b) { a.x += b.x; a.y += b.y; a.width += b.width; a.height += b.height; return a; } public static Rect Add(this Rect a, Vector2 b) { a.x += b.x; a.y += b.y; return a; } public static Rect Add(this Rect a, float x, float y) { a.x += x; a.y += y; return a; } public static Rect Substract(this Rect a, Rect b) { a.x -= b.x; a.y -= b.y; a.width -= b.width; a.height -= b.height; return a; } public static Rect Substract(this Rect a, Vector2 v) { a.x -= v.x; a.y -= v.y; return a; } public static Rect Substract(this Rect a, float x, float y) { a.x -= x; a.y -= y; return a; } } public static class GameObjectExtensions { public static bool HasComponent<T>(this GameObject go) where T : Component { if (go == null) return false; return go.GetComponent<T>() != null; } } public static class Loudness { //http://wiki.unity3d.com/index.php?title=Loudness // A 20 dB increase sounds about 4x louder. // A signal needs an amplitude that is 10^(dB/20) greater, // to be increased by 'dB' decibels. class Exponents { public static readonly float Set = Mathf.Log(10, 4); public static readonly float Get = 1 / Set; } public static float GetLoudness(this AudioSource audioSource) { return Mathf.Pow(audioSource.volume, Exponents.Get); } public static float SetLoudness(this AudioSource audioSource, float value) { float v = audioSource.volume = Mathf.Pow(Mathf.Clamp01(value), Exponents.Set); return v; } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections; using System.Collections.Generic; #if DYNAMIC_OBJECT using System.Dynamic; #endif using System.Linq; using System.Reflection; using NLog.Common; using NLog.Config; /// <summary> /// Converts object into a List of property-names and -values using reflection /// </summary> internal class ObjectReflectionCache : IObjectTypeTransformer { private MruCache<Type, ObjectPropertyInfos> ObjectTypeCache => _objectTypeCache ?? System.Threading.Interlocked.CompareExchange(ref _objectTypeCache, new MruCache<Type, ObjectPropertyInfos>(10000), null) ?? _objectTypeCache; private MruCache<Type, ObjectPropertyInfos> _objectTypeCache; private IObjectTypeTransformer ObjectTypeTransformation => _objectTypeTransformation ?? (_objectTypeTransformation = ConfigurationItemFactory.Default.ObjectTypeTransformer); private IObjectTypeTransformer _objectTypeTransformation; public static IObjectTypeTransformer Instance { get; } = new ObjectReflectionCache(); object IObjectTypeTransformer.TryTransformObject(object obj) { return null; } public ObjectPropertyList LookupObjectProperties(object value) { if (TryLookupExpandoObject(value, out var propertyValues)) { return propertyValues; } if (!ReferenceEquals(ObjectTypeTransformation, Instance)) { var result = ObjectTypeTransformation.TryTransformObject(value); if (result != null) { if (result is IConvertible) { return new ObjectPropertyList(result, ObjectPropertyInfos.SimpleToString.Properties, ObjectPropertyInfos.SimpleToString.FastLookup); } if (TryLookupExpandoObject(result, out propertyValues)) { return propertyValues; } value = result; } } var objectType = value.GetType(); var propertyInfos = BuildObjectPropertyInfos(value, objectType); ObjectTypeCache.TryAddValue(objectType, propertyInfos); return new ObjectPropertyList(value, propertyInfos.Properties, propertyInfos.FastLookup); } public bool TryLookupExpandoObject(object value, out ObjectPropertyList objectPropertyList) { if (value is IDictionary<string, object> expando) { objectPropertyList = new ObjectPropertyList(expando); return true; } #if DYNAMIC_OBJECT if (value is DynamicObject d) { var dictionary = DynamicObjectToDict(d); objectPropertyList = new ObjectPropertyList(dictionary); return true; } #endif Type objectType = value.GetType(); if (ObjectTypeCache.TryGetValue(objectType, out var propertyInfos)) { if (!propertyInfos.HasFastLookup) { var fastLookup = BuildFastLookup(propertyInfos.Properties, false); propertyInfos = new ObjectPropertyInfos(propertyInfos.Properties, fastLookup); ObjectTypeCache.TryAddValue(objectType, propertyInfos); } objectPropertyList = new ObjectPropertyList(value, propertyInfos.Properties, propertyInfos.FastLookup); return true; } if (TryExtractExpandoObject(objectType, out propertyInfos)) { ObjectTypeCache.TryAddValue(objectType, propertyInfos); objectPropertyList = new ObjectPropertyList(value, propertyInfos.Properties, propertyInfos.FastLookup); return true; } objectPropertyList = default(ObjectPropertyList); return false; } private static bool TryExtractExpandoObject(Type objectType, out ObjectPropertyInfos propertyInfos) { foreach (var interfaceType in objectType.GetInterfaces()) { if (IsGenericDictionaryEnumeratorType(interfaceType)) { var dictionaryEnumerator = (IDictionaryEnumerator)Activator.CreateInstance(typeof(DictionaryEnumerator<,>).MakeGenericType(interfaceType.GetGenericArguments())); propertyInfos = new ObjectPropertyInfos(null, new[] { new FastPropertyLookup(string.Empty, TypeCode.Object, (o, p) => dictionaryEnumerator.GetEnumerator(o)) }); return true; } } propertyInfos = default(ObjectPropertyInfos); return false; } private static ObjectPropertyInfos BuildObjectPropertyInfos(object value, Type objectType) { ObjectPropertyInfos propertyInfos; if (ConvertSimpleToString(objectType)) { propertyInfos = ObjectPropertyInfos.SimpleToString; } else { var properties = GetPublicProperties(objectType); if (value is Exception) { // Special handling of Exception (Include Exception-Type as artificial first property) var fastLookup = BuildFastLookup(properties, true); propertyInfos = new ObjectPropertyInfos(properties, fastLookup); } else if (properties.Length == 0) { propertyInfos = ObjectPropertyInfos.SimpleToString; } else { propertyInfos = new ObjectPropertyInfos(properties, null); } } return propertyInfos; } private static bool ConvertSimpleToString(Type objectType) { if (typeof(IFormattable).IsAssignableFrom(objectType)) return true; if (typeof(Uri).IsAssignableFrom(objectType)) return true; if (typeof(MemberInfo).IsAssignableFrom(objectType)) return true; // Skip serializing all types in the application if (typeof(Assembly).IsAssignableFrom(objectType)) return true; // Skip serializing all types in the application if (typeof(Module).IsAssignableFrom(objectType)) return true; // Skip serializing all types in the application if (typeof(System.IO.Stream).IsAssignableFrom(objectType)) return true; // Skip serializing properties that often throws exceptions return false; } private static PropertyInfo[] GetPublicProperties(Type type) { PropertyInfo[] properties = null; try { properties = type.GetProperties(PublicProperties); } catch (Exception ex) { InternalLogger.Warn(ex, "Failed to get object properties for type: {0}", type); } // Skip Index-Item-Properties (Ex. public string this[int Index]) if (properties != null) { foreach (var prop in properties) { if (!prop.IsValidPublicProperty()) { properties = properties.Where(p => p.IsValidPublicProperty()).ToArray(); break; } } } return properties ?? ArrayHelper.Empty<PropertyInfo>(); } private static FastPropertyLookup[] BuildFastLookup(PropertyInfo[] properties, bool includeType) { int fastAccessIndex = includeType ? 1 : 0; FastPropertyLookup[] fastLookup = new FastPropertyLookup[properties.Length + fastAccessIndex]; if (includeType) { fastLookup[0] = new FastPropertyLookup("Type", TypeCode.String, (o, p) => o.GetType().ToString()); } foreach (var prop in properties) { var getterMethod = prop.GetGetMethod(); Type propertyType = getterMethod.ReturnType; ReflectionHelpers.LateBoundMethod valueLookup = ReflectionHelpers.CreateLateBoundMethod(getterMethod); #if NETSTANDARD1_3 TypeCode typeCode = propertyType == typeof(string) ? TypeCode.String : (propertyType == typeof(int) ? TypeCode.Int32 : TypeCode.Object); #else TypeCode typeCode = Type.GetTypeCode(propertyType); // Skip cyclic-reference checks when not TypeCode.Object #endif fastLookup[fastAccessIndex++] = new FastPropertyLookup(prop.Name, typeCode, valueLookup); } return fastLookup; } private const BindingFlags PublicProperties = BindingFlags.Instance | BindingFlags.Public; public struct ObjectPropertyList : IEnumerable<ObjectPropertyList.PropertyValue> { internal static readonly StringComparer NameComparer = StringComparer.Ordinal; private static readonly FastPropertyLookup[] CreateIDictionaryEnumerator = new[] { new FastPropertyLookup(string.Empty, TypeCode.Object, (o, p) => ((IDictionary<string, object>)o).GetEnumerator()) }; private readonly object _object; private readonly PropertyInfo[] _properties; private readonly FastPropertyLookup[] _fastLookup; public struct PropertyValue { public readonly string Name; public readonly object Value; public TypeCode TypeCode => Value == null ? TypeCode.Empty : _typecode; private readonly TypeCode _typecode; public PropertyValue(string name, object value, TypeCode typeCode) { Name = name; Value = value; _typecode = typeCode; } public PropertyValue(object owner, PropertyInfo propertyInfo) { Name = propertyInfo.Name; Value = propertyInfo.GetValue(owner, null); _typecode = TypeCode.Object; } public PropertyValue(object owner, FastPropertyLookup fastProperty) { Name = fastProperty.Name; Value = fastProperty.ValueLookup(owner, null); _typecode = fastProperty.TypeCode; } } public bool ConvertToString => _properties?.Length == 0; internal ObjectPropertyList(object value, PropertyInfo[] properties, FastPropertyLookup[] fastLookup) { _object = value; _properties = properties; _fastLookup = fastLookup; } public ObjectPropertyList(IDictionary<string, object> value) { _object = value; // Expando objects _properties = null; _fastLookup = CreateIDictionaryEnumerator; } public bool TryGetPropertyValue(string name, out PropertyValue propertyValue) { if (_properties != null) { if (_fastLookup != null) { return TryFastLookupPropertyValue(name, out propertyValue); } else { return TrySlowLookupPropertyValue(name, out propertyValue); } } else if (_object is IDictionary<string, object> expandoObject) { if (expandoObject.TryGetValue(name, out var objectValue)) { propertyValue = new PropertyValue(name, objectValue, TypeCode.Object); return true; } propertyValue = default(PropertyValue); return false; } else { return TryListLookupPropertyValue(name, out propertyValue); } } /// <summary> /// Scans properties for name (Skips string-compare and value-lookup until finding match) /// </summary> private bool TryFastLookupPropertyValue(string name, out PropertyValue propertyValue) { int nameHashCode = NameComparer.GetHashCode(name); foreach (var fastProperty in _fastLookup) { if (fastProperty.NameHashCode == nameHashCode && NameComparer.Equals(fastProperty.Name, name)) { propertyValue = new PropertyValue(_object, fastProperty); return true; } } propertyValue = default(PropertyValue); return false; } /// <summary> /// Scans properties for name (Skips property value lookup until finding match) /// </summary> private bool TrySlowLookupPropertyValue(string name, out PropertyValue propertyValue) { foreach (var propInfo in _properties) { if (NameComparer.Equals(propInfo.Name, name)) { propertyValue = new PropertyValue(_object, propInfo); return true; } } propertyValue = default(PropertyValue); return false; } /// <summary> /// Scans properties for name /// </summary> private bool TryListLookupPropertyValue(string name, out PropertyValue propertyValue) { foreach (var item in this) { if (NameComparer.Equals(item.Name, name)) { propertyValue = item; return true; } } propertyValue = default(PropertyValue); return false; } public override string ToString() { return _object?.ToString() ?? "null"; } public Enumerator GetEnumerator() { if (_properties != null) return new Enumerator(_object, _properties, _fastLookup); else return new Enumerator((IEnumerator<KeyValuePair<string, object>>)_fastLookup[0].ValueLookup(_object, null)); } IEnumerator<PropertyValue> IEnumerable<PropertyValue>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public struct Enumerator : IEnumerator<PropertyValue> { private readonly object _owner; private readonly PropertyInfo[] _properties; private readonly FastPropertyLookup[] _fastLookup; private readonly IEnumerator<KeyValuePair<string, object>> _enumerator; private int _index; internal Enumerator(object owner, PropertyInfo[] properties, FastPropertyLookup[] fastLookup) { _owner = owner; _properties = properties; _fastLookup = fastLookup; _index = -1; _enumerator = null; } internal Enumerator(IEnumerator<KeyValuePair<string, object>> enumerator) { _owner = enumerator; _properties = null; _fastLookup = null; _index = 0; _enumerator = enumerator; } public PropertyValue Current { get { try { if (_fastLookup != null) return new PropertyValue(_owner, _fastLookup[_index]); else if (_properties != null) return new PropertyValue(_owner, _properties[_index]); else return new PropertyValue(_enumerator.Current.Key, _enumerator.Current.Value, TypeCode.Object); } catch (Exception ex) { InternalLogger.Debug(ex, "Failed to get property value for object: {0}", _owner); return default(PropertyValue); } } } object IEnumerator.Current => Current; public void Dispose() { _enumerator?.Dispose(); } public bool MoveNext() { if (_properties != null) return ++_index < (_fastLookup?.Length ?? _properties.Length); else return _enumerator.MoveNext(); } public void Reset() { if (_properties != null) _index = -1; else _enumerator.Reset(); } } } internal struct FastPropertyLookup { public readonly string Name; public readonly ReflectionHelpers.LateBoundMethod ValueLookup; public readonly TypeCode TypeCode; public readonly int NameHashCode; public FastPropertyLookup(string name, TypeCode typeCode, ReflectionHelpers.LateBoundMethod valueLookup) { Name = name; ValueLookup = valueLookup; TypeCode = typeCode; NameHashCode = ObjectPropertyList.NameComparer.GetHashCode(name); } } private struct ObjectPropertyInfos : IEquatable<ObjectPropertyInfos> { public readonly PropertyInfo[] Properties; public readonly FastPropertyLookup[] FastLookup; public static readonly ObjectPropertyInfos SimpleToString = new ObjectPropertyInfos(ArrayHelper.Empty<PropertyInfo>(), ArrayHelper.Empty<FastPropertyLookup>()); public ObjectPropertyInfos(PropertyInfo[] properties, FastPropertyLookup[] fastLookup) { Properties = properties; FastLookup = fastLookup; } public bool HasFastLookup => FastLookup != null; public bool Equals(ObjectPropertyInfos other) { return ReferenceEquals(Properties, other.Properties) && FastLookup?.Length == other.FastLookup?.Length; } } #if DYNAMIC_OBJECT private static Dictionary<string, object> DynamicObjectToDict(DynamicObject d) { var newVal = new Dictionary<string, object>(); foreach (var propName in d.GetDynamicMemberNames()) { if (d.TryGetMember(new GetBinderAdapter(propName), out var result)) { newVal[propName] = result; } } return newVal; } /// <summary> /// Binder for retrieving value of <see cref="DynamicObject"/> /// </summary> private sealed class GetBinderAdapter : GetMemberBinder { internal GetBinderAdapter(string name) : base(name, false) { } /// <inheritdoc /> public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { return target; } } #endif private static bool IsGenericDictionaryEnumeratorType(Type interfaceType) { if (interfaceType.IsGenericType()) { if (interfaceType.GetGenericTypeDefinition() == typeof(IDictionary<,>) #if NET4_5 || interfaceType.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>) #endif ) { if (interfaceType.GetGenericArguments()[0] == typeof(string)) { return true; } } } return false; } private interface IDictionaryEnumerator { IEnumerator<KeyValuePair<string,object>> GetEnumerator(object value); } internal sealed class DictionaryEnumerator<TKey, TValue> : IDictionaryEnumerator { public IEnumerator<KeyValuePair<string, object>> GetEnumerator(object value) { if (value is IDictionary<TKey, TValue> dictionary) { if (dictionary.Count > 0) return YieldEnumerator(dictionary); } #if NET4_5 else if (value is IReadOnlyDictionary<TKey, TValue> readonlyDictionary) { if (readonlyDictionary.Count > 0) return YieldEnumerator(readonlyDictionary); } #endif return EmptyDictionaryEnumerator.Default; } private IEnumerator<KeyValuePair<string, object>> YieldEnumerator(IDictionary<TKey,TValue> dictionary) { foreach (var item in dictionary) yield return new KeyValuePair<string, object>(item.Key.ToString(), item.Value); } #if NET4_5 private IEnumerator<KeyValuePair<string, object>> YieldEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary) { foreach (var item in dictionary) yield return new KeyValuePair<string, object>(item.Key.ToString(), item.Value); } #endif private sealed class EmptyDictionaryEnumerator : IEnumerator<KeyValuePair<string, object>> { public static readonly EmptyDictionaryEnumerator Default = new EmptyDictionaryEnumerator(); KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current => default(KeyValuePair<string, object>); object IEnumerator.Current => default(KeyValuePair<string, object>); bool IEnumerator.MoveNext() => false; void IDisposable.Dispose() { // Nothing here on purpose } void IEnumerator.Reset() { // Nothing here on purpose } } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Redshift.Model { /// <summary> /// Container for the parameters to the RestoreFromClusterSnapshot operation. /// Creates a new cluster from a snapshot. By default, Amazon Redshift creates the resulting /// cluster with the same configuration as the original cluster from which the snapshot /// was created, except that the new cluster is created with the default cluster security /// and parameter groups. After Amazon Redshift creates the cluster, you can use the <a>ModifyCluster</a> /// API to associate a different security group and different parameter group with the /// restored cluster. If you are using a DS node type, you can also choose to change to /// another DS node type of the same size during restore. /// /// /// <para> /// If you restore a cluster into a VPC, you must provide a cluster subnet group where /// you want the cluster restored. /// </para> /// /// <para> /// For more information about working with snapshots, go to <a href="http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html">Amazon /// Redshift Snapshots</a> in the <i>Amazon Redshift Cluster Management Guide</i>. /// </para> /// </summary> public partial class RestoreFromClusterSnapshotRequest : AmazonRedshiftRequest { private bool? _allowVersionUpgrade; private int? _automatedSnapshotRetentionPeriod; private string _availabilityZone; private string _clusterIdentifier; private string _clusterParameterGroupName; private List<string> _clusterSecurityGroups = new List<string>(); private string _clusterSubnetGroupName; private string _elasticIp; private string _hsmClientCertificateIdentifier; private string _hsmConfigurationIdentifier; private string _kmsKeyId; private string _nodeType; private string _ownerAccount; private int? _port; private string _preferredMaintenanceWindow; private bool? _publiclyAccessible; private string _snapshotClusterIdentifier; private string _snapshotIdentifier; private List<string> _vpcSecurityGroupIds = new List<string>(); /// <summary> /// Gets and sets the property AllowVersionUpgrade. /// <para> /// If <code>true</code>, major version upgrades can be applied during the maintenance /// window to the Amazon Redshift engine that is running on the cluster. /// </para> /// /// <para> /// Default: <code>true</code> /// </para> /// </summary> public bool AllowVersionUpgrade { get { return this._allowVersionUpgrade.GetValueOrDefault(); } set { this._allowVersionUpgrade = value; } } // Check to see if AllowVersionUpgrade property is set internal bool IsSetAllowVersionUpgrade() { return this._allowVersionUpgrade.HasValue; } /// <summary> /// Gets and sets the property AutomatedSnapshotRetentionPeriod. /// <para> /// The number of days that automated snapshots are retained. If the value is 0, automated /// snapshots are disabled. Even if automated snapshots are disabled, you can still create /// manual snapshots when you want with <a>CreateClusterSnapshot</a>. /// </para> /// /// <para> /// Default: The value selected for the cluster from which the snapshot was taken. /// </para> /// /// <para> /// Constraints: Must be a value from 0 to 35. /// </para> /// </summary> public int AutomatedSnapshotRetentionPeriod { get { return this._automatedSnapshotRetentionPeriod.GetValueOrDefault(); } set { this._automatedSnapshotRetentionPeriod = value; } } // Check to see if AutomatedSnapshotRetentionPeriod property is set internal bool IsSetAutomatedSnapshotRetentionPeriod() { return this._automatedSnapshotRetentionPeriod.HasValue; } /// <summary> /// Gets and sets the property AvailabilityZone. /// <para> /// The Amazon EC2 Availability Zone in which to restore the cluster. /// </para> /// /// <para> /// Default: A random, system-chosen Availability Zone. /// </para> /// /// <para> /// Example: <code>us-east-1a</code> /// </para> /// </summary> public string AvailabilityZone { get { return this._availabilityZone; } set { this._availabilityZone = value; } } // Check to see if AvailabilityZone property is set internal bool IsSetAvailabilityZone() { return this._availabilityZone != null; } /// <summary> /// Gets and sets the property ClusterIdentifier. /// <para> /// The identifier of the cluster that will be created from restoring the snapshot. /// </para> /// /// <para> /// /// <para> /// Constraints: /// </para> /// <ul> <li>Must contain from 1 to 63 alphanumeric characters or hyphens.</li> <li>Alphabetic /// characters must be lowercase.</li> <li>First character must be a letter.</li> <li>Cannot /// end with a hyphen or contain two consecutive hyphens.</li> <li>Must be unique for /// all clusters within an AWS account.</li> </ul> /// </para> /// </summary> public string ClusterIdentifier { get { return this._clusterIdentifier; } set { this._clusterIdentifier = value; } } // Check to see if ClusterIdentifier property is set internal bool IsSetClusterIdentifier() { return this._clusterIdentifier != null; } /// <summary> /// Gets and sets the property ClusterParameterGroupName. /// <para> /// The name of the parameter group to be associated with this cluster. /// </para> /// /// <para> /// Default: The default Amazon Redshift cluster parameter group. For information about /// the default parameter group, go to <a href="http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-parameter-groups.html">Working /// with Amazon Redshift Parameter Groups</a>. /// </para> /// /// <para> /// Constraints: /// </para> /// <ul> <li>Must be 1 to 255 alphanumeric characters or hyphens.</li> <li>First character /// must be a letter.</li> <li>Cannot end with a hyphen or contain two consecutive hyphens.</li> /// </ul> /// </summary> public string ClusterParameterGroupName { get { return this._clusterParameterGroupName; } set { this._clusterParameterGroupName = value; } } // Check to see if ClusterParameterGroupName property is set internal bool IsSetClusterParameterGroupName() { return this._clusterParameterGroupName != null; } /// <summary> /// Gets and sets the property ClusterSecurityGroups. /// <para> /// A list of security groups to be associated with this cluster. /// </para> /// /// <para> /// Default: The default cluster security group for Amazon Redshift. /// </para> /// /// <para> /// Cluster security groups only apply to clusters outside of VPCs. /// </para> /// </summary> public List<string> ClusterSecurityGroups { get { return this._clusterSecurityGroups; } set { this._clusterSecurityGroups = value; } } // Check to see if ClusterSecurityGroups property is set internal bool IsSetClusterSecurityGroups() { return this._clusterSecurityGroups != null && this._clusterSecurityGroups.Count > 0; } /// <summary> /// Gets and sets the property ClusterSubnetGroupName. /// <para> /// The name of the subnet group where you want to cluster restored. /// </para> /// /// <para> /// A snapshot of cluster in VPC can be restored only in VPC. Therefore, you must provide /// subnet group name where you want the cluster restored. /// </para> /// </summary> public string ClusterSubnetGroupName { get { return this._clusterSubnetGroupName; } set { this._clusterSubnetGroupName = value; } } // Check to see if ClusterSubnetGroupName property is set internal bool IsSetClusterSubnetGroupName() { return this._clusterSubnetGroupName != null; } /// <summary> /// Gets and sets the property ElasticIp. /// <para> /// The elastic IP (EIP) address for the cluster. /// </para> /// </summary> public string ElasticIp { get { return this._elasticIp; } set { this._elasticIp = value; } } // Check to see if ElasticIp property is set internal bool IsSetElasticIp() { return this._elasticIp != null; } /// <summary> /// Gets and sets the property HsmClientCertificateIdentifier. /// <para> /// Specifies the name of the HSM client certificate the Amazon Redshift cluster uses /// to retrieve the data encryption keys stored in an HSM. /// </para> /// </summary> public string HsmClientCertificateIdentifier { get { return this._hsmClientCertificateIdentifier; } set { this._hsmClientCertificateIdentifier = value; } } // Check to see if HsmClientCertificateIdentifier property is set internal bool IsSetHsmClientCertificateIdentifier() { return this._hsmClientCertificateIdentifier != null; } /// <summary> /// Gets and sets the property HsmConfigurationIdentifier. /// <para> /// Specifies the name of the HSM configuration that contains the information the Amazon /// Redshift cluster can use to retrieve and store keys in an HSM. /// </para> /// </summary> public string HsmConfigurationIdentifier { get { return this._hsmConfigurationIdentifier; } set { this._hsmConfigurationIdentifier = value; } } // Check to see if HsmConfigurationIdentifier property is set internal bool IsSetHsmConfigurationIdentifier() { return this._hsmConfigurationIdentifier != null; } /// <summary> /// Gets and sets the property KmsKeyId. /// <para> /// The AWS Key Management Service (KMS) key ID of the encryption key that you want to /// use to encrypt data in the cluster that you restore from a shared snapshot. /// </para> /// </summary> public string KmsKeyId { get { return this._kmsKeyId; } set { this._kmsKeyId = value; } } // Check to see if KmsKeyId property is set internal bool IsSetKmsKeyId() { return this._kmsKeyId != null; } /// <summary> /// Gets and sets the property NodeType. /// <para> /// The node type that the restored cluster will be provisioned with. /// </para> /// /// <para> /// Default: The node type of the cluster from which the snapshot was taken. You can /// modify this if you are using any DS node type. In that case, you can choose to restore /// into another DS node type of the same size. For example, you can restore ds1.8xlarge /// into ds2.8xlarge, or ds2.xlarge into ds1.xlarge. If you have a DC instance type, you /// must restore into that same instance type and size. In other words, you can only restore /// a dc1.large instance type into another dc1.large instance type. For more information /// about node types, see <a href="http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#rs-about-clusters-and-nodes"> /// About Clusters and Nodes</a> in the <i>Amazon Redshift Cluster Management Guide</i> /// </para> /// </summary> public string NodeType { get { return this._nodeType; } set { this._nodeType = value; } } // Check to see if NodeType property is set internal bool IsSetNodeType() { return this._nodeType != null; } /// <summary> /// Gets and sets the property OwnerAccount. /// <para> /// The AWS customer account used to create or copy the snapshot. Required if you are /// restoring a snapshot you do not own, optional if you own the snapshot. /// </para> /// </summary> public string OwnerAccount { get { return this._ownerAccount; } set { this._ownerAccount = value; } } // Check to see if OwnerAccount property is set internal bool IsSetOwnerAccount() { return this._ownerAccount != null; } /// <summary> /// Gets and sets the property Port. /// <para> /// The port number on which the cluster accepts connections. /// </para> /// /// <para> /// Default: The same port as the original cluster. /// </para> /// /// <para> /// Constraints: Must be between <code>1115</code> and <code>65535</code>. /// </para> /// </summary> public int Port { get { return this._port.GetValueOrDefault(); } set { this._port = value; } } // Check to see if Port property is set internal bool IsSetPort() { return this._port.HasValue; } /// <summary> /// Gets and sets the property PreferredMaintenanceWindow. /// <para> /// The weekly time range (in UTC) during which automated cluster maintenance can occur. /// /// </para> /// /// <para> /// Format: <code>ddd:hh24:mi-ddd:hh24:mi</code> /// </para> /// /// <para> /// Default: The value selected for the cluster from which the snapshot was taken. For /// more information about the time blocks for each region, see <a href="http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#rs-maintenance-windows">Maintenance /// Windows</a> in Amazon Redshift Cluster Management Guide. /// </para> /// /// <para> /// Valid Days: Mon | Tue | Wed | Thu | Fri | Sat | Sun /// </para> /// /// <para> /// Constraints: Minimum 30-minute window. /// </para> /// </summary> public string PreferredMaintenanceWindow { get { return this._preferredMaintenanceWindow; } set { this._preferredMaintenanceWindow = value; } } // Check to see if PreferredMaintenanceWindow property is set internal bool IsSetPreferredMaintenanceWindow() { return this._preferredMaintenanceWindow != null; } /// <summary> /// Gets and sets the property PubliclyAccessible. /// <para> /// If <code>true</code>, the cluster can be accessed from a public network. /// </para> /// </summary> public bool PubliclyAccessible { get { return this._publiclyAccessible.GetValueOrDefault(); } set { this._publiclyAccessible = value; } } // Check to see if PubliclyAccessible property is set internal bool IsSetPubliclyAccessible() { return this._publiclyAccessible.HasValue; } /// <summary> /// Gets and sets the property SnapshotClusterIdentifier. /// <para> /// The name of the cluster the source snapshot was created from. This parameter is required /// if your IAM user has a policy containing a snapshot resource element that specifies /// anything other than * for the cluster name. /// </para> /// </summary> public string SnapshotClusterIdentifier { get { return this._snapshotClusterIdentifier; } set { this._snapshotClusterIdentifier = value; } } // Check to see if SnapshotClusterIdentifier property is set internal bool IsSetSnapshotClusterIdentifier() { return this._snapshotClusterIdentifier != null; } /// <summary> /// Gets and sets the property SnapshotIdentifier. /// <para> /// The name of the snapshot from which to create the new cluster. This parameter isn't /// case sensitive. /// </para> /// /// <para> /// Example: <code>my-snapshot-id</code> /// </para> /// </summary> public string SnapshotIdentifier { get { return this._snapshotIdentifier; } set { this._snapshotIdentifier = value; } } // Check to see if SnapshotIdentifier property is set internal bool IsSetSnapshotIdentifier() { return this._snapshotIdentifier != null; } /// <summary> /// Gets and sets the property VpcSecurityGroupIds. /// <para> /// A list of Virtual Private Cloud (VPC) security groups to be associated with the cluster. /// /// </para> /// /// <para> /// Default: The default VPC security group is associated with the cluster. /// </para> /// /// <para> /// VPC security groups only apply to clusters in VPCs. /// </para> /// </summary> public List<string> VpcSecurityGroupIds { get { return this._vpcSecurityGroupIds; } set { this._vpcSecurityGroupIds = value; } } // Check to see if VpcSecurityGroupIds property is set internal bool IsSetVpcSecurityGroupIds() { return this._vpcSecurityGroupIds != null && this._vpcSecurityGroupIds.Count > 0; } } }
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; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnMunicipio class. /// </summary> [Serializable] public partial class PnMunicipioCollection : ActiveList<PnMunicipio, PnMunicipioCollection> { public PnMunicipioCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnMunicipioCollection</returns> public PnMunicipioCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnMunicipio 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 PN_municipios table. /// </summary> [Serializable] public partial class PnMunicipio : ActiveRecord<PnMunicipio>, IActiveRecord { #region .ctors and Default Settings public PnMunicipio() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnMunicipio(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnMunicipio(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnMunicipio(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("PN_municipios", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdMunicipio = new TableSchema.TableColumn(schema); colvarIdMunicipio.ColumnName = "id_municipio"; colvarIdMunicipio.DataType = DbType.Int32; colvarIdMunicipio.MaxLength = 0; colvarIdMunicipio.AutoIncrement = true; colvarIdMunicipio.IsNullable = false; colvarIdMunicipio.IsPrimaryKey = true; colvarIdMunicipio.IsForeignKey = false; colvarIdMunicipio.IsReadOnly = false; colvarIdMunicipio.DefaultSetting = @""; colvarIdMunicipio.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdMunicipio); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = -1; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = true; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarIdLocalidad = new TableSchema.TableColumn(schema); colvarIdLocalidad.ColumnName = "id_localidad"; colvarIdLocalidad.DataType = DbType.Int32; colvarIdLocalidad.MaxLength = 0; colvarIdLocalidad.AutoIncrement = false; colvarIdLocalidad.IsNullable = false; colvarIdLocalidad.IsPrimaryKey = false; colvarIdLocalidad.IsForeignKey = false; colvarIdLocalidad.IsReadOnly = false; colvarIdLocalidad.DefaultSetting = @""; colvarIdLocalidad.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdLocalidad); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_municipios",schema); } } #endregion #region Props [XmlAttribute("IdMunicipio")] [Bindable(true)] public int IdMunicipio { get { return GetColumnValue<int>(Columns.IdMunicipio); } set { SetColumnValue(Columns.IdMunicipio, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("IdLocalidad")] [Bindable(true)] public int IdLocalidad { get { return GetColumnValue<int>(Columns.IdLocalidad); } set { SetColumnValue(Columns.IdLocalidad, value); } } #endregion //no foreign key tables defined (0) //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(string varNombre,int varIdLocalidad) { PnMunicipio item = new PnMunicipio(); item.Nombre = varNombre; item.IdLocalidad = varIdLocalidad; 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(int varIdMunicipio,string varNombre,int varIdLocalidad) { PnMunicipio item = new PnMunicipio(); item.IdMunicipio = varIdMunicipio; item.Nombre = varNombre; item.IdLocalidad = varIdLocalidad; 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 IdMunicipioColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdLocalidadColumn { get { return Schema.Columns[2]; } } #endregion #region Columns Struct public struct Columns { public static string IdMunicipio = @"id_municipio"; public static string Nombre = @"nombre"; public static string IdLocalidad = @"id_localidad"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using lro = Google.LongRunning; /// <summary>Generated snippets.</summary> public sealed class GeneratedUrlMapsClientSnippets { /// <summary>Snippet for AggregatedList</summary> public void AggregatedListRequestObject() { // Snippet: AggregatedList(AggregatedListUrlMapsRequest, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) AggregatedListUrlMapsRequest request = new AggregatedListUrlMapsRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<UrlMapsAggregatedList, KeyValuePair<string, UrlMapsScopedList>> response = urlMapsClient.AggregatedList(request); // Iterate over all response items, lazily performing RPCs as required foreach (KeyValuePair<string, UrlMapsScopedList> item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (UrlMapsAggregatedList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, UrlMapsScopedList> item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, UrlMapsScopedList>> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, UrlMapsScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedListAsync</summary> public async Task AggregatedListRequestObjectAsync() { // Snippet: AggregatedListAsync(AggregatedListUrlMapsRequest, CallSettings) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) AggregatedListUrlMapsRequest request = new AggregatedListUrlMapsRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<UrlMapsAggregatedList, KeyValuePair<string, UrlMapsScopedList>> response = urlMapsClient.AggregatedListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, UrlMapsScopedList> item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((UrlMapsAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, UrlMapsScopedList> item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, UrlMapsScopedList>> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, UrlMapsScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedList</summary> public void AggregatedList() { // Snippet: AggregatedList(string, string, int?, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<UrlMapsAggregatedList, KeyValuePair<string, UrlMapsScopedList>> response = urlMapsClient.AggregatedList(project); // Iterate over all response items, lazily performing RPCs as required foreach (KeyValuePair<string, UrlMapsScopedList> item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (UrlMapsAggregatedList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, UrlMapsScopedList> item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, UrlMapsScopedList>> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, UrlMapsScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedListAsync</summary> public async Task AggregatedListAsync() { // Snippet: AggregatedListAsync(string, string, int?, CallSettings) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<UrlMapsAggregatedList, KeyValuePair<string, UrlMapsScopedList>> response = urlMapsClient.AggregatedListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, UrlMapsScopedList> item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((UrlMapsAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, UrlMapsScopedList> item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, UrlMapsScopedList>> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, UrlMapsScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeleteUrlMapRequest, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) DeleteUrlMapRequest request = new DeleteUrlMapRequest { RequestId = "", Project = "", UrlMap = "", }; // Make the request lro::Operation<Operation, Operation> response = urlMapsClient.Delete(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = urlMapsClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeleteUrlMapRequest, CallSettings) // Additional: DeleteAsync(DeleteUrlMapRequest, CancellationToken) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) DeleteUrlMapRequest request = new DeleteUrlMapRequest { RequestId = "", Project = "", UrlMap = "", }; // Make the request lro::Operation<Operation, Operation> response = await urlMapsClient.DeleteAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await urlMapsClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) string project = ""; string urlMap = ""; // Make the request lro::Operation<Operation, Operation> response = urlMapsClient.Delete(project, urlMap); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = urlMapsClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, CallSettings) // Additional: DeleteAsync(string, string, CancellationToken) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string urlMap = ""; // Make the request lro::Operation<Operation, Operation> response = await urlMapsClient.DeleteAsync(project, urlMap); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await urlMapsClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetUrlMapRequest, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) GetUrlMapRequest request = new GetUrlMapRequest { Project = "", UrlMap = "", }; // Make the request UrlMap response = urlMapsClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetUrlMapRequest, CallSettings) // Additional: GetAsync(GetUrlMapRequest, CancellationToken) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) GetUrlMapRequest request = new GetUrlMapRequest { Project = "", UrlMap = "", }; // Make the request UrlMap response = await urlMapsClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) string project = ""; string urlMap = ""; // Make the request UrlMap response = urlMapsClient.Get(project, urlMap); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, CallSettings) // Additional: GetAsync(string, string, CancellationToken) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string urlMap = ""; // Make the request UrlMap response = await urlMapsClient.GetAsync(project, urlMap); // End snippet } /// <summary>Snippet for Insert</summary> public void InsertRequestObject() { // Snippet: Insert(InsertUrlMapRequest, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) InsertUrlMapRequest request = new InsertUrlMapRequest { RequestId = "", UrlMapResource = new UrlMap(), Project = "", }; // Make the request lro::Operation<Operation, Operation> response = urlMapsClient.Insert(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = urlMapsClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertRequestObjectAsync() { // Snippet: InsertAsync(InsertUrlMapRequest, CallSettings) // Additional: InsertAsync(InsertUrlMapRequest, CancellationToken) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) InsertUrlMapRequest request = new InsertUrlMapRequest { RequestId = "", UrlMapResource = new UrlMap(), Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await urlMapsClient.InsertAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await urlMapsClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Insert</summary> public void Insert() { // Snippet: Insert(string, UrlMap, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) string project = ""; UrlMap urlMapResource = new UrlMap(); // Make the request lro::Operation<Operation, Operation> response = urlMapsClient.Insert(project, urlMapResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = urlMapsClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertAsync() { // Snippet: InsertAsync(string, UrlMap, CallSettings) // Additional: InsertAsync(string, UrlMap, CancellationToken) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) string project = ""; UrlMap urlMapResource = new UrlMap(); // Make the request lro::Operation<Operation, Operation> response = await urlMapsClient.InsertAsync(project, urlMapResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await urlMapsClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InvalidateCache</summary> public void InvalidateCacheRequestObject() { // Snippet: InvalidateCache(InvalidateCacheUrlMapRequest, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) InvalidateCacheUrlMapRequest request = new InvalidateCacheUrlMapRequest { RequestId = "", Project = "", CacheInvalidationRuleResource = new CacheInvalidationRule(), UrlMap = "", }; // Make the request lro::Operation<Operation, Operation> response = urlMapsClient.InvalidateCache(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = urlMapsClient.PollOnceInvalidateCache(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InvalidateCacheAsync</summary> public async Task InvalidateCacheRequestObjectAsync() { // Snippet: InvalidateCacheAsync(InvalidateCacheUrlMapRequest, CallSettings) // Additional: InvalidateCacheAsync(InvalidateCacheUrlMapRequest, CancellationToken) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) InvalidateCacheUrlMapRequest request = new InvalidateCacheUrlMapRequest { RequestId = "", Project = "", CacheInvalidationRuleResource = new CacheInvalidationRule(), UrlMap = "", }; // Make the request lro::Operation<Operation, Operation> response = await urlMapsClient.InvalidateCacheAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await urlMapsClient.PollOnceInvalidateCacheAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InvalidateCache</summary> public void InvalidateCache() { // Snippet: InvalidateCache(string, string, CacheInvalidationRule, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) string project = ""; string urlMap = ""; CacheInvalidationRule cacheInvalidationRuleResource = new CacheInvalidationRule(); // Make the request lro::Operation<Operation, Operation> response = urlMapsClient.InvalidateCache(project, urlMap, cacheInvalidationRuleResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = urlMapsClient.PollOnceInvalidateCache(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InvalidateCacheAsync</summary> public async Task InvalidateCacheAsync() { // Snippet: InvalidateCacheAsync(string, string, CacheInvalidationRule, CallSettings) // Additional: InvalidateCacheAsync(string, string, CacheInvalidationRule, CancellationToken) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string urlMap = ""; CacheInvalidationRule cacheInvalidationRuleResource = new CacheInvalidationRule(); // Make the request lro::Operation<Operation, Operation> response = await urlMapsClient.InvalidateCacheAsync(project, urlMap, cacheInvalidationRuleResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await urlMapsClient.PollOnceInvalidateCacheAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListUrlMapsRequest, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) ListUrlMapsRequest request = new ListUrlMapsRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<UrlMapList, UrlMap> response = urlMapsClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (UrlMap item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (UrlMapList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (UrlMap item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<UrlMap> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (UrlMap item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListUrlMapsRequest, CallSettings) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) ListUrlMapsRequest request = new ListUrlMapsRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<UrlMapList, UrlMap> response = urlMapsClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((UrlMap item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((UrlMapList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (UrlMap item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<UrlMap> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (UrlMap item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, int?, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<UrlMapList, UrlMap> response = urlMapsClient.List(project); // Iterate over all response items, lazily performing RPCs as required foreach (UrlMap item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (UrlMapList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (UrlMap item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<UrlMap> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (UrlMap item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, int?, CallSettings) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<UrlMapList, UrlMap> response = urlMapsClient.ListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((UrlMap item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((UrlMapList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (UrlMap item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<UrlMap> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (UrlMap item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Patch</summary> public void PatchRequestObject() { // Snippet: Patch(PatchUrlMapRequest, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) PatchUrlMapRequest request = new PatchUrlMapRequest { RequestId = "", UrlMapResource = new UrlMap(), Project = "", UrlMap = "", }; // Make the request lro::Operation<Operation, Operation> response = urlMapsClient.Patch(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = urlMapsClient.PollOncePatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PatchAsync</summary> public async Task PatchRequestObjectAsync() { // Snippet: PatchAsync(PatchUrlMapRequest, CallSettings) // Additional: PatchAsync(PatchUrlMapRequest, CancellationToken) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) PatchUrlMapRequest request = new PatchUrlMapRequest { RequestId = "", UrlMapResource = new UrlMap(), Project = "", UrlMap = "", }; // Make the request lro::Operation<Operation, Operation> response = await urlMapsClient.PatchAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await urlMapsClient.PollOncePatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Patch</summary> public void Patch() { // Snippet: Patch(string, string, UrlMap, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) string project = ""; string urlMap = ""; UrlMap urlMapResource = new UrlMap(); // Make the request lro::Operation<Operation, Operation> response = urlMapsClient.Patch(project, urlMap, urlMapResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = urlMapsClient.PollOncePatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PatchAsync</summary> public async Task PatchAsync() { // Snippet: PatchAsync(string, string, UrlMap, CallSettings) // Additional: PatchAsync(string, string, UrlMap, CancellationToken) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string urlMap = ""; UrlMap urlMapResource = new UrlMap(); // Make the request lro::Operation<Operation, Operation> response = await urlMapsClient.PatchAsync(project, urlMap, urlMapResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await urlMapsClient.PollOncePatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Update</summary> public void UpdateRequestObject() { // Snippet: Update(UpdateUrlMapRequest, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) UpdateUrlMapRequest request = new UpdateUrlMapRequest { RequestId = "", UrlMapResource = new UrlMap(), Project = "", UrlMap = "", }; // Make the request lro::Operation<Operation, Operation> response = urlMapsClient.Update(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = urlMapsClient.PollOnceUpdate(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateAsync</summary> public async Task UpdateRequestObjectAsync() { // Snippet: UpdateAsync(UpdateUrlMapRequest, CallSettings) // Additional: UpdateAsync(UpdateUrlMapRequest, CancellationToken) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) UpdateUrlMapRequest request = new UpdateUrlMapRequest { RequestId = "", UrlMapResource = new UrlMap(), Project = "", UrlMap = "", }; // Make the request lro::Operation<Operation, Operation> response = await urlMapsClient.UpdateAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await urlMapsClient.PollOnceUpdateAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Update</summary> public void Update() { // Snippet: Update(string, string, UrlMap, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) string project = ""; string urlMap = ""; UrlMap urlMapResource = new UrlMap(); // Make the request lro::Operation<Operation, Operation> response = urlMapsClient.Update(project, urlMap, urlMapResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = urlMapsClient.PollOnceUpdate(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateAsync</summary> public async Task UpdateAsync() { // Snippet: UpdateAsync(string, string, UrlMap, CallSettings) // Additional: UpdateAsync(string, string, UrlMap, CancellationToken) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string urlMap = ""; UrlMap urlMapResource = new UrlMap(); // Make the request lro::Operation<Operation, Operation> response = await urlMapsClient.UpdateAsync(project, urlMap, urlMapResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await urlMapsClient.PollOnceUpdateAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Validate</summary> public void ValidateRequestObject() { // Snippet: Validate(ValidateUrlMapRequest, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) ValidateUrlMapRequest request = new ValidateUrlMapRequest { Project = "", UrlMap = "", UrlMapsValidateRequestResource = new UrlMapsValidateRequest(), }; // Make the request UrlMapsValidateResponse response = urlMapsClient.Validate(request); // End snippet } /// <summary>Snippet for ValidateAsync</summary> public async Task ValidateRequestObjectAsync() { // Snippet: ValidateAsync(ValidateUrlMapRequest, CallSettings) // Additional: ValidateAsync(ValidateUrlMapRequest, CancellationToken) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) ValidateUrlMapRequest request = new ValidateUrlMapRequest { Project = "", UrlMap = "", UrlMapsValidateRequestResource = new UrlMapsValidateRequest(), }; // Make the request UrlMapsValidateResponse response = await urlMapsClient.ValidateAsync(request); // End snippet } /// <summary>Snippet for Validate</summary> public void Validate() { // Snippet: Validate(string, string, UrlMapsValidateRequest, CallSettings) // Create client UrlMapsClient urlMapsClient = UrlMapsClient.Create(); // Initialize request argument(s) string project = ""; string urlMap = ""; UrlMapsValidateRequest urlMapsValidateRequestResource = new UrlMapsValidateRequest(); // Make the request UrlMapsValidateResponse response = urlMapsClient.Validate(project, urlMap, urlMapsValidateRequestResource); // End snippet } /// <summary>Snippet for ValidateAsync</summary> public async Task ValidateAsync() { // Snippet: ValidateAsync(string, string, UrlMapsValidateRequest, CallSettings) // Additional: ValidateAsync(string, string, UrlMapsValidateRequest, CancellationToken) // Create client UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string urlMap = ""; UrlMapsValidateRequest urlMapsValidateRequestResource = new UrlMapsValidateRequest(); // Make the request UrlMapsValidateResponse response = await urlMapsClient.ValidateAsync(project, urlMap, urlMapsValidateRequestResource); // End snippet } } }
#region Imported Types using DeviceSQL.Device.ROC.Data; using DeviceSQL.Devices.Device.ROC.Data; using Microsoft.SqlServer.Server; using System; using System.Data.SqlTypes; using System.IO; using System.Linq; #endregion namespace DeviceSQL.SQLTypes.ROCMaster { [Serializable()] [SqlUserDefinedType(Format.UserDefined, IsByteOrdered = false, IsFixedLength = false, MaxByteSize = 27)] public struct ROCMaster_ROCPlusEventRecord : INullable, IBinarySerialize { #region Fields private byte[] data; #endregion #region Properties public bool IsNull { get; internal set; } public static ROCMaster_ROCPlusEventRecord Null { get { return new ROCMaster_ROCPlusEventRecord() { IsNull = true }; } } public byte[] Data { get { if (data == null) { data = new byte[22]; } return data; } internal set { data = value; } } public int Index { get; internal set; } public SqlDateTime DateTimeStamp { get { var dateTimeStamp = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DateTimeStamp; return dateTimeStamp.HasValue ? dateTimeStamp.Value : SqlDateTime.Null; } } public SqlString EventType { get { return new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).EventType.ToString(); } } public SqlString EventCode { get { var eventCode = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).EventCode; return eventCode.HasValue ? eventCode.Value.ToString() : SqlString.Null; } } public string OperatorId { get { return new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).OperatorId; } } internal Tlp Tlp { get { return new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).Tlp; } } public SqlByte PointType { get { return Tlp.PointType; } } public SqlByte LogicalNumber { get { return Tlp.LogicalNumber; } } public SqlByte Parameter { get { return Tlp.Parameter; } } public SqlString DataType { get { var dataType = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DataType; return dataType.HasValue ? dataType.Value.ToString() : SqlString.Null; } } public SqlBinary OldValue { get { return new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).OldValue; } } public SqlBinary NewValue { get { return new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).NewValue; } } public SqlInt32 Spare { get { return new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).Spare; } } public SqlString Description { get { return new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).Description; } } public SqlByte FstNumber { get { var fstNumber = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).FstNumber; return fstNumber.HasValue ? fstNumber.Value : SqlByte.Null; } } public SqlSingle FstValue { get { var fstValue = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).FstValue; return fstValue.HasValue ? fstValue.Value : SqlSingle.Null; } } public SqlDateTime DateTimeValue { get { var dateTimeValue = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DateTimeValue; return dateTimeValue.HasValue ? dateTimeValue.Value : SqlDateTime.Null; } } public SqlSingle CalibrationRawValue { get { var calibrationRawValue = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).CalibrationRawValue; return calibrationRawValue.HasValue ? calibrationRawValue.Value : SqlSingle.Null; } } public SqlSingle CalibrationCalibratedValue { get { var calibrationCalibratedValue = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).CalibrationCalibratedValue; return calibrationCalibratedValue.HasValue ? calibrationCalibratedValue.Value : SqlSingle.Null; } } public ROCMaster_Parameter OldParameterValue { get { if (!PointType.IsNull && !Parameter.IsNull) { switch (new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DataType) { case ParameterType.AC3: return new ROCMaster_Parameter() { RawType = ParameterType.AC3, RawValue = OldValue.Value.Take(3).ToArray() }; case ParameterType.BIN: return new ROCMaster_Parameter() { RawType = ParameterType.BIN, RawValue = OldValue.Value.Take(1).ToArray() }; case ParameterType.FL: return new ROCMaster_Parameter() { RawType = ParameterType.FL, RawValue = OldValue.Value }; case ParameterType.INT16: return new ROCMaster_Parameter() { RawType = ParameterType.INT16, RawValue = OldValue.Value.Take(2).ToArray() }; case ParameterType.INT32: return new ROCMaster_Parameter() { RawType = ParameterType.INT32, RawValue = OldValue.Value }; case ParameterType.INT8: return new ROCMaster_Parameter() { RawType = ParameterType.INT8, RawValue = OldValue.Value.Take(1).ToArray() }; case ParameterType.TLP: return new ROCMaster_Parameter() { RawType = ParameterType.TLP, RawValue = OldValue.Value.Take(3).ToArray() }; case ParameterType.UINT16: return new ROCMaster_Parameter() { RawType = ParameterType.UINT16, RawValue = OldValue.Value.Take(2).ToArray() }; case ParameterType.UINT32: return new ROCMaster_Parameter() { RawType = ParameterType.UINT32, RawValue = OldValue.Value }; case ParameterType.TIME: return new ROCMaster_Parameter() { RawType = ParameterType.TIME, RawValue = OldValue.Value }; case ParameterType.UINT8: return new ROCMaster_Parameter() { RawType = ParameterType.UINT8, RawValue = OldValue.Value.Take(1).ToArray() }; default: return ROCMaster_Parameter.Null; } } else { return ROCMaster_Parameter.Null; } } } public ROCMaster_Parameter NewParameterValue { get { if (!PointType.IsNull && !Parameter.IsNull) { switch (new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DataType) { case ParameterType.AC3: return new ROCMaster_Parameter() { RawType = ParameterType.AC3, RawValue = NewValue.Value.Take(3).ToArray() }; case ParameterType.AC7: return new ROCMaster_Parameter() { RawType = ParameterType.AC7, RawValue = NewValue.Value.Union(new byte[3]).ToArray() }; case ParameterType.AC10: return new ROCMaster_Parameter() { RawType = ParameterType.AC10, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).ToArray() }; case ParameterType.AC12: return new ROCMaster_Parameter() { RawType = ParameterType.AC12, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).Union(new byte[2]).ToArray() }; case ParameterType.AC20: return new ROCMaster_Parameter() { RawType = ParameterType.AC20, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).Union(new byte[10]).ToArray() }; case ParameterType.AC30: return new ROCMaster_Parameter() { RawType = ParameterType.AC30, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).Union(new byte[20]).ToArray() }; case ParameterType.AC40: return new ROCMaster_Parameter() { RawType = ParameterType.AC40, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).Union(new byte[30]).ToArray() }; case ParameterType.BIN: return new ROCMaster_Parameter() { RawType = ParameterType.BIN, RawValue = NewValue.Value.Take(1).ToArray() }; case ParameterType.FL: return new ROCMaster_Parameter() { RawType = ParameterType.FL, RawValue = NewValue.Value }; case ParameterType.DOUBLE: return new ROCMaster_Parameter() { RawType = ParameterType.DOUBLE, RawValue = NewValue.Value.Union(OldValue.Value).ToArray() }; case ParameterType.INT16: return new ROCMaster_Parameter() { RawType = ParameterType.INT16, RawValue = NewValue.Value.Take(2).ToArray() }; case ParameterType.INT32: return new ROCMaster_Parameter() { RawType = ParameterType.INT32, RawValue = NewValue.Value }; case ParameterType.INT8: return new ROCMaster_Parameter() { RawType = ParameterType.INT8, RawValue = NewValue.Value.Take(1).ToArray() }; case ParameterType.TLP: return new ROCMaster_Parameter() { RawType = ParameterType.TLP, RawValue = NewValue.Value.Take(3).ToArray() }; case ParameterType.UINT16: return new ROCMaster_Parameter() { RawType = ParameterType.UINT16, RawValue = NewValue.Value.Take(2).ToArray() }; case ParameterType.UINT32: return new ROCMaster_Parameter() { RawType = ParameterType.UINT32, RawValue = NewValue.Value }; case ParameterType.TIME: return new ROCMaster_Parameter() { RawType = ParameterType.TIME, RawValue = NewValue.Value }; case ParameterType.UINT8: return new ROCMaster_Parameter() { RawType = ParameterType.UINT8, RawValue = NewValue.Value.Take(1).ToArray() }; default: return ROCMaster_Parameter.Null; } } else { return ROCMaster_Parameter.Null; } } } #endregion #region Helper Methods public static ROCMaster_ROCPlusEventRecord Parse(SqlString stringToParse) { var parsedEventRecord = stringToParse.Value.Split(",".ToCharArray()); var base64Bytes = Convert.FromBase64String(parsedEventRecord[1]); if (base64Bytes.Length == 22) { return new ROCMaster_ROCPlusEventRecord() { Index = ushort.Parse(parsedEventRecord[0]), Data = base64Bytes }; } else { throw new ArgumentException("Input must be exactly 22 bytes"); } } public override string ToString() { return string.Format("{0},{1}", Index, Convert.ToBase64String(Data)); } #endregion #region Serialization Methods public void Read(BinaryReader binaryReader) { IsNull = binaryReader.ReadBoolean(); Index = binaryReader.ReadInt32(); if (!IsNull) { Data = binaryReader.ReadBytes(22); } } public void Write(BinaryWriter binaryWriter) { binaryWriter.Write(IsNull); binaryWriter.Write(Index); if (!IsNull) { binaryWriter.Write(Data, 0, 22); } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class InvocationExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override ISignatureHelpProvider CreateSignatureHelpProvider() { return new InvocationExpressionSignatureHelpProvider(); } #region "Regular tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationAfterCloseParen() { var markup = @" class C { int Foo(int x) { [|Foo(Foo(x)$$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int C.Foo(int x)", currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationInsideLambda() { var markup = @" using System; class C { void Foo(Action<int> f) { [|Foo(i => Console.WriteLine(i)$$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(Action<int> f)", currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationInsideLambda2() { var markup = @" using System; class C { void Foo(Action<int> f) { [|Foo(i => Con$$sole.WriteLine(i)|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(Action<int> f)", currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutParameters() { var markup = @" class C { void Foo() { [|Foo($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutParametersMethodXmlComments() { var markup = @" class C { /// <summary> /// Summary for foo /// </summary> void Foo() { [|Foo($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", "Summary for foo", null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersOn1() { var markup = @" class C { void Foo(int a, int b) { [|Foo($$a, b|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class C { /// <summary> /// Summary for Foo /// </summary> /// <param name=" + "\"a\">Param a</param>" + @" /// <param name=" + "\"b\">Param b</param>" + @" void Foo(int a, int b) { [|Foo($$a, b|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", "Summary for Foo", "Param a", currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersOn2() { var markup = @" class C { void Foo(int a, int b) { [|Foo(a, $$b|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersXmlComentsOn2() { var markup = @" class C { /// <summary> /// Summary for Foo /// </summary> /// <param name=" + "\"a\">Param a</param>" + @" /// <param name=" + "\"b\">Param b</param>" + @" void Foo(int a, int b) { [|Foo(a, $$b|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", "Summary for Foo", "Param b", currentParameterIndex: 1)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutClosingParen() { var markup = @" class C { void Foo() { [|Foo($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutClosingParenWithParameters() { var markup = @"class C { void Foo(int a, int b) { [|Foo($$a, b |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutClosingParenWithParametersOn2() { var markup = @" class C { void Foo(int a, int b) { [|Foo(a, $$b |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnLambda() { var markup = @" using System; class C { void Foo() { Action<int> f = (i) => Console.WriteLine(i); [|f($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void Action<int>(int obj)", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnMemberAccessExpression() { var markup = @" class C { static void Bar(int a) { } void Foo() { [|C.Bar($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Bar(int a)", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestExtensionMethod1() { var markup = @" using System; class C { void Method() { string s = ""Text""; [|s.ExtensionMethod($$ |]} } public static class MyExtension { public static int ExtensionMethod(this string s, int x) { return s.Length; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Extension}) int string.ExtensionMethod(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); // TODO: Once we do the work to allow extension methods in nested types, we should change this. Test(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestOptionalParameters() { var markup = @" class Class1 { void Test() { Foo($$ } void Foo(int a = 42) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void Class1.Foo([int a = 42])", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestNoInvocationOnEventNotInCurrentClass() { var markup = @" using System; class C { void Foo() { D d; [|d.evt($$ |]} } public class D { public event Action evt; }"; Test(markup); } [WorkItem(539712)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnNamedType() { var markup = @" class Program { void Main() { C.Foo($$ } } class C { public static double Foo(double x) { return x; } public double Foo(double x, double y) { return x + y; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("double C.Foo(double x)", string.Empty, string.Empty, currentParameterIndex: 0) }; Test(markup, expectedOrderedItems); } [WorkItem(539712)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnInstance() { var markup = @" class Program { void Main() { new C().Foo($$ } } class C { public static double Foo(double x) { return x; } public double Foo(double x, double y) { return x + y; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("double C.Foo(double x, double y)", string.Empty, string.Empty, currentParameterIndex: 0) }; Test(markup, expectedOrderedItems); } [WorkItem(545118)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestStatic1() { var markup = @" class C { static void Foo() { Bar($$ } static void Bar() { } void Bar(int i) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0) }; Test(markup, expectedOrderedItems); } [WorkItem(545118)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestStatic2() { var markup = @" class C { void Foo() { Bar($$ } static void Bar() { } void Bar(int i) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0), new SignatureHelpTestItem("void C.Bar(int i)", currentParameterIndex: 0) }; Test(markup, expectedOrderedItems); } [WorkItem(543117)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnAnonymousType() { var markup = @" using System.Collections.Generic; class Program { static void Main(string[] args) { var foo = new { Name = string.Empty, Age = 30 }; Foo(foo).Add($$); } static List<T> Foo<T>(T t) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( $@"void List<'a>.Add('a item) {FeaturesResources.AnonymousTypes} 'a {FeaturesResources.Is} new {{ string Name, int Age }}", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: $@" {FeaturesResources.AnonymousTypes} 'a {FeaturesResources.Is} new {{ string Name, int Age }}") }; Test(markup, expectedOrderedItems); } [WorkItem(968188)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnBaseExpression_ProtectedAccessibility() { var markup = @" using System; public class Base { protected virtual void Foo(int x) { } } public class Derived : Base { void Test() { base.Foo($$); } protected override void Foo(int x) { throw new NotImplementedException(); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( @"void Base.Foo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty) }; Test(markup, expectedOrderedItems); } [WorkItem(968188)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnBaseExpression_AbstractBase() { var markup = @" using System; public abstract class Base { protected abstract void Foo(int x); } public class Derived : Base { void Test() { base.Foo($$); } protected override void Foo(int x) { throw new NotImplementedException(); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( @"void Base.Foo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty) }; Test(markup, expectedOrderedItems); } [WorkItem(968188)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnThisExpression_ProtectedAccessibility() { var markup = @" using System; public class Base { protected virtual void Foo(int x) { } } public class Derived : Base { void Test() { this.Foo($$); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( @"void Base.Foo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty) }; Test(markup, expectedOrderedItems); } [WorkItem(968188)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnThisExpression_ProtectedAccessibility_Overridden() { var markup = @" using System; public class Base { protected virtual void Foo(int x) { } } public class Derived : Base { void Test() { this.Foo($$); } protected override void Foo(int x) { throw new NotImplementedException(); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( @"void Derived.Foo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty) }; Test(markup, expectedOrderedItems); } [WorkItem(968188)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase() { var markup = @" using System; public abstract class Base { protected abstract void Foo(int x); } public class Derived : Base { void Test() { this.Foo($$); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( @"void Base.Foo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty) }; Test(markup, expectedOrderedItems); } [WorkItem(968188)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase_Overridden() { var markup = @" using System; public abstract class Base { protected abstract void Foo(int x); } public class Derived : Base { void Test() { this.Foo($$); } protected override void Foo(int x) { throw new NotImplementedException(); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( @"void Derived.Foo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty) }; Test(markup, expectedOrderedItems); } [WorkItem(968188)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnBaseExpression_ProtectedInternalAccessibility() { var markup = @" using System; public class Base { protected internal void Foo(int x) { } } public class Derived : Base { void Test() { base.Foo($$); } protected override void Foo(int x) { throw new NotImplementedException(); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( @"void Base.Foo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty) }; Test(markup, expectedOrderedItems); } [WorkItem(968188)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnBaseMember_ProtectedAccessibility_ThroughType() { var markup = @" using System; public class Base { protected virtual void Foo(int x) { } } public class Derived : Base { void Test() { new Base().Foo($$); } protected override void Foo(int x) { throw new NotImplementedException(); } }"; Test(markup, null); } [WorkItem(968188)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnBaseExpression_PrivateAccessibility() { var markup = @" using System; public class Base { private void Foo(int x) { } } public class Derived : Base { void Test() { base.Foo($$); } protected override void Foo(int x) { throw new NotImplementedException(); } }"; Test(markup, null); } #endregion #region "Current Parameter Name" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestCurrentParameterName() { var markup = @" class C { void Foo(int someParameter, bool something) { Foo(something: false, someParameter: $$) } }"; VerifyCurrentParameterName(markup, "someParameter"); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnTriggerParens() { var markup = @" class C { void Foo() { [|Foo($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnTriggerComma() { var markup = @" class C { void Foo(int a, int b) { [|Foo(23,$$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestNoInvocationOnSpace() { var markup = @" class C { void Foo(int a, int b) { [|Foo(23, $$|]); } }"; Test(markup, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '(' }; char[] unexpectedCharacters = { ' ', '[', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Method_BrowsableStateAlways() { var markup = @" class Program { void M() { Foo.Bar($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Method_BrowsableStateNever() { var markup = @" class Program { void M() { Foo.Bar($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Method_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new Foo().Bar($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public void Bar() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever() { var markup = @" class Program { void M() { new Foo().Bar($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar(int x) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Method_Overloads_BothBrowsableNever() { var markup = @" class Program { void M() { new Foo().Bar($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar(int x) { } }"; var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void OverriddenSymbolsFilteredFromSigHelp() { var markup = @" class Program { void M() { new D().Foo($$ } }"; var referencedCode = @" public class B { public virtual void Foo(int original) { } } public class D : B { public override void Foo(int derived) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void D.Foo(int derived)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass() { var markup = @" class Program { void M() { new C().Foo($$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class C { public void Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass() { var markup = @" class Program { void M() { new D().Foo($$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class B { public void Foo() { } } public class D : B { public void Foo(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void B.Foo()", string.Empty, null, currentParameterIndex: 0), new SignatureHelpTestItem("void D.Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0), }; TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_BrowsableStateNeverMethodsInBaseClass() { var markup = @" class Program : B { void M() { Foo($$ } }"; var referencedCode = @" public class B { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void B.Foo()", string.Empty, null, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways() { var markup = @" class Program { void M() { new C<int>().Foo($$ } }"; var referencedCode = @" public class C<T> { public void Foo(T t) { } public void Foo(int i) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1() { var markup = @" class Program { void M() { new C<int>().Foo($$ } }"; var referencedCode = @" public class C<T> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(T t) { } public void Foo(int i) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2() { var markup = @" class Program { void M() { new C<int>().Foo($$ } }"; var referencedCode = @" public class C<T> { public void Foo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(int i) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever() { var markup = @" class Program { void M() { new C<int>().Foo($$ } }"; var referencedCode = @" public class C<T> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(int i) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways() { var markup = @" class Program { void M() { new C<int, int>().Foo($$ } }"; var referencedCode = @" public class C<T, U> { public void Foo(T t) { } public void Foo(U u) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed() { var markup = @" class Program { void M() { new C<int, int>().Foo($$ } }"; var referencedCode = @" public class C<T, U> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(T t) { } public void Foo(U u) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever() { var markup = @" class Program { void M() { new C<int, int>().Foo($$ } }"; var referencedCode = @" public class C<T, U> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(U u) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion #region "Awaitable tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void AwaitableMethod() { var markup = @" using System.Threading.Tasks; class C { async Task Foo() { [|Foo($$|]); } }"; var description = $@" {WorkspacesResources.Usage} await Foo();"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Awaitable}) Task C.Foo()", methodDocumentation: description, currentParameterIndex: 0)); TestSignatureHelpWithMscorlib45(markup, expectedOrderedItems, "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void AwaitableMethod2() { var markup = @" using System.Threading.Tasks; class C { async Task<Task<int>> Foo() { [|Foo($$|]); } }"; var description = $@" {WorkspacesResources.Usage} Task<int> x = await Foo();"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Awaitable}) Task<Task<int>> C.Foo()", methodDocumentation: description, currentParameterIndex: 0)); TestSignatureHelpWithMscorlib45(markup, expectedOrderedItems, "C#"); } #endregion [WorkItem(13849, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestSpecificity1() { var markup = @" class Class1 { static void Main() { var obj = new C<int>(); [|obj.M($$|]) } } class C<T> { /// <param name=""t"">Generic t</param> public void M(T t) { } /// <param name=""t"">Real t</param> public void M(int t) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void C<int>.M(int t)", string.Empty, "Real t", currentParameterIndex: 0) }; Test(markup, expectedOrderedItems); } [WorkItem(530017)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void LongSignature() { var markup = @" class C { void Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z) { [|Foo($$|]) } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( signature: "void C.Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)", prettyPrintedSignature: @"void C.Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)", currentParameterIndex: 0) }; Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void GenericExtensionMethod() { var markup = @" interface IFoo { void Bar<T>(); } static class FooExtensions { public static void Bar<T1, T2>(this IFoo foo) { } } class Program { static void Main() { IFoo f = null; [|f.Bar($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void IFoo.Bar<T>()", currentParameterIndex: 0), new SignatureHelpTestItem($"({CSharpFeaturesResources.Extension}) void IFoo.Bar<T1, T2>()", currentParameterIndex: 0), }; // Extension methods are supported in Interactive/Script (yet). Test(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithCrefXmlComments() { var markup = @" class C { /// <summary> /// Summary for foo. See method <see cref=""Bar"" /> /// </summary> void Foo() { [|Foo($$|]); } void Bar() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", "Summary for foo. See method C.Bar()", null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO void bar() { } #endif void foo() { bar($$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"void C.bar()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO void bar() { } #endif #if BAR void foo() { bar($$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"void C.bar()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false); } [WorkItem(768697)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void InstanceAndStaticMethodsShown1() { var markup = @" class C { Foo Foo; void M() { Foo.Bar($$ } } class Foo { public void Bar(int x) { } public static void Bar(string s) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0), new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0) }; Test(markup, expectedOrderedItems); } [WorkItem(768697)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void InstanceAndStaticMethodsShown2() { var markup = @" class C { Foo Foo; void M() { Foo.Bar($$""); } } class Foo { public void Bar(int x) { } public static void Bar(string s) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0), new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0) }; Test(markup, expectedOrderedItems); } [WorkItem(768697)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void InstanceAndStaticMethodsShown3() { var markup = @" class C { Foo Foo; void M() { Foo.Bar($$ } } class Foo { public static void Bar(int x) { } public static void Bar(string s) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0), new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0) }; Test(markup, expectedOrderedItems); } [WorkItem(768697)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void InstanceAndStaticMethodsShown4() { var markup = @" class C { void M() { Foo x; x.Bar($$ } } class Foo { public static void Bar(int x) { } public static void Bar(string s) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); Test(markup, expectedOrderedItems); } [WorkItem(768697)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void InstanceAndStaticMethodsShown5() { var markup = @" class C { void M() { Foo x; x.Bar($$ } } class x { } class Foo { public static void Bar(int x) { } public static void Bar(string s) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); Test(markup, expectedOrderedItems); } [WorkItem(1067933)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void InvokedWithNoToken() { var markup = @" // foo($$"; Test(markup); } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Archiver.Codecs { public class ExtendRecordingRequestDecoder { public const ushort BLOCK_LENGTH = 32; public const ushort TEMPLATE_ID = 11; public const ushort SCHEMA_ID = 101; public const ushort SCHEMA_VERSION = 6; private ExtendRecordingRequestDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public ExtendRecordingRequestDecoder() { _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 IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public ExtendRecordingRequestDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ControlSessionIdId() { return 1; } public static int ControlSessionIdSinceVersion() { return 0; } public static int ControlSessionIdEncodingOffset() { return 0; } public static int ControlSessionIdEncodingLength() { return 8; } public static string ControlSessionIdMetaAttribute(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 long ControlSessionIdNullValue() { return -9223372036854775808L; } public static long ControlSessionIdMinValue() { return -9223372036854775807L; } public static long ControlSessionIdMaxValue() { return 9223372036854775807L; } public long ControlSessionId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int CorrelationIdId() { return 2; } public static int CorrelationIdSinceVersion() { return 0; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static string CorrelationIdMetaAttribute(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 long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public long CorrelationId() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int RecordingIdId() { return 3; } public static int RecordingIdSinceVersion() { return 0; } public static int RecordingIdEncodingOffset() { return 16; } public static int RecordingIdEncodingLength() { return 8; } public static string RecordingIdMetaAttribute(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 long RecordingIdNullValue() { return -9223372036854775808L; } public static long RecordingIdMinValue() { return -9223372036854775807L; } public static long RecordingIdMaxValue() { return 9223372036854775807L; } public long RecordingId() { return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian); } public static int StreamIdId() { return 4; } public static int StreamIdSinceVersion() { return 0; } public static int StreamIdEncodingOffset() { return 24; } public static int StreamIdEncodingLength() { return 4; } public static string StreamIdMetaAttribute(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 StreamIdNullValue() { return -2147483648; } public static int StreamIdMinValue() { return -2147483647; } public static int StreamIdMaxValue() { return 2147483647; } public int StreamId() { return _buffer.GetInt(_offset + 24, ByteOrder.LittleEndian); } public static int SourceLocationId() { return 5; } public static int SourceLocationSinceVersion() { return 0; } public static int SourceLocationEncodingOffset() { return 28; } public static int SourceLocationEncodingLength() { return 4; } public static string SourceLocationMetaAttribute(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 SourceLocation SourceLocation() { return (SourceLocation)_buffer.GetInt(_offset + 28, ByteOrder.LittleEndian); } public static int ChannelId() { return 6; } public static int ChannelSinceVersion() { return 0; } public static string ChannelCharacterEncoding() { return "US-ASCII"; } public static string ChannelMetaAttribute(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 ChannelHeaderLength() { return 4; } public int ChannelLength() { int limit = _parentMessage.Limit(); return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); } public int GetChannel(IMutableDirectBuffer dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public int GetChannel(byte[] dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public string Channel() { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); _parentMessage.Limit(limit + headerLength + dataLength); byte[] tmp = new byte[dataLength]; _buffer.GetBytes(limit + headerLength, tmp, 0, dataLength); return Encoding.ASCII.GetString(tmp); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[ExtendRecordingRequest](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ControlSessionId="); builder.Append(ControlSessionId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("CorrelationId="); builder.Append(CorrelationId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='recordingId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("RecordingId="); builder.Append(RecordingId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='streamId', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("StreamId="); builder.Append(StreamId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='sourceLocation', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=28, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=BEGIN_ENUM, name='SourceLocation', referencedName='null', description='Source location for recorded stream.', id=-1, version=0, deprecated=0, encodedLength=4, offset=28, componentTokenCount=4, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}} builder.Append("SourceLocation="); builder.Append(SourceLocation()); builder.Append('|'); //Token{signal=BEGIN_VAR_DATA, name='channel', referencedName='null', description='null', id=6, version=0, deprecated=0, encodedLength=0, offset=32, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("Channel="); builder.Append(Channel()); Limit(originalLimit); return builder; } } }
// // FolderGallery.cs // // Author: // Lorenzo Milesi <maxxer@yetopen.it> // Stephane Delcroix <stephane@delcroix.org> // Stephen Shaw <sshaw@decriptor.com> // // Copyright (C) 2008-2009 Novell, Inc. // Copyright (C) 2008 Lorenzo Milesi // Copyright (C) 2008-2009 Stephane Delcroix // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // /* * Copyright (C) 2005 Alessandro Gervaso <gervystar@gervystar.net> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 */ //This should be used to export the selected pics to an original gallery //located on a GIO location. using System; using System.IO; using Hyena; using FSpot; using FSpot.Core; using FSpot.Database; using FSpot.Filters; using FSpot.Settings; using FSpot.Utils; namespace FSpot.Exporters.Folder { internal class FolderGallery { protected struct ScaleRequest { public string Name; public int Width; public int Height; public bool Skip; public bool CopyExif; public static ScaleRequest Default = new ScaleRequest (string.Empty, 0, 0, false); public ScaleRequest (string name, int width, int height, bool skip, bool exif = false) { this.Name = name != null ? name : string.Empty; this.Width = width; this.Height = height; this.Skip = skip; this.CopyExif = exif; } public bool AvoidScale (int size) { return (size < this.Width && size < this.Height && this.Skip); } } #region Variables protected bool scale; protected ScaleRequest[] requests; #endregion #region Constructor internal FolderGallery (IBrowsableCollection selection, string path, string gallery_name) { if (null == selection) throw new ArgumentNullException (nameof (selection)); if (0 == selection.Count) throw new ArgumentException ("selection can't be empty"); if (null == path) throw new ArgumentNullException (nameof (path)); if (null == gallery_name) throw new ArgumentNullException (nameof (gallery_name)); Collection = selection; GalleryName = gallery_name; GalleryPath = Path.Combine (path, GalleryName); this.requests = new ScaleRequest [] { ScaleRequest.Default }; } #endregion #region Properties public string GalleryName { get; protected set; } public string GalleryPath { get; protected set; } protected IBrowsableCollection Collection { get; set; } public string Description { get; set; } public Uri Destination { get; set; } protected int Size { get; set; } public bool ExportTags { get; set; } public bool ExportTagIcons { get; set; } string language = string.Empty; public string Language { get { if (language == null) { if ((language = Environment.GetEnvironmentVariable ("LC_ALL")) == null) if ((language = Environment.GetEnvironmentVariable ("LC_MESSAGES")) == null) if ((language = Environment.GetEnvironmentVariable ("LANG")) == null) language = "en"; if (language.IndexOf ('.') >= 0) language = language.Substring (0, language.IndexOf ('.')); if (language.IndexOf ('@') >= 0) language = language.Substring (0, language.IndexOf ('@')); language = language.Replace ('_', '-'); } return language; } } #endregion #region method public virtual void GenerateLayout () { MakeDir (GalleryPath); } protected virtual string ImageName (int image_num) { var uri = Collection [image_num].DefaultVersion.Uri; var dest_uri = new SafeUri (GalleryPath); // Find an unused name int i = 1; var dest = dest_uri.Append (uri.GetFilename ()); var file = new FileInfo (dest.AbsolutePath); while (file.Exists) { var filename = uri.GetFilenameWithoutExtension (); var extension = uri.GetExtension (); dest = dest_uri.Append ($"{filename}-{i++}{extension}"); file = new FileInfo (dest.AbsolutePath); } return dest.GetFilename (); } public void ProcessImage (int image_num, FilterSet filter_set) { IPhoto photo = Collection [image_num]; string path; ScaleRequest req; req = requests [0]; MakeDir (SubdirPath (req.Name)); path = SubdirPath (req.Name, ImageName (image_num)); using (FilterRequest request = new FilterRequest (photo.DefaultVersion.Uri)) { filter_set.Convert (request); if (request.Current.LocalPath == path) request.Preserve (request.Current); else System.IO.File.Copy (request.Current.LocalPath, path, true); if (photo != null && photo is Photo && App.Instance.Database != null) App.Instance.Database.Exports.Create ((photo as Photo).Id, (photo as Photo).DefaultVersionId, ExportStore.FolderExportType, // FIXME this is wrong, the final path is the one // after the Xfer. new SafeUri (path).ToString ()); for (int i = 1; i < requests.Length; i++) { req = requests [i]; if (scale && req.AvoidScale (Size)) continue; FilterSet req_set = new FilterSet (); req_set.Add (new ResizeFilter ((uint)Math.Max (req.Width, req.Height))); bool sharpen; try { sharpen = Preferences.Get<bool> (FolderExport.SHARPEN_KEY); } catch (NullReferenceException) { sharpen = true; Preferences.Set (FolderExport.SHARPEN_KEY, true); } if (sharpen) { if (req.Name == "lq") req_set.Add (new SharpFilter (0.1, 2, 4)); if (req.Name == "thumbs") req_set.Add (new SharpFilter (0.1, 2, 5)); } using (FilterRequest tmp_req = new FilterRequest (photo.DefaultVersion.Uri)) { req_set.Convert (tmp_req); MakeDir (SubdirPath (req.Name)); path = SubdirPath (req.Name, ImageName (image_num)); System.IO.File.Copy (tmp_req.Current.LocalPath, path, true); } } } } protected string MakeDir (string path) { try { Directory.CreateDirectory (path); } catch { Log.ErrorFormat ("Error in creating directory \"{0}\"", path); } return path; } protected string SubdirPath (string subdir, string file = null) { string path = Path.Combine (GalleryPath, subdir); if (file != null) path = Path.Combine (path, file); return path; } public void SetScale (int size) { this.scale = true; Size = size; requests [0].Width = size; requests [0].Height = size; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /* unboxing where a parameter is types as object and then is unboxed to its scalar type */ using System; using System.Reflection; using System.Runtime.CompilerServices; class X { public static int x_count = 1; public virtual void incCount() { x_count *= 2; } } class A : X { public static int a_count = 1; public override void incCount() { a_count *= 17; } } class B : X { public static int b_count = 1; public override void incCount() { b_count *= 19; } } class C : A { public static int c_count = 1; public override void incCount() { c_count *= 23; } } class D : B { public static int d_count = 1; public override void incCount() { d_count *= 31; } } sealed class CS : A { public static int cs_count = 1; public override void incCount() { cs_count *= 37; } } sealed class DS : B { public static int ds_count = 1; public override void incCount() { ds_count *= 41; } } class mainMethod { public static bool failed = false; public static void checkGetType(System.Object x) { if (x.GetType() == typeof(DS)) (new DS()).incCount(); if (x.GetType() == typeof(CS)) (new CS()).incCount(); if (x.GetType() == typeof(D)) (new D()).incCount(); if (x.GetType() == typeof(C)) (new C()).incCount(); if (x.GetType() == typeof(B)) (new B()).incCount(); if (x.GetType() == typeof(A)) (new A()).incCount(); if (x.GetType() == typeof(X)) (new X()).incCount(); if (x.GetType() == null) (new X()).incCount(); } public static void checkIs(System.Object x) { if (x is X) (new X()).incCount(); if (x is A) (new A()).incCount(); if (x is B) (new B()).incCount(); if (x is C) (new C()).incCount(); if (x is D) (new D()).incCount(); if (x is CS) (new CS()).incCount(); if (x is DS) (new DS()).incCount(); } public static void checkAs(System.Object x) { X x1 = x as X; if (x1 != null) (new X()).incCount(); A a = x as A; if (a != null) (new A()).incCount(); B b = x as B; if (b != null) (new B()).incCount(); C c = x as C; if (c != null) (new C()).incCount(); D d = x as D; if (d != null) (new D()).incCount(); CS cs = x as CS; if (cs != null) (new CS()).incCount(); DS ds = x as DS; if (ds != null) (new DS()).incCount(); } public static void checkGetTypeObjectCast(System.Object x) { if (x.GetType() == typeof(DS)) ((DS)x).incCount(); if (x.GetType() == typeof(CS)) ((CS)x).incCount(); if (x.GetType() == typeof(D)) ((D)x).incCount(); if (x.GetType() == typeof(C)) ((C)x).incCount(); if (x.GetType() == typeof(B)) ((B)x).incCount(); if (x.GetType() == typeof(A)) ((A)x).incCount(); if (x.GetType() == typeof(X)) ((X)x).incCount(); if (x.GetType() == null) ((X)x).incCount(); } public static void checkIsObjectCast(System.Object x) { if (x is X) ((X)x).incCount(); if (x is A) ((A)x).incCount(); if (x is B) ((B)x).incCount(); if (x is C) ((C)x).incCount(); if (x is D) ((D)x).incCount(); if (x is CS) ((CS)x).incCount(); if (x is DS) ((DS)x).incCount(); } public static void checkAsObjectCast(System.Object x) { X x2 = x as X; if (x2 != null) ((X)x).incCount(); A a = x as A; if (a != null) ((A)x).incCount(); B b = x as B; if (b != null) ((B)x).incCount(); C c = x as C; if (c != null) ((C)x).incCount(); D d = x as D; if (d != null) ((D)x).incCount(); CS cs = x as CS; if (cs != null) ((CS)x).incCount(); DS ds = x as DS; if (ds != null) ((DS)x).incCount(); } public static void checkCount(ref int actual, int expected, string message) { if (actual != expected) { Console.WriteLine("FAILED: {0}", message); failed = true; } actual = 1; } public static void checkAllCounts(ref int x_actual, int ds, int cs, int d, int c, int b, int a, int x, string dsm, string csm, string dm, string cm, string bm, string am, string xm) { /* printCount(ref DS.ds_count, ds, dsm); printCount(ref CS.cs_count, cs, csm); printCount(ref D.d_count, d, dm); printCount(ref C.c_count, c, cm); printCount(ref B.b_count, b, bm); printCount(ref A.a_count, a, am); printCount(ref x_actual, x, xm); */ checkCount(ref DS.ds_count, ds, dsm); checkCount(ref CS.cs_count, cs, csm); checkCount(ref D.d_count, d, dm); checkCount(ref C.c_count, c, cm); checkCount(ref B.b_count, b, bm); checkCount(ref A.a_count, a, am); checkCount(ref x_actual, x, xm); } public static void printCount(ref int actual, int expected, string message) { Console.Write("{0}, ", actual); actual = 1; } public static void callCheckGetType() { int i = 0; checkGetType(new System.Object()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); checkGetType(new X()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 2, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); checkGetType(new A()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 17, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); checkGetType(new B()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 19, 1, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); checkGetType(new C()); checkAllCounts(ref X.x_count, 1, 1, 1, 23, 1, 1, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); checkGetType(new D()); checkAllCounts(ref X.x_count, 1, 1, 31, 1, 1, 1, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); checkGetType(new CS()); checkAllCounts(ref X.x_count, 1, 37, 1, 1, 1, 1, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); checkGetType(new DS()); checkAllCounts(ref X.x_count, 41, 1, 1, 1, 1, 1, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); } public static void callCheckIs() { int i = 0; checkIs(new System.Object()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 1, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); checkIs(new X()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 2, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); checkIs(new A()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 17, 2, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); checkIs(new B()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 19, 1, 2, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); checkIs(new C()); checkAllCounts(ref X.x_count, 1, 1, 1, 23, 1, 17, 2, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); checkIs(new D()); checkAllCounts(ref X.x_count, 1, 1, 31, 1, 19, 1, 2, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); checkIs(new CS()); checkAllCounts(ref X.x_count, 1, 37, 1, 1, 1, 17, 2, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); checkIs(new DS()); checkAllCounts(ref X.x_count, 41, 1, 1, 1, 19, 1, 2, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); } public static void callCheckAs() { int i = 0; checkAs(new System.Object()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 1, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); checkAs(new X()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 2, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); checkAs(new A()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 17, 2, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); checkAs(new B()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 19, 1, 2, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); checkAs(new C()); checkAllCounts(ref X.x_count, 1, 1, 1, 23, 1, 17, 2, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); checkAs(new D()); checkAllCounts(ref X.x_count, 1, 1, 31, 1, 19, 1, 2, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); checkAs(new CS()); checkAllCounts(ref X.x_count, 1, 37, 1, 1, 1, 17, 2, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); checkAs(new DS()); checkAllCounts(ref X.x_count, 41, 1, 1, 1, 19, 1, 2, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); } public static void callCheckGetTypeObjectCast() { int i = 0; checkGetTypeObjectCast(new System.Object()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); checkGetTypeObjectCast(new X()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 2, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); checkGetTypeObjectCast(new A()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 17, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); checkGetTypeObjectCast(new B()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 19, 1, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); checkGetTypeObjectCast(new C()); checkAllCounts(ref X.x_count, 1, 1, 1, 23, 1, 1, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); checkGetTypeObjectCast(new D()); checkAllCounts(ref X.x_count, 1, 1, 31, 1, 1, 1, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); checkGetTypeObjectCast(new CS()); checkAllCounts(ref X.x_count, 1, 37, 1, 1, 1, 1, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); checkGetTypeObjectCast(new DS()); checkAllCounts(ref X.x_count, 41, 1, 1, 1, 1, 1, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); } public static void callCheckIsObjectCast() { int i = 0; checkIsObjectCast(new System.Object()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); checkIsObjectCast(new X()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 2, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); checkIsObjectCast(new A()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 289, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); checkIsObjectCast(new B()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 361, 1, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); checkIsObjectCast(new C()); checkAllCounts(ref X.x_count, 1, 1, 1, 12167, 1, 1, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); checkIsObjectCast(new D()); checkAllCounts(ref X.x_count, 1, 1, 29791, 1, 1, 1, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); checkIsObjectCast(new CS()); checkAllCounts(ref X.x_count, 1, 50653, 1, 1, 1, 1, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); checkIsObjectCast(new DS()); checkAllCounts(ref X.x_count, 68921, 1, 1, 1, 1, 1, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); } public static void callCheckAsObjectCast() { int i = 0; checkAsObjectCast(new System.Object()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 1, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); checkAsObjectCast(new X()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 2, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); checkAsObjectCast(new A()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 289, 1, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); checkAsObjectCast(new B()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 361, 1, 1, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); checkAsObjectCast(new C()); checkAllCounts(ref X.x_count, 1, 1, 1, 12167, 1, 1, 1, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); checkAsObjectCast(new D()); checkAllCounts(ref X.x_count, 1, 1, 29791, 1, 1, 1, 1, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); checkAsObjectCast(new CS()); checkAllCounts(ref X.x_count, 1, 50653, 1, 1, 1, 1, 1, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); checkAsObjectCast(new DS()); checkAllCounts(ref X.x_count, 68921, 1, 1, 1, 1, 1, 1, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); } public static int Main() { callCheckGetType(); callCheckIs(); callCheckAs(); callCheckGetTypeObjectCast(); callCheckIsObjectCast(); callCheckAsObjectCast(); if (failed) return 101; else return 100; } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Collections.ObjectModel { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; [Serializable] ////[DebuggerTypeProxy( typeof( Mscorlib_CollectionDebugView<> ) )] ////[DebuggerDisplay( "Count = {Count}" )] public class Collection<T> : IList<T>, IList { IList<T> m_items; [NonSerialized] private Object m_syncRoot; public Collection() { m_items = new List<T>(); } public Collection( IList<T> list ) { if(list == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.list ); } m_items = list; } public int Count { get { return m_items.Count; } } protected IList<T> Items { get { return m_items; } } public T this[int index] { get { return m_items[index]; } set { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } if(index < 0 || index >= m_items.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(); } SetItem( index, value ); } } public void Add( T item ) { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } int index = m_items.Count; InsertItem( index, item ); } public void Clear() { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } ClearItems(); } public void CopyTo( T[] array, int index ) { m_items.CopyTo( array, index ); } public bool Contains( T item ) { return m_items.Contains( item ); } public IEnumerator<T> GetEnumerator() { return m_items.GetEnumerator(); } public int IndexOf( T item ) { return m_items.IndexOf( item ); } public void Insert( int index, T item ) { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } if(index < 0 || index > m_items.Count) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert ); } InsertItem( index, item ); } public bool Remove( T item ) { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } int index = m_items.IndexOf( item ); if(index < 0) { return false; } RemoveItem( index ); return true; } public void RemoveAt( int index ) { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } if(index < 0 || index >= m_items.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(); } RemoveItem( index ); } protected virtual void ClearItems() { m_items.Clear(); } protected virtual void InsertItem( int index, T item ) { m_items.Insert( index, item ); } protected virtual void RemoveItem( int index ) { m_items.RemoveAt( index ); } protected virtual void SetItem( int index, T item ) { m_items[index] = item; } bool ICollection<T>.IsReadOnly { get { return m_items.IsReadOnly; } } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)m_items).GetEnumerator(); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if(m_syncRoot == null) { ICollection c = m_items as ICollection; if(c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange( ref m_syncRoot, new Object(), null ); } } return m_syncRoot; } } void ICollection.CopyTo( Array array, int index ) { if(array == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.array ); } if(array.Rank != 1) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_RankMultiDimNotSupported ); } if(array.GetLowerBound( 0 ) != 0) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_NonZeroLowerBound ); } if(index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(array.Length - index < Count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } T[] tArray = array as T[]; if(tArray != null) { m_items.CopyTo( tArray, index ); } else { // // Catch the obvious case assignment will fail. // We can found all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType(); Type sourceType = typeof( T ); if(!(targetType.IsAssignableFrom( sourceType ) || sourceType.IsAssignableFrom( targetType ))) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // object[] objects = array as object[]; if(objects == null) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } int count = m_items.Count; try { for(int i = 0; i < count; i++) { objects[index++] = m_items[i]; } } catch(ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } } } object IList.this[int index] { get { return m_items[index]; } set { ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>( value, ExceptionArgument.value ); try { this[index] = (T)value; } catch(InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException( value, typeof( T ) ); } } } bool IList.IsReadOnly { get { return m_items.IsReadOnly; } } bool IList.IsFixedSize { get { // There is no IList<T>.IsFixedSize, so we must assume that only // readonly collections are fixed size, if our internal item // collection does not implement IList. Note that Array implements // IList, and therefore T[] and U[] will be fixed-size. IList list = m_items as IList; if(list != null) { return list.IsFixedSize; } return m_items.IsReadOnly; } } int IList.Add( object value ) { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>( value, ExceptionArgument.value ); try { Add( (T)value ); } catch(InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException( value, typeof( T ) ); } return this.Count - 1; } bool IList.Contains( object value ) { if(IsCompatibleObject( value )) { return Contains( (T)value ); } return false; } int IList.IndexOf( object value ) { if(IsCompatibleObject( value )) { return IndexOf( (T)value ); } return -1; } void IList.Insert( int index, object value ) { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>( value, ExceptionArgument.value ); try { Insert( index, (T)value ); } catch(InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException( value, typeof( T ) ); } } void IList.Remove( object value ) { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } if(IsCompatibleObject( value )) { Remove( (T)value ); } } private static bool IsCompatibleObject( object value ) { // Non-null values are fine. Only accept nulls if T is a class or Nullable<U>. // Note that default(T) is not equal to null for value types except when T is Nullable<U>. return ((value is T) || (value == null && default( T ) == null)); } } }
using System; using System.Collections.Generic; using System.Reflection; using Orleans.CodeGeneration; using Orleans.Utilities; namespace Orleans { /// <summary> /// Maintains a map between grain classes and corresponding interface-implementation mappings. /// </summary> internal class InterfaceToImplementationMappingCache { public struct Entry { public Entry(MethodInfo implementationMethod, MethodInfo interfaceMethod) { ImplementationMethod = implementationMethod; InterfaceMethod = interfaceMethod; } public MethodInfo ImplementationMethod { get; } public MethodInfo InterfaceMethod { get; } } /// <summary> /// The map from implementation types to interface types to map of method ids to method infos. /// </summary> private readonly CachedReadConcurrentDictionary<Type, Dictionary<Type, Dictionary<int, Entry>>> mappings = new CachedReadConcurrentDictionary<Type, Dictionary<Type, Dictionary<int, Entry>>>(); /// <summary> /// Returns a mapping from method id to method info for the provided implementation and interface types. /// </summary> /// <param name="implementationType">The implementation type.</param> /// <param name="interfaceType">The interface type.</param> /// <returns> /// A mapping from method id to method info. /// </returns> public Dictionary<int, Entry> GetOrCreate(Type implementationType, Type interfaceType) { // Get or create the mapping between interfaceId and invoker for the provided type. if (!this.mappings.TryGetValue(implementationType, out var invokerMap)) { // Generate an the invoker mapping using the provided invoker. this.mappings[implementationType] = invokerMap = CreateInterfaceToImplementationMap(implementationType); } // Attempt to get the invoker for the provided interfaceId. if (!invokerMap.TryGetValue(interfaceType, out var interfaceToImplementationMap)) { throw new InvalidOperationException($"Type {implementationType} does not implement interface {interfaceType}"); } return interfaceToImplementationMap; } /// <summary> /// Maps the interfaces of the provided <paramref name="implementationType"/>. /// </summary> /// <param name="implementationType">The implementation type.</param> /// <returns>The mapped interface.</returns> private static Dictionary<Type, Dictionary<int, Entry>> CreateInterfaceToImplementationMap(Type implementationType) { var name = implementationType.Name; if (implementationType.IsConstructedGenericType) return CreateMapForConstructedGeneric(implementationType); return CreateMapForNonGeneric(implementationType); } /// <summary> /// Creates and returns a map from interface type to map of method id to method info for the provided non-generic type. /// </summary> /// <param name="implementationType">The implementation type.</param> /// <returns>A map from interface type to map of method id to method info for the provided type.</returns> private static Dictionary<Type, Dictionary<int, Entry>> CreateMapForNonGeneric(Type implementationType) { if (implementationType.IsConstructedGenericType) { throw new InvalidOperationException( $"Type {implementationType} passed to {nameof(CreateMapForNonGeneric)} is a constructed generic type."); } var concreteInterfaces = implementationType.GetInterfaces(); var interfaces = new List<(Type Concrete, Type Generic)>(concreteInterfaces.Length); foreach (var iface in concreteInterfaces) { if (iface.IsConstructedGenericType) { interfaces.Add((iface, iface.GetGenericTypeDefinition())); } else { interfaces.Add((iface, null)); } } // Create an invoker for every interface on the provided type. var result = new Dictionary<Type, Dictionary<int, Entry>>(interfaces.Count); var implementationTypeInfo = implementationType.GetTypeInfo(); foreach (var (iface, genericIface) in interfaces) { var methods = GrainInterfaceUtils.GetMethods(iface); var genericIfaceMethods = genericIface is object ? GrainInterfaceUtils.GetMethods(genericIface) : null; // Map every method on this interface from the definition interface onto the implementation class. var methodMap = new Dictionary<int, Entry>(methods.Length); var genericInterfaceMethodMap = genericIface is object ? new Dictionary<int, Entry>(genericIfaceMethods.Length) : null; var mapping = default(InterfaceMapping); for (var i = 0; i < methods.Length; i++) { var method = methods[i]; // If this method is not from the expected interface (eg, because it's from a parent interface), then // get the mapping for the interface which it does belong to. if (mapping.InterfaceType != method.DeclaringType) { mapping = implementationTypeInfo.GetRuntimeInterfaceMap(method.DeclaringType); } // Find the index of the interface method and then get the implementation method at that position. for (var k = 0; k < mapping.InterfaceMethods.Length; k++) { if (mapping.InterfaceMethods[k] != method) continue; methodMap[GrainInterfaceUtils.ComputeMethodId(method)] = new Entry(mapping.TargetMethods[k], method); if (genericIface is object) { var id = GrainInterfaceUtils.ComputeMethodId(genericIfaceMethods[i]); genericInterfaceMethodMap[id] = new Entry(mapping.TargetMethods[k], genericIfaceMethods[i]); methodMap[id] = new Entry(mapping.TargetMethods[k], method); } break; } } // Add the resulting map of methodId -> method to the interface map. result[iface] = methodMap; if (genericIface is object) { result[genericIface] = genericInterfaceMethodMap; } } return result; } /// <summary> /// Creates and returns a map from interface type to map of method id to method info for the provided constructed generic type. /// </summary> /// <param name="implementationType">The implementation type.</param> /// <returns>A map from interface type to map of method id to method info for the provided type.</returns> private static Dictionary<Type, Dictionary<int, Entry>> CreateMapForConstructedGeneric(Type implementationType) { // It is important to note that the interfaceId and methodId are computed based upon the non-concrete // version of the implementation type. During code generation, the concrete type would not be available // and therefore the generic type definition is used. if (!implementationType.IsConstructedGenericType) { throw new InvalidOperationException( $"Type {implementationType} passed to {nameof(CreateMapForConstructedGeneric)} is not a constructed generic type"); } var genericClass = implementationType.GetGenericTypeDefinition(); var genericInterfaces = genericClass.GetInterfaces(); var concreteInterfaces = implementationType.GetInterfaces(); // Create an invoker for every interface on the provided type. var result = new Dictionary<Type, Dictionary<int, Entry>>(genericInterfaces.Length); for (var i = 0; i < genericInterfaces.Length; i++) { // Because these methods are identical except for type parameters, their methods should also be identical except // for type parameters, including identical ordering. That is the assumption. var genericMethods = GrainInterfaceUtils.GetMethods(genericInterfaces[i]); var concreteInterfaceMethods = GrainInterfaceUtils.GetMethods(concreteInterfaces[i]); // Map every method on this interface from the definition interface onto the implementation class. var methodMap = new Dictionary<int, Entry>(genericMethods.Length); var genericMap = default(InterfaceMapping); var concreteMap = default(InterfaceMapping); for (var j = 0; j < genericMethods.Length; j++) { // If this method is not from the expected interface (eg, because it's from a parent interface), then // get the mapping for the interface which it does belong to. var genericInterfaceMethod = genericMethods[j]; if (genericMap.InterfaceType != genericInterfaceMethod.DeclaringType) { genericMap = genericClass.GetTypeInfo().GetRuntimeInterfaceMap(genericInterfaceMethod.DeclaringType); concreteMap = implementationType.GetTypeInfo().GetRuntimeInterfaceMap(concreteInterfaceMethods[j].DeclaringType); } // Determine the position in the definition's map which the target method belongs to and take the implementation // from the same position on the implementation's map. for (var k = 0; k < genericMap.InterfaceMethods.Length; k++) { if (genericMap.InterfaceMethods[k] != genericInterfaceMethod) continue; methodMap[GrainInterfaceUtils.ComputeMethodId(genericInterfaceMethod)] = new Entry(concreteMap.TargetMethods[k], concreteMap.InterfaceMethods[k]); break; } } // Add the resulting map of methodId -> method to the interface map. result[concreteInterfaces[i]] = methodMap; } return result; } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Globalization; namespace WebApplication2 { /// <summary> /// Summary description for frmAddProcedure. /// </summary> public partial class frmUpdInventory : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; public SqlConnection epsDbConn=new SqlConnection(strDB); private String Id; private int GetIndexOfStatus (string s) { return (rblStatus.Items.IndexOf(rblStatus.Items.FindByValue(s))); } private int GetIndexOflstResourceTypes (string s) { return (lstResourceTypes.Items.IndexOf (lstResourceTypes.Items.FindByValue(s))); } private int GetIndexOfLocs (string s) { return (lstLocations.Items.IndexOf (lstLocations.Items.FindByValue(s))); } private int GetIndexOfVisibility(string s) { return (lstVisibility.Items.IndexOf(lstVisibility.Items.FindByValue(s))); } int ResTypeFlag = 0; protected void Page_Load(object sender, System.EventArgs e) { Id=Request.Params["Id"]; if (!IsPostBack) { lblOrg.Text=(Session["OrgName"]).ToString(); lblAction.Text = Request.Params["btnAction"] + " Inventory"; loadResTypes(); loadLocs(); loadVisibility(); loadStatus(); /*rblStatus.BorderColor=System.Drawing.Color.Navy; rblStatus.ForeColor=System.Drawing.Color.Navy; lstLocations.BorderColor=System.Drawing.Color.Navy; lstLocations.ForeColor=System.Drawing.Color.Navy;*/ if (Session["CallerUpdInv"].ToString() == "frmInventory") { //lblContent1.Text="Add Inventory Item of type: " + Session["ResTypeName"].ToString(); } else { } btnAction.Text= Request.Params["btnAction"]; if (Request.Params["btnAction"] == "Update") { loadData(); } else { rblStatus.SelectedIndex = GetIndexOfStatus("1"); } } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion private void loadData() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_RetrieveInventory"; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=Request.Params["Id"]; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"InventoryT"); txtDesc.Text=ds.Tables["InventoryT"].Rows[0][2].ToString(); txtSubLoc.Text = ds.Tables["InventoryT"].Rows[0][9].ToString(); lstLocations.SelectedIndex= GetIndexOfLocs(ds.Tables["InventoryT"].Rows[0][3].ToString()); rblStatus.SelectedIndex = GetIndexOfStatus(ds.Tables["InventoryT"].Rows[0][5].ToString()); if (ResTypeFlag == 0) { lstResourceTypes.SelectedIndex = GetIndexOflstResourceTypes(ds.Tables["InventoryT"].Rows[0][4].ToString()); } lblQty.Text = "Quantity (In " + ds.Tables["InventoryT"].Rows[0][8].ToString() + ")"; txtQty.Text = ds.Tables["InventoryT"].Rows[0][10].ToString(); lstVisibility.SelectedIndex= GetIndexOfVisibility(ds.Tables["InventoryT"].Rows[0][6].ToString()); } private void loadVisibility() { SqlCommand cmd = new SqlCommand(); cmd.Connection = this.epsDbConn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "ams_RetrieveVisibility"; cmd.Parameters.Add("@Vis", SqlDbType.Int); cmd.Parameters["@Vis"].Value = Session["OrgVis"].ToString(); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "Visibility"); lstVisibility.DataSource = ds; lstVisibility.DataMember = "Visibility"; lstVisibility.DataTextField = "Name"; lstVisibility.DataValueField = "Id"; lstVisibility.DataBind(); } private void loadResTypes() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_RetrieveResourceTypes"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"ResourceTypes"); lstResourceTypes.DataSource = ds; lstResourceTypes.DataMember= "ResourceTypes"; lstResourceTypes.DataTextField = "Name"; lstResourceTypes.DataValueField = "Id"; lstResourceTypes.DataBind(); } private void loadLocs() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_RetrieveLocations"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Locations"); lstLocations.DataSource = ds; lstLocations.DataMember= "Locations"; lstLocations.DataTextField = "Name"; lstLocations.DataValueField = "Id"; lstLocations.DataBind(); } private void loadStatus() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_RetrieveInventoryStatus"; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"InventoryStatus"); rblStatus.DataSource = ds; rblStatus.DataMember= "InventoryStatus"; rblStatus.DataTextField = "Name"; rblStatus.DataValueField = "Id"; rblStatus.DataBind(); } protected void btnAction_Click(object sender, System.EventArgs e) { if (btnAction.Text == "Update") { SqlCommand cmd = new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_UpdateInventory"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=Int32.Parse(Id); cmd.Parameters.Add("@SubLoc", SqlDbType.NVarChar); cmd.Parameters["@SubLoc"].Value = txtSubLoc.Text; cmd.Parameters.Add("@Desc", SqlDbType.NVarChar); cmd.Parameters["@Desc"].Value = txtDesc.Text; if (txtQty.Text != "") { cmd.Parameters.Add("@Qty", SqlDbType.Float); cmd.Parameters["@Qty"].Value = float.Parse(txtQty.Text, NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign); } cmd.Parameters.Add ("@StatusId",SqlDbType.Int); cmd.Parameters["@StatusId"].Value=rblStatus.SelectedItem.Value; cmd.Parameters.Add("@ResTypeId", SqlDbType.Int); if (Session["CallerUpdInv"].ToString() == "frmInventory") { cmd.Parameters["@ResTypeId"].Value = lstResourceTypes.SelectedItem.Value; } cmd.Parameters.Add("@VisId", SqlDbType.Int); cmd.Parameters["@VisId"].Value = lstVisibility.SelectedItem.Value; cmd.Parameters.Add("@LocId", SqlDbType.Int); cmd.Parameters["@LocId"].Value = lstLocations.SelectedItem.Value; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); Done(); } else if (btnAction.Text == "Add") { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_AddInventory"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add("@SubLoc", SqlDbType.NVarChar); cmd.Parameters["@SubLoc"].Value = txtSubLoc.Text; cmd.Parameters.Add ("@Desc",SqlDbType.NVarChar); cmd.Parameters["@Desc"].Value= txtDesc.Text; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"]; if (txtQty.Text != "") { cmd.Parameters.Add("@Qty", SqlDbType.Float); cmd.Parameters["@Qty"].Value = float.Parse(txtQty.Text, NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign); } cmd.Parameters.Add("@LocId", SqlDbType.Int); cmd.Parameters["@LocId"].Value=lstLocations.SelectedItem.Value; cmd.Parameters.Add ("@StatusId",SqlDbType.Int); cmd.Parameters["@StatusId"].Value=rblStatus.SelectedItem.Value; cmd.Parameters.Add ("@ResTypeId",SqlDbType.Int); if (Session["CallerUpdInv"].ToString() == "frmInventory") { cmd.Parameters["@ResTypeId"].Value = lstResourceTypes.SelectedItem.Value; ; } else { //cmd.Parameters["@ResTypeId"].Value=lstResourceTypes.SelectedItem.Value; } cmd.Parameters.Add("@VisId", SqlDbType.Int); cmd.Parameters["@VisId"].Value = lstVisibility.SelectedItem.Value; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); Done(); } } private void Done() { Response.Redirect (strURL + Session["CallerUpdInv"].ToString() + ".aspx?"); } protected void btnCancel_Click(object sender, System.EventArgs e) { Done(); } /*private void btnAddLoc_Click(object sender, System.EventArgs e) { Session["CUpdLocs"]="frmUpdInventory"; Response.Redirect (strURL + "frmUpdLoc.aspx?" + "&btnAction=" + "Add"); }*/ protected void lstResourceTypes_SelectedIndexChanged(object sender, EventArgs e) { Session["Desc"] = txtDesc.Text; ResTypeFlag = 1; if (Request.Params["btnAction"] == "Update") { loadData(); } txtDesc.Text = Session["Desc"].ToString(); Session["Desc"] = null; ResTypeFlag = 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Text; // Name of namespace matches the name of the assembly on purpose to // ensure that we can handle this (mostly an issue for C++ code generation). namespace PInvokeTests { internal class Program { [DllImport("*", CallingConvention = CallingConvention.StdCall)] private static extern int Square(int intValue); [DllImport("*", CallingConvention = CallingConvention.StdCall)] private static extern int IsTrue(bool boolValue); [DllImport("*", CallingConvention = CallingConvention.StdCall)] private static extern int CheckIncremental(int[] array, int sz); [DllImport("*", CallingConvention = CallingConvention.StdCall)] private static extern int CheckIncremental_Foo(Foo[] array, int sz); [DllImport("*", CallingConvention = CallingConvention.StdCall)] private static extern int Inc(ref int value); [DllImport("*", CallingConvention = CallingConvention.StdCall)] private static extern int VerifyByRefFoo(ref Foo value); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] private static extern bool GetNextChar(ref char c); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] private static extern int VerifyAnsiString(string str); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] private static extern int VerifyAnsiStringOut(out string str); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] private static extern int VerifyAnsiStringRef(ref string str); [DllImport("*", EntryPoint = "VerifyAnsiStringRef", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] private static extern int VerifyAnsiStringInRef([In]ref string str); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] private static extern int VerifyUnicodeString(string str); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] private static extern int VerifyUnicodeStringOut(out string str); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] private static extern int VerifyUnicodeStringRef(ref string str); [DllImport("*", EntryPoint = "VerifyUnicodeStringRef", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] private static extern int VerifyUnicodeStringInRef([In]ref string str); [DllImport("*", CharSet = CharSet.Ansi)] private static extern int VerifyAnsiStringArray([In, MarshalAs(UnmanagedType.LPArray)]string[] str); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] private static extern bool VerifyAnsiCharArrayIn(char[] a); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] private static extern bool VerifyAnsiCharArrayOut([Out]char[] a); [DllImport("*", CharSet = CharSet.Ansi)] private static extern void ToUpper([In, Out, MarshalAs(UnmanagedType.LPArray)]string[] str); [DllImport("*", CharSet = CharSet.Ansi)] private static extern bool VerifySizeParamIndex( [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out byte[] arrByte, out byte arrSize); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, EntryPoint = "VerifyUnicodeStringBuilder")] private static extern int VerifyUnicodeStringBuilder(StringBuilder sb); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, EntryPoint = "VerifyUnicodeStringBuilder")] private static extern int VerifyUnicodeStringBuilderIn([In]StringBuilder sb); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] private static extern int VerifyUnicodeStringBuilderOut([Out]StringBuilder sb); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, EntryPoint = "VerifyAnsiStringBuilder")] private static extern int VerifyAnsiStringBuilder(StringBuilder sb); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, EntryPoint = "VerifyAnsiStringBuilder")] private static extern int VerifyAnsiStringBuilderIn([In]StringBuilder sb); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] private static extern int VerifyAnsiStringBuilderOut([Out]StringBuilder sb); [DllImport("*", CallingConvention = CallingConvention.StdCall)] public static extern bool SafeHandleTest(SafeMemoryHandle sh1, Int64 sh1Value); [DllImport("*", CallingConvention = CallingConvention.StdCall)] public static extern int SafeHandleOutTest(out SafeMemoryHandle sh1); [DllImport("*", CallingConvention = CallingConvention.StdCall, SetLastError = true)] public static extern bool LastErrorTest(); delegate int Delegate_Int(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j); [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern bool ReversePInvoke_Int(Delegate_Int del); [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet=CharSet.Ansi)] delegate bool Delegate_String(string s); [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern bool ReversePInvoke_String(Delegate_String del); [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern Delegate_String GetDelegate(); [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern bool Callback(ref Delegate_String d); delegate void Delegate_Unused(); [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern unsafe int* ReversePInvoke_Unused(Delegate_Unused del); [DllImport("*", CallingConvention = CallingConvention.StdCall, EntryPoint = "StructTest")] static extern bool StructTest_Auto(AutoStruct ss); [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern bool StructTest_Sequential2(NesterOfSequentialStruct.SequentialStruct ss); [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern bool StructTest(SequentialStruct ss); [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern void StructTest_ByRef(ref SequentialStruct ss); [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern void StructTest_ByOut(out SequentialStruct ss); [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern bool StructTest_Explicit(ExplicitStruct es); [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern bool StructTest_Nested(NestedStruct ns); [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern bool StructTest_Array(SequentialStruct []ns, int length); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] static extern bool IsNULL(char[] a); [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] static extern bool IsNULL(String sb); [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern bool IsNULL(Foo[] foo); [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern bool IsNULL(SequentialStruct[] foo); [StructLayout(LayoutKind.Sequential, CharSet= CharSet.Ansi, Pack = 4)] public unsafe struct InlineArrayStruct { public int f0; public int f1; public int f2; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)] public short[] inlineArray; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 11)] public string inlineString; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 4)] public unsafe struct InlineUnicodeStruct { public int f0; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 11)] public string inlineString; } [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern bool InlineArrayTest(ref InlineArrayStruct ias, ref InlineUnicodeStruct ius); [UnmanagedFunctionPointer(CallingConvention.Cdecl, SetLastError = true)] public unsafe delegate void SetLastErrorFuncDelegate(int errorCode); [DllImport("*", CallingConvention = CallingConvention.StdCall)] internal static extern IntPtr GetFunctionPointer(); public static int Main(string[] args) { TestBlittableType(); TestBoolean(); TestUnichar(); TestArrays(); TestByRef(); TestString(); TestStringBuilder(); TestLastError(); TestSafeHandle(); TestStringArray(); TestSizeParamIndex(); #if !CODEGEN_CPP TestDelegate(); #endif TestStruct(); return 100; } public static void ThrowIfNotEquals<T>(T expected, T actual, string message) { if (!expected.Equals(actual)) { message += "\nExpected: " + expected.ToString() + "\n"; message += "Actual: " + actual.ToString() + "\n"; throw new Exception(message); } } public static void ThrowIfNotEquals(bool expected, bool actual, string message) { ThrowIfNotEquals(expected ? 1 : 0, actual ? 1 : 0, message); } private static void TestBlittableType() { Console.WriteLine("Testing marshalling blittable types"); ThrowIfNotEquals(100, Square(10), "Int marshalling failed"); } private static void TestBoolean() { Console.WriteLine("Testing marshalling boolean"); ThrowIfNotEquals(1, IsTrue(true), "Bool marshalling failed"); ThrowIfNotEquals(0, IsTrue(false), "Bool marshalling failed"); } private static void TestUnichar() { Console.WriteLine("Testing Unichar"); char c = 'a'; ThrowIfNotEquals(true, GetNextChar(ref c), "Unichar marshalling failed."); ThrowIfNotEquals('b', c, "Unichar marshalling failed."); } struct Foo { public int a; public float b; } private static void TestArrays() { Console.WriteLine("Testing marshalling int arrays"); const int ArraySize = 100; int[] arr = new int[ArraySize]; for (int i = 0; i < ArraySize; i++) arr[i] = i; ThrowIfNotEquals(0, CheckIncremental(arr, ArraySize), "Array marshalling failed"); Console.WriteLine("Testing marshalling blittable struct arrays"); Foo[] arr_foo = null; ThrowIfNotEquals(true, IsNULL(arr_foo), "Blittable array null check failed"); arr_foo = new Foo[ArraySize]; for (int i = 0; i < ArraySize; i++) { arr_foo[i].a = i; arr_foo[i].b = i; } ThrowIfNotEquals(0, CheckIncremental_Foo(arr_foo, ArraySize), "Array marshalling failed"); char[] a = "Hello World".ToCharArray(); ThrowIfNotEquals(true, VerifyAnsiCharArrayIn(a), "Ansi Char Array In failed"); char[] b = new char[12]; ThrowIfNotEquals(true, VerifyAnsiCharArrayOut(b), "Ansi Char Array Out failed"); ThrowIfNotEquals("Hello World!", new String(b), "Ansi Char Array Out failed2"); char[] c = null; ThrowIfNotEquals(true, IsNULL(c), "AnsiChar Array null check failed"); } private static void TestByRef() { Console.WriteLine("Testing marshalling by ref"); int value = 100; ThrowIfNotEquals(0, Inc(ref value), "By ref marshalling failed"); ThrowIfNotEquals(101, value, "By ref marshalling failed"); Foo foo = new Foo(); foo.a = 10; foo.b = 20; int ret = VerifyByRefFoo(ref foo); ThrowIfNotEquals(0, ret, "By ref struct marshalling failed"); ThrowIfNotEquals(foo.a, 11, "By ref struct unmarshalling failed"); ThrowIfNotEquals(foo.b, 21.0f, "By ref struct unmarshalling failed"); } private static void TestString() { Console.WriteLine("Testing marshalling string"); ThrowIfNotEquals(1, VerifyAnsiString("Hello World"), "Ansi String marshalling failed."); ThrowIfNotEquals(1, VerifyUnicodeString("Hello World"), "Unicode String marshalling failed."); string s; ThrowIfNotEquals(1, VerifyAnsiStringOut(out s), "Out Ansi String marshalling failed"); ThrowIfNotEquals("Hello World", s, "Out Ansi String marshalling failed"); VerifyAnsiStringInRef(ref s); ThrowIfNotEquals("Hello World", s, "In Ref ansi String marshalling failed"); VerifyAnsiStringRef(ref s); ThrowIfNotEquals("Hello World!", s, "Ref ansi String marshalling failed"); ThrowIfNotEquals(1, VerifyUnicodeStringOut(out s), "Out Unicode String marshalling failed"); ThrowIfNotEquals("Hello World", s, "Out Unicode String marshalling failed"); VerifyUnicodeStringInRef(ref s); ThrowIfNotEquals("Hello World", s, "In Ref Unicode String marshalling failed"); VerifyUnicodeStringRef(ref s); ThrowIfNotEquals("Hello World!", s, "Ref Unicode String marshalling failed"); string ss = null; ThrowIfNotEquals(true, IsNULL(ss), "Ansi String null check failed"); } private static void TestStringBuilder() { Console.WriteLine("Testing marshalling string builder"); StringBuilder sb = new StringBuilder("Hello World"); ThrowIfNotEquals(1, VerifyUnicodeStringBuilder(sb), "Unicode StringBuilder marshalling failed"); ThrowIfNotEquals("HELLO WORLD", sb.ToString(), "Unicode StringBuilder marshalling failed."); StringBuilder sb1 = null; // for null stringbuilder it should return -1 ThrowIfNotEquals(-1, VerifyUnicodeStringBuilder(sb1), "Null unicode StringBuilder marshalling failed"); StringBuilder sb2 = new StringBuilder("Hello World"); ThrowIfNotEquals(1, VerifyUnicodeStringBuilderIn(sb2), "In unicode StringBuilder marshalling failed"); // Only [In] should change stringbuilder value ThrowIfNotEquals("Hello World", sb2.ToString(), "In unicode StringBuilder marshalling failed"); StringBuilder sb3 = new StringBuilder(); ThrowIfNotEquals(1, VerifyUnicodeStringBuilderOut(sb3), "Out Unicode string marshalling failed"); ThrowIfNotEquals("Hello World", sb3.ToString(), "Out Unicode StringBuilder marshalling failed"); StringBuilder sb4 = new StringBuilder("Hello World"); ThrowIfNotEquals(1, VerifyAnsiStringBuilder(sb4), "Ansi StringBuilder marshalling failed"); ThrowIfNotEquals("HELLO WORLD", sb4.ToString(), "Ansi StringBuilder marshalling failed."); StringBuilder sb5 = null; // for null stringbuilder it should return -1 ThrowIfNotEquals(-1, VerifyAnsiStringBuilder(sb5), "Null Ansi StringBuilder marshalling failed"); StringBuilder sb6 = new StringBuilder("Hello World"); ThrowIfNotEquals(1, VerifyAnsiStringBuilderIn(sb6), "In unicode StringBuilder marshalling failed"); // Only [In] should change stringbuilder value ThrowIfNotEquals("Hello World", sb6.ToString(), "In unicode StringBuilder marshalling failed"); StringBuilder sb7 = new StringBuilder(); ThrowIfNotEquals(1, VerifyAnsiStringBuilderOut(sb7), "Out Ansi string marshalling failed"); ThrowIfNotEquals("Hello World!", sb7.ToString(), "Out Ansi StringBuilder marshalling failed"); } private static void TestStringArray() { Console.WriteLine("Testing marshalling string array"); string[] strArray = new string[] { "Hello", "World" }; ThrowIfNotEquals(1, VerifyAnsiStringArray(strArray), "Ansi string array in marshalling failed."); ToUpper(strArray); ThrowIfNotEquals(true, "HELLO" == strArray[0] && "WORLD" == strArray[1], "Ansi string array out marshalling failed."); } private static void TestLastError() { Console.WriteLine("Testing last error"); ThrowIfNotEquals(true, LastErrorTest(), "GetLastWin32Error is not zero"); ThrowIfNotEquals(12345, Marshal.GetLastWin32Error(), "Last Error test failed"); } private static void TestSafeHandle() { Console.WriteLine("Testing marshalling SafeHandle"); SafeMemoryHandle hnd = SafeMemoryHandle.AllocateMemory(1000); IntPtr hndIntPtr = hnd.DangerousGetHandle(); //get the IntPtr associated with hnd long val = hndIntPtr.ToInt64(); //return the 64-bit value associated with hnd ThrowIfNotEquals(true, SafeHandleTest(hnd, val), "SafeHandle marshalling failed."); Console.WriteLine("Testing marshalling out SafeHandle"); SafeMemoryHandle hnd2; int actual = SafeHandleOutTest(out hnd2); int expected = unchecked((int)hnd2.DangerousGetHandle().ToInt64()); ThrowIfNotEquals(actual, expected, "SafeHandle out marshalling failed"); } private static void TestSizeParamIndex() { Console.WriteLine("Testing SizeParamIndex"); byte byte_Array_Size; byte[] arrByte; VerifySizeParamIndex(out arrByte, out byte_Array_Size); ThrowIfNotEquals(10, byte_Array_Size, "out size failed."); bool pass = true; for (int i = 0; i < byte_Array_Size; i++) { if (arrByte[i] != i) { pass = false; break; } } ThrowIfNotEquals(true, pass, "SizeParamIndex failed."); } private class ClosedDelegateCLass { public int Sum(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j) { return a + b + c + d + e + f + g + h + i + j; } public bool GetString(String s) { return s == "Hello World"; } } private static void TestDelegate() { Console.WriteLine("Testing Delegate"); Delegate_Int del = new Delegate_Int(Sum); ThrowIfNotEquals(true, ReversePInvoke_Int(del), "Delegate marshalling failed."); unsafe { // // We haven't instantiated Delegate_Unused and nobody // allocates it. If a EEType is not constructed for Delegate_Unused // it will fail during linking. // ReversePInvoke_Unused(null); } Delegate_Int closed = new Delegate_Int((new ClosedDelegateCLass()).Sum); ThrowIfNotEquals(true, ReversePInvoke_Int(closed), "Closed Delegate marshalling failed."); Delegate_String ret = GetDelegate(); ThrowIfNotEquals(true, ret("Hello World!"), "Delegate as P/Invoke return failed"); Delegate_String d = new Delegate_String(new ClosedDelegateCLass().GetString); ThrowIfNotEquals(true, Callback(ref d), "Delegate IN marshalling failed"); ThrowIfNotEquals(true, d("Hello World!"), "Delegate OUT marshalling failed"); Delegate_String ds = new Delegate_String((new ClosedDelegateCLass()).GetString); ThrowIfNotEquals(true, ReversePInvoke_String(ds), "Delegate marshalling failed."); IntPtr procAddress = GetFunctionPointer(); SetLastErrorFuncDelegate funcDelegate = Marshal.GetDelegateForFunctionPointer<SetLastErrorFuncDelegate>(procAddress); funcDelegate(0x204); ThrowIfNotEquals(0x204, Marshal.GetLastWin32Error(), "Not match"); } static int Sum(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j) { return a + b + c + d + e + f + g + h + i + j; } [StructLayout(LayoutKind.Auto)] public struct AutoStruct { public short f0; public int f1; public float f2; [MarshalAs(UnmanagedType.LPStr)] public String f3; } [StructLayout(LayoutKind.Sequential)] public struct SequentialStruct { public short f0; public int f1; public float f2; [MarshalAs(UnmanagedType.LPStr)] public String f3; } // A second struct with the same name but nested. Regression test against native types being mangled into // the compiler-generated type and losing fully qualified type name information. class NesterOfSequentialStruct { [StructLayout(LayoutKind.Sequential)] public struct SequentialStruct { public float f1; public int f2; } } [StructLayout(LayoutKind.Explicit)] public struct ExplicitStruct { [FieldOffset(0)] public int f1; [FieldOffset(12)] public float f2; [FieldOffset(24)] [MarshalAs(UnmanagedType.LPStr)] public String f3; } [StructLayout(LayoutKind.Sequential)] public struct NestedStruct { public int f1; public ExplicitStruct f2; } [StructLayout(LayoutKind.Explicit)] public struct TestStruct2 { [FieldOffset(0)] public int f1; [FieldOffset(8)] public bool f2; } private static void TestStruct() { #if !CODEGEN_CPP Console.WriteLine("Testing Structs"); SequentialStruct ss = new SequentialStruct(); ss.f0 = 100; ss.f1 = 1; ss.f2 = 10.0f; ss.f3 = "Hello"; ThrowIfNotEquals(true, StructTest(ss), "Struct marshalling scenario1 failed."); StructTest_ByRef(ref ss); ThrowIfNotEquals(true, ss.f1 == 2 && ss.f2 == 11.0 && ss.f3.Equals("Ifmmp"), "Struct marshalling scenario2 failed."); SequentialStruct ss2 = new SequentialStruct(); StructTest_ByOut(out ss2); ThrowIfNotEquals(true, ss2.f0 == 1 && ss2.f1 == 1.0 && ss2.f2 == 1.0 && ss2.f3.Equals("0123456"), "Struct marshalling scenario3 failed."); NesterOfSequentialStruct.SequentialStruct ss3 = new NesterOfSequentialStruct.SequentialStruct(); ss3.f1 = 10.0f; ss3.f2 = 123; ThrowIfNotEquals(true, StructTest_Sequential2(ss3), "Struct marshalling scenario1 failed."); ExplicitStruct es = new ExplicitStruct(); es.f1 = 100; es.f2 = 100.0f; es.f3 = "Hello"; ThrowIfNotEquals(true, StructTest_Explicit(es), "Struct marshalling scenario4 failed."); NestedStruct ns = new NestedStruct(); ns.f1 = 100; ns.f2 = es; ThrowIfNotEquals(true, StructTest_Nested(ns), "Struct marshalling scenario5 failed."); SequentialStruct[] ssa = null; ThrowIfNotEquals(true, IsNULL(ssa), "Non-blittable array null check failed"); ssa = new SequentialStruct[3]; for (int i = 0; i < 3; i++) { ssa[i].f1 = 0; ssa[i].f1 = i; ssa[i].f2 = i*i; ssa[i].f3 = i.LowLevelToString(); } ThrowIfNotEquals(true, StructTest_Array(ssa, ssa.Length), "Array of struct marshalling failed"); InlineArrayStruct ias = new InlineArrayStruct(); ias.inlineArray = new short[128]; for (short i = 0; i < 128; i++) { ias.inlineArray[i] = i; } ias.inlineString = "Hello"; InlineUnicodeStruct ius = new InlineUnicodeStruct(); ius.inlineString = "Hello World"; TestStruct2 ts = new TestStruct2() { f1 = 100, f2 = true }; int size = Marshal.SizeOf<TestStruct2>(ts); IntPtr memory = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr<TestStruct2>(ts, memory, false); TestStruct2 ts2 = Marshal.PtrToStructure<TestStruct2>(memory); ThrowIfNotEquals(true, ts2.f1 == 100 && ts2.f2 == true, "Struct marshalling Marshal API failed"); IntPtr offset = Marshal.OffsetOf<TestStruct2>("f2"); ThrowIfNotEquals(new IntPtr(8), offset, "Struct marshalling OffsetOf failed."); } finally { Marshal.FreeHGlobal(memory); } ThrowIfNotEquals(true, InlineArrayTest(ref ias, ref ius), "inline array marshalling failed"); bool pass = true; for (short i = 0; i < 128; i++) { if (ias.inlineArray[i] != i + 1) { pass = false; } } ThrowIfNotEquals(true, pass, "inline array marshalling failed"); ThrowIfNotEquals("Hello World", ias.inlineString, "Inline ByValTStr Ansi marshalling failed"); ThrowIfNotEquals("Hello World", ius.inlineString, "Inline ByValTStr Unicode marshalling failed"); // RhpThrowEx is not implemented in CPPCodeGen pass = false; AutoStruct autoStruct = new AutoStruct(); try { // passing struct with Auto layout should throw exception. StructTest_Auto(autoStruct); } catch (Exception) { pass = true; } ThrowIfNotEquals(true, pass, "Struct marshalling scenario6 failed."); #endif } } public class SafeMemoryHandle : SafeHandle //SafeHandle subclass { [DllImport("*", CallingConvention = CallingConvention.StdCall)] public static extern SafeMemoryHandle AllocateMemory(int size); [DllImport("*", CallingConvention = CallingConvention.StdCall)] public static extern bool ReleaseMemory(IntPtr handle); public SafeMemoryHandle() : base(IntPtr.Zero, true) { } private static readonly IntPtr _invalidHandleValue = new IntPtr(-1); public override bool IsInvalid { get { return handle == IntPtr.Zero || handle == _invalidHandleValue; } } override protected bool ReleaseHandle() { return ReleaseMemory(handle); } } //end of SafeMemoryHandle class public static class LowLevelExtensions { // Int32.ToString() calls into glob/loc garbage that hits CppCodegen limitations public static string LowLevelToString(this int i) { char[] digits = new char[11]; int numDigits = 0; if (i == int.MinValue) return "-2147483648"; bool negative = i < 0; if (negative) i = -i; do { digits[numDigits] = (char)('0' + (i % 10)); numDigits++; i /= 10; } while (i != 0); if (negative) { digits[numDigits] = '-'; numDigits++; } Array.Reverse(digits); return new string(digits, digits.Length - numDigits, numDigits); } } }
//*************************************************** //* This file was generated by tool //* SharpKit //*************************************************** using System; using System.Collections.Generic; using SharpKit.JavaScript; namespace Y_ { /// <summary> /// A base class for Resize, providing: /// * Basic Lifecycle (initializer, renderUI, bindUI, syncUI, destructor) /// * Applies drag handles to an element to make it resizable /// * Here is the list of valid resize handles: /// `[ 't', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl' ]`. You can /// read this list as top, top-right, right, bottom-right, bottom, /// bottom-left, left, top-left. /// * The drag handles are inserted into the element and positioned /// absolute. Some elements, such as a textarea or image, don't support /// children. To overcome that, set wrap:true in your config and the /// element willbe wrapped for you automatically. /// Quick Example: /// var instance = new Y.Resize({ /// node: '#resize1', /// preserveRatio: true, /// wrap: true, /// maxHeight: 170, /// maxWidth: 400, /// handles: 't, tr, r, br, b, bl, l, tl' /// }); /// Check the list of <a href="Resize.html#configattributes">Configuration Attributes</a> available for /// Resize. /// </summary> public partial class Resize : Y_.Base { /// <summary> /// Creates the handle element based on the handle name and initialize the /// DragDrop on it. /// </summary> protected void _buildHandle(object handle){} /// <summary> /// Basic resize calculations. /// </summary> protected void _calcResize(){} /// <summary> /// Helper method to update the current size value on /// <a href="Resize.html#property_info">info</a> to respect the /// min/max values and fix the top/left calculations. /// </summary> protected void _checkSize(object offset, Y_.DataType_.Number size){} /// <summary> /// Copy relevant styles of the <a href="Resize.html#attr_node">node</a> /// to the <a href="Resize.html#attr_wrapper">wrapper</a>. /// </summary> protected void _copyStyles(Node node, Node wrapper){} [JsMethod(JsonInitializers=true)] public Resize(){} /// <summary> /// Default resize:mouseUp handler /// </summary> protected void _defMouseUpFn(EventFacade @event){} /// <summary> /// Default resize:align handler /// </summary> protected void _defResizeAlignFn(EventFacade @event){} /// <summary> /// Default resize:end handler /// </summary> protected void _defResizeEndFn(EventFacade @event){} /// <summary> /// Default resize:resize handler /// </summary> protected void _defResizeFn(EventFacade @event){} /// <summary> /// Default resize:start handler /// </summary> protected void _defResizeStartFn(EventFacade @event){} /// <summary> /// Fires the resize:mouseUp event. /// </summary> protected void _handleMouseUpEvent(EventFacade @event){} /// <summary> /// Fires the resize:align event. /// </summary> protected void _handleResizeAlignEvent(EventFacade @event){} /// <summary> /// Fires the resize:end event. /// </summary> protected void _handleResizeEndEvent(EventFacade @event){} /// <summary> /// Fires the resize:resize event. /// </summary> protected void _handleResizeEvent(EventFacade @event){} /// <summary> /// Fires the resize:start event. /// </summary> protected void _handleResizeStartEvent(EventFacade @event){} /// <summary> /// Mouseenter event handler for the handles. /// </summary> protected void _onHandleMouseEnter(EventFacade @event){} /// <summary> /// Mouseout event handler for the handles. /// </summary> protected void _onHandleMouseLeave(EventFacade @event){} /// <summary> /// Mouseenter event handler for the <a href="Resize.html#attr_wrapper">wrapper</a>. /// </summary> protected void _onWrapperMouseEnter(EventFacade @event){} /// <summary> /// Mouseleave event handler for the <a href="Resize.html#attr_wrapper">wrapper</a>. /// </summary> protected void _onWrapperMouseLeave(EventFacade @event){} /// <summary> /// Responsible for loop each handle element and append to the wrapper. /// </summary> protected void _renderHandles(){} /// <summary> /// Logic method for _defResizeFn. Allow AOP. /// </summary> protected void _resize(EventFacade @event){} /// <summary> /// Logic method for _defResizeAlignFn. Allow AOP. /// </summary> protected void _resizeAlign(EventFacade @event){} /// <summary> /// Logic method for _defResizeEndFn. Allow AOP. /// </summary> protected void _resizeEnd(EventFacade @event){} /// <summary> /// Logic method for _defResizeStartFn. Allow AOP. /// </summary> protected void _resizeStart(EventFacade @event){} /// <summary> /// Set the active state of the handles. /// </summary> protected void _setActiveHandlesUI(object val){} /// <summary> /// Handles setting the activeHandle from a node, used from startDrag (for touch) and mouseenter (for mouse). /// </summary> protected void _setHandleFromNode(Node node){} /// <summary> /// Setter for the handles attribute /// </summary> protected void _setHandles(object val){} /// <summary> /// Set the visibility of the handles. /// </summary> protected void _setHideHandlesUI(object val){} /// <summary> /// Setter for the wrap attribute /// </summary> protected void _setWrap(object val){} /// <summary> /// Sync the Resize UI with internal values from /// <a href="Resize.html#property_info">info</a>. /// </summary> protected void _syncUI(){} /// <summary> /// Default value for the wrapper handles node attribute /// </summary> protected void _valueHandlesWrapper(){} /// <summary> /// Default value for the wrapper attribute /// </summary> protected void _valueWrapper(){} /// <summary> /// Bind the events on the Resize UI. Lifecycle. /// </summary> protected void bindUI(){} /// <summary> /// Descructor lifecycle implementation for the Resize class. Purges events attached /// to the node (and all child nodes) and removes the Resize handles. /// </summary> protected void destructor(){} /// <summary> /// <p>Loop through each handle which is being used and executes a callback.</p> /// <p>Example:</p> /// <pre><code>instance.eachHandle( /// function(handleName, index) { ... } /// );</code></pre> /// </summary> public void eachHandle(JsAction fn){} /// <summary> /// Construction logic executed during Resize instantiation. Lifecycle. /// </summary> protected void initializer(){} /// <summary> /// Creates DOM (or manipulates DOM for progressive enhancement) /// This method is invoked by initializer(). It's chained automatically for /// subclasses if required. /// </summary> protected void renderer(){} /// <summary> /// Create the DOM structure for the Resize. Lifecycle. /// </summary> protected void renderUI(){} /// <summary> /// Sync the Resize UI. /// </summary> protected void syncUI(){} /// <summary> /// Static property used to define the default attribute /// configuration for the Resize. /// </summary> public object ATTRS{get;set;} /// <summary> /// The default minimum height of the element. Only used when /// ResizeConstrained is not plugged. /// </summary> public Y_.DataType_.Number defMinHeight{get;set;} /// <summary> /// The default minimum width of the element. Only used when /// ResizeConstrained is not plugged. /// </summary> public Y_.DataType_.Number defMinWidth{get;set;} /// <summary> /// Store DD.Delegate reference for the respective Resize instance. /// </summary> public object @delegate{get;set;} /// <summary> /// Node to wrap the resize handles. /// </summary> public Node handlesWrapper{get;set;} /// <summary> /// Stores the current values for the height, width, top and left. You are /// able to manipulate these values on resize in order to change the resize /// behavior. /// </summary> protected object info{get;set;} /// <summary> /// Stores the last values for the height, width, top and left. /// </summary> protected object lastInfo{get;set;} /// <summary> /// The selector or element to resize. Required. /// </summary> public Node node{get;set;} /// <summary> /// Stores the <a href="Resize.html#attr_node">node</a> /// surrounding information retrieved from /// <a href="Resize.html#method__getBoxSurroundingInfo">_getBoxSurroundingInfo</a>. /// </summary> public object nodeSurrounding{get;set;} /// <summary> /// Stores the original values for the height, width, top and left, stored /// on resize start. /// </summary> protected object originalInfo{get;set;} /// <summary> /// Stores the <a href="Resize.html#attr_wrapper">wrapper</a> /// surrounding information retrieved from /// <a href="Resize.html#method__getBoxSurroundingInfo">_getBoxSurroundingInfo</a>. /// </summary> public object wrapperSurrounding{get;set;} } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Help; using System.IO; using System.Globalization; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Diagnostics; namespace Microsoft.PowerShell.Commands { /// <summary> /// This class implements the Update-Help cmdlet /// </summary> [Cmdlet(VerbsData.Update, "Help", DefaultParameterSetName = PathParameterSetName, SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=210614")] public sealed class UpdateHelpCommand : UpdatableHelpCommandBase { #region Constructor /// <summary> /// Class constructor /// </summary> public UpdateHelpCommand() : base(UpdatableHelpCommandType.UpdateHelpCommand) { } #endregion private bool _alreadyCheckedOncePerDayPerModule = false; #region Parameters /// <summary> /// Specifies the modules to update /// </summary> [Parameter(Position = 0, ParameterSetName = PathParameterSetName, ValueFromPipelineByPropertyName = true)] [Parameter(Position = 0, ParameterSetName = LiteralPathParameterSetName, ValueFromPipelineByPropertyName = true)] [Alias("Name")] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Module { get { return _module; } set { _module = value; } } private string[] _module; /// <summary> /// Specifies the Module Specifications to update /// </summary> [Parameter(ParameterSetName = PathParameterSetName, ValueFromPipelineByPropertyName = true)] [Parameter(ParameterSetName = LiteralPathParameterSetName, ValueFromPipelineByPropertyName = true)] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public ModuleSpecification[] FullyQualifiedModule { get; set; } /// <summary> /// Specifies the paths to update from /// </summary> [Parameter(Position = 1, ParameterSetName = PathParameterSetName)] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] SourcePath { get { return _path; } set { _path = value; } } private string[] _path; /// <summary> /// Specifies the literal path to save updates to /// </summary> [Parameter(ParameterSetName = LiteralPathParameterSetName, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath { get { return _path; } set { _path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; /// <summary> /// Scans paths recursively /// </summary> [Parameter] public SwitchParameter Recurse { get { return _recurse; } set { _recurse = value; } } private bool _recurse; #endregion private bool _isInitialized = false; #region Implementation /// <summary> /// Begin processing /// </summary> protected override void BeginProcessing() { // Disable Get-Help prompt UpdatableHelpSystem.SetDisablePromptToUpdateHelp(); if (_path == null) { // Pull default source path from GP string defaultSourcePath = _helpSystem.GetDefaultSourcePath(); if (defaultSourcePath != null) { _path = new string[1] { defaultSourcePath }; } } } /// <summary> /// Main cmdlet logic /// </summary> protected override void ProcessRecord() { try { // Module and FullyQualifiedModule should not be specified at the same time. // Throw out terminating error if this is the case. if (Module != null && FullyQualifiedModule != null) { string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "Module", "FullyQualifiedModule"); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(error); } if (!_isInitialized) { if (_path == null && Recurse.IsPresent) { PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.CannotSpecifyRecurseWithoutPath)); ThrowTerminatingError(e.ErrorRecord); } _isInitialized = true; } base.Process(_module, FullyQualifiedModule); // Reset the per-runspace help cache foreach (HelpProvider provider in Context.HelpSystem.HelpProviders) { if (_stopping) { break; } provider.Reset(); } } finally { ProgressRecord progress = new ProgressRecord(activityId, HelpDisplayStrings.UpdateProgressActivityForModule, HelpDisplayStrings.UpdateProgressInstalling); progress.PercentComplete = 100; progress.RecordType = ProgressRecordType.Completed; WriteProgress(progress); } } /// <summary> /// Process a single module with a given culture /// </summary> /// <param name="module">module to process</param> /// <param name="culture">culture to use</param> /// <returns>true if the module has been processed, false if not</returns> internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string culture) { UpdatableHelpInfo currentHelpInfo = null; UpdatableHelpInfo newHelpInfo = null; string helpInfoUri = null; // reading the xml file even if force is specified // Reason: we need the current version for ShouldProcess string xml = UpdatableHelpSystem.LoadStringFromPath(this, SessionState.Path.Combine(module.ModuleBase, module.GetHelpInfoName()), null); if (xml != null) { // constructing the helpinfo object from previous update help log xml.. // no need to resolve the uri's in this case. currentHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, currentCulture: null, pathOverride: null, verbose: false, shouldResolveUri: false, // ignore validation exception if _force is true ignoreValidationException: _force); } // Don't update too frequently if (!_alreadyCheckedOncePerDayPerModule && !CheckOncePerDayPerModule(module.ModuleName, module.ModuleBase, module.GetHelpInfoName(), DateTime.UtcNow, _force)) { return true; } _alreadyCheckedOncePerDayPerModule = true; if (_path != null) { UpdatableHelpSystemDrive helpInfoDrive = null; try { Collection<string> resolvedPaths = new Collection<string>(); // Search for the HelpInfo XML foreach (string path in _path) { if (String.IsNullOrEmpty(path)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.PathNullOrEmpty)); WriteError(e.ErrorRecord); return false; } try { string sourcePath = path; if (_credential != null) { UpdatableHelpSystemDrive drive = new UpdatableHelpSystemDrive(this, path, _credential); sourcePath = drive.DriveName; } // Expand wildcard characters foreach (string tempPath in ResolvePath(sourcePath, _recurse, _isLiteralPath)) { resolvedPaths.Add(tempPath); } } catch (System.Management.Automation.DriveNotFoundException e) { ThrowPathMustBeValidContainersException(path, e); } catch (ItemNotFoundException e) { ThrowPathMustBeValidContainersException(path, e); } } if (resolvedPaths.Count == 0) { return true; } // Everything in resolvedPaths is a container foreach (string resolvedPath in resolvedPaths) { string literalPath = SessionState.Path.Combine(resolvedPath, module.GetHelpInfoName()); xml = UpdatableHelpSystem.LoadStringFromPath(this, literalPath, _credential); if (xml != null) { newHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, culture, resolvedPath, verbose: false, shouldResolveUri: true, ignoreValidationException: false); helpInfoUri = resolvedPath; break; } } } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml", StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable, null, e); } finally { if (helpInfoDrive != null) { helpInfoDrive.Dispose(); } } } else { // Form the actual HelpInfo.xml uri helpInfoUri = _helpSystem.GetHelpInfoUri(module, null).ResolvedUri; string uri = helpInfoUri + module.GetHelpInfoName(); newHelpInfo = _helpSystem.GetHelpInfo(UpdatableHelpCommandType.UpdateHelpCommand, uri, module.ModuleName, module.ModuleGuid, culture); } if (newHelpInfo == null) { throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml", StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable, null, null); } bool installed = false; foreach (UpdatableHelpUri contentUri in newHelpInfo.HelpContentUriCollection) { Version currentHelpVersion = (currentHelpInfo != null) ? currentHelpInfo.GetCultureVersion(contentUri.Culture) : null; string updateHelpShouldProcessAction = string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.UpdateHelpShouldProcessActionMessage, module.ModuleName, (currentHelpVersion != null) ? currentHelpVersion.ToString() : "0.0.0.0", newHelpInfo.GetCultureVersion(contentUri.Culture), contentUri.Culture); if (!this.ShouldProcess(updateHelpShouldProcessAction, "Update-Help")) { continue; } if (Utils.IsUnderProductFolder(module.ModuleBase) && (!Utils.IsAdministrator())) { string message = StringUtil.Format(HelpErrors.UpdatableHelpRequiresElevation); ProcessException(module.ModuleName, null, new UpdatableHelpSystemException("UpdatableHelpSystemRequiresElevation", message, ErrorCategory.InvalidOperation, null, null)); return false; } if (!IsUpdateNecessary(module, _force ? null : currentHelpInfo, newHelpInfo, contentUri.Culture, _force)) { WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, module.ModuleName, HelpDisplayStrings.NewestContentAlreadyInstalled, contentUri.Culture.Name, newHelpInfo.GetCultureVersion(contentUri.Culture))); installed = true; continue; } else { try { Debug.Assert(helpInfoUri != null, "If we are here, helpInfoUri must not be null"); string helpContentUri = contentUri.ResolvedUri; string xsdPath = SessionState.Path.Combine(Utils.GetApplicationBase(Context.ShellID), "Schemas\\PSMaml\\maml.xsd"); // TODO: Edit the maml XSDs and change this // Gather destination paths Collection<string> destPaths = new Collection<string>(); destPaths.Add(module.ModuleBase); #if !CORECLR // Side-By-Side directories are not present in OneCore environments. if (IsSystemModule(module.ModuleName) && ClrFacade.Is64BitOperatingSystem()) { string path = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID).Replace("System32", "SysWOW64"); destPaths.Add(path); } #endif Collection<string> filesInstalled; if (Directory.Exists(helpContentUri)) { if (_credential != null) { string helpContentName = module.GetHelpContentName(contentUri.Culture); string tempContentPath = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())); try { using (UpdatableHelpSystemDrive drive = new UpdatableHelpSystemDrive(this, helpContentUri, _credential)) { if (!Directory.Exists(tempContentPath)) { Directory.CreateDirectory(tempContentPath); } InvokeProvider.Item.Copy(new string[1] { Path.Combine(drive.DriveName, helpContentName) }, Path.Combine(tempContentPath, helpContentName), false, CopyContainers.CopyTargetContainer, true, true); // Local _helpSystem.InstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, Context, tempContentPath, destPaths, module.GetHelpContentName(contentUri.Culture), Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())), contentUri.Culture, xsdPath, out filesInstalled); } } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); throw new UpdatableHelpSystemException("HelpContentNotFound", StringUtil.Format(HelpDisplayStrings.HelpContentNotFound), ErrorCategory.ResourceUnavailable, null, e); } } else { _helpSystem.InstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, Context, helpContentUri, destPaths, module.GetHelpContentName(contentUri.Culture), Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())), contentUri.Culture, xsdPath, out filesInstalled); } } else { // Remote // Download and install help content if (!_helpSystem.DownloadAndInstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, Context, destPaths, module.GetHelpContentName(contentUri.Culture), contentUri.Culture, helpContentUri, xsdPath, out filesInstalled)) { installed = false; continue; } } _helpSystem.GenerateHelpInfo(module.ModuleName, module.ModuleGuid, newHelpInfo.UnresolvedUri, contentUri.Culture.Name, newHelpInfo.GetCultureVersion(contentUri.Culture), module.ModuleBase, module.GetHelpInfoName(), _force); foreach (string fileInstalled in filesInstalled) { WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, module.ModuleName, StringUtil.Format(HelpDisplayStrings.UpdatedHelpContent, fileInstalled), contentUri.Culture.Name, newHelpInfo.GetCultureVersion(contentUri.Culture))); } LogMessage(StringUtil.Format(HelpDisplayStrings.UpdateHelpCompleted)); installed = true; } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); ProcessException(module.ModuleName, contentUri.Culture.Name, e); } } } return installed; } /// <summary> /// Throws PathMustBeValidContainers exception /// </summary> /// <param name="path"></param> /// <param name="e"></param> private void ThrowPathMustBeValidContainersException(string path, Exception e) { throw new UpdatableHelpSystemException("PathMustBeValidContainers", StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, path), ErrorCategory.InvalidArgument, null, e); } #endregion } }
using System; using System.Collections; namespace DoFactory.HeadFirst.Iterator.DinerMerger { class MenuTestDrive { static void Main(string[] args) { var pancakeHouseMenu = new PancakeHouseMenu(); var dinerMenu = new DinerMenu(); var waitress = new Waitress(pancakeHouseMenu, dinerMenu); waitress.PrintMenu(); // Wait for user Console.ReadKey(); } } #region Waitress public class Waitress { private PancakeHouseMenu _pancakeHouseMenu; private DinerMenu _dinerMenu; public Waitress(PancakeHouseMenu pancakeHouseMenu, DinerMenu dinerMenu) { this._pancakeHouseMenu = pancakeHouseMenu; this._dinerMenu = dinerMenu; } public void PrintMenu() { Iterator pancakeIterator = _pancakeHouseMenu.CreateIterator(); Iterator dinerIterator = _dinerMenu.CreateIterator(); Console.WriteLine("MENU\n----\nBREAKFAST"); PrintMenu(pancakeIterator); Console.WriteLine("\nLUNCH"); PrintMenu(dinerIterator); } private void PrintMenu(Iterator iterator) { while (iterator.HasNext()) { MenuItem menuItem = (MenuItem)iterator.Next(); Console.Write(menuItem.Name + ", "); Console.Write(menuItem.Price + " -- "); Console.WriteLine(menuItem.Description); } } public void PrintVegetarianMenu() { PrintVegetarianMenu(_pancakeHouseMenu.CreateIterator()); PrintVegetarianMenu(_dinerMenu.CreateIterator()); } public bool IsItemVegetarian(String name) { Iterator breakfastIterator = _pancakeHouseMenu.CreateIterator(); if (IsVegetarian(name, breakfastIterator)) { return true; } Iterator dinnerIterator = _dinerMenu.CreateIterator(); if (IsVegetarian(name, dinnerIterator)) { return true; } return false; } private void PrintVegetarianMenu(Iterator iterator) { while (iterator.HasNext()) { MenuItem menuItem = (MenuItem)iterator.Next(); if (menuItem.Vegetarian) { Console.WriteLine(menuItem.Name); Console.WriteLine("\t\t" + menuItem.Price); Console.WriteLine("\t" + menuItem.Description); } } } private bool IsVegetarian(string name, Iterator iterator) { while (iterator.HasNext()) { MenuItem menuItem = (MenuItem)iterator.Next(); if (menuItem.Name.Equals(name)) { if (menuItem.Vegetarian) { return true; } } } return false; } } #endregion #region Iterators public interface Iterator { bool HasNext(); object Next(); } public class AlternatingDinerMenuIterator : Iterator { private MenuItem[] _list; private int _position; public AlternatingDinerMenuIterator(MenuItem[] list) { this._list = list; _position = int.Parse(DateTime.Now.DayOfWeek.ToString()) % 2; } public object Next() { MenuItem menuItem = _list[_position]; _position = _position + 2; return menuItem; } public bool HasNext() { if (_position >= _list.Length || _list[_position] == null) { return false; } else { return true; } } public override string ToString() { return "Alternating Diner Menu Iterator"; } } public class ArrayIterator : Iterator { private MenuItem[] _items; private int _position = 0; // Constructore public ArrayIterator(MenuItem[] items) { this._items = items; } public object Next() { MenuItem menuItem = _items[_position]; _position = _position + 1; return menuItem; } public bool HasNext() { if (_position >= _items.Length || _items[_position] == null) { return false; } else { return true; } } } public class ArrayListIterator : Iterator { private ArrayList _items; private int _position = 0; // Constructor public ArrayListIterator(ArrayList items) { this._items = items; } public object Next() { object o = _items[_position]; _position = _position + 1; return o; } public bool HasNext() { if (_position >= _items.Count) { return false; } else { return true; } } } public class DinerMenuIterator : Iterator { private MenuItem[] _items; private int _position = 0; public DinerMenuIterator(MenuItem[] items) { this._items = items; } public Object Next() { MenuItem menuItem = _items[_position]; _position = _position + 1; return menuItem; } public bool HasNext() { if (_position >= _items.Length || _items[_position] == null) { return false; } else { return true; } } } #endregion #region Menu and MenuItems public interface Menu { Iterator CreateIterator(); } public class MenuItem { // Constructor public MenuItem(string name, string description, bool vegetarian, double price) { this.Name = name; this.Description = description; this.Vegetarian = vegetarian; this.Price = price; } public string Name { get; set; } public string Description { get; set; } public double Price { get; set; } public bool Vegetarian { get; set; } public override string ToString() { return (Name + ", $" + Price + "\n " + Description); } } public class DinerMenu : Menu { private static readonly int MAX_ITEMS = 6; private int _numberOfItems = 0; private MenuItem[] _menuItems = new MenuItem[MAX_ITEMS]; public DinerMenu() { AddItem("Vegetarian BLT", "(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99); AddItem("BLT", "Bacon with lettuce & tomato on whole wheat", false, 2.99); AddItem("Soup of the day", "Soup of the day, with a side of potato salad", false, 3.29); AddItem("Hotdog", "A hot dog, with saurkraut, relish, onions, topped with cheese", false, 3.05); AddItem("Steamed Veggies and Brown Rice", "Steamed vegetables over brown rice", true, 3.99); AddItem("Pasta", "Spaghetti with Marinara Sauce, and a slice of sourdough bread", true, 3.89); } public void AddItem(String name, String description, bool vegetarian, double price) { MenuItem menuItem = new MenuItem(name, description, vegetarian, price); if (_numberOfItems >= MAX_ITEMS) { Console.WriteLine("Sorry, menu is full! Can't add item to menu"); } else { _menuItems[_numberOfItems] = menuItem; _numberOfItems = _numberOfItems + 1; } } public MenuItem[] GetMenuItems() { return _menuItems; } public Iterator CreateIterator() { return new DinerMenuIterator(_menuItems); } // other menu methods here } public class PancakeHouseMenu : Menu { private ArrayList _menuItems = new ArrayList(); public PancakeHouseMenu() { AddItem("K&B's Pancake Breakfast", "Pancakes with scrambled eggs, and toast", true, 2.99); AddItem("Regular Pancake Breakfast", "Pancakes with fried eggs, sausage", false, 2.99); AddItem("Blueberry Pancakes", "Pancakes made with fresh blueberries", true, 3.49); AddItem("Waffles", "Waffles, with your choice of blueberries or strawberries", true, 3.59); } public void AddItem(String name, String description, bool vegetarian, double price) { _menuItems.Add(new MenuItem(name, description, vegetarian, price)); } public ArrayList GetMenuItems() { return _menuItems; } public Iterator CreateIterator() { return new PancakeHouseMenuIterator(_menuItems); } public override string ToString() { return "Objectville Pancake House Menu"; } // other menu methods here } public class PancakeHouseMenuIterator : Iterator { private ArrayList _items; private int _position = 0; public PancakeHouseMenuIterator(ArrayList items) { this._items = items; } public object Next() { object o = _items[_position]; _position = _position + 1; return o; } public bool HasNext() { if (_position >= _items.Count) { return false; } else { return true; } } } #endregion }
namespace EIDSS.Reports.Parameterized.Human.GG.Report { public partial class LaboratoryResearchReport { #region 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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LaboratoryResearchReport)); DevExpress.XtraReports.UI.XRSummary xrSummary1 = new DevExpress.XtraReports.UI.XRSummary(); this.VetReport = new DevExpress.XtraReports.UI.DetailReportBand(); this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand(); this.VetDetail = new DevExpress.XtraReports.UI.DetailBand(); this.xrTable3 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow22 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell39 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell47 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell(); this.VetReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.xrTable4 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow20 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell43 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow21 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell44 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell45 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell46 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrPageBreak1 = new DevExpress.XtraReports.UI.XRPageBreak(); this.xrTable2 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell36 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.tableCustomSubheader = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow16 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow17 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrPictureBox1 = new DevExpress.XtraReports.UI.XRPictureBox(); this.HeaderTable = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.HeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.locationCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.OrganizationPrefixCell = new DevExpress.XtraReports.UI.XRTableCell(); this.OrganizationCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.m_DataAdapter = new EIDSS.Reports.Parameterized.Human.GG.DataSet.LaboratoryResearchDataSetTableAdapters.LaboratoryResearchResultAdapter(); this.m_DataSet = new EIDSS.Reports.Parameterized.Human.GG.DataSet.LaboratoryResearchDataSet(); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableCustomSubheader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // cellLanguage // this.cellLanguage.StylePriority.UseTextAlignment = false; // // lblReportName // resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // Detail // this.Detail.Expanded = false; this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; resources.ApplyResources(this.Detail, "Detail"); // // PageHeader // resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; // // PageFooter // this.PageFooter.StylePriority.UseBorders = false; // // ReportHeader // this.ReportHeader.Expanded = false; resources.ApplyResources(this.ReportHeader, "ReportHeader"); // // xrPageInfo1 // resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1"); this.xrPageInfo1.StylePriority.UseBorders = false; this.xrPageInfo1.StylePriority.UseFont = false; // // cellReportHeader // this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.cellReportHeader, "cellReportHeader"); // // cellBaseSite // this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.cellBaseSite, "cellBaseSite"); // // cellBaseCountry // resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry"); // // cellBaseLeftHeader // resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader"); // // tableBaseHeader // resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader"); this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // VetReport // this.VetReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.ReportFooter, this.VetDetail, this.VetReportHeader}); this.VetReport.DataAdapter = this.m_DataAdapter; this.VetReport.DataMember = "LaboratoryResearchResult"; this.VetReport.DataSource = this.m_DataSet; this.VetReport.Level = 0; this.VetReport.Name = "VetReport"; resources.ApplyResources(this.VetReport, "VetReport"); // // ReportFooter // resources.ApplyResources(this.ReportFooter, "ReportFooter"); this.ReportFooter.Name = "ReportFooter"; // // VetDetail // this.VetDetail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable3}); resources.ApplyResources(this.VetDetail, "VetDetail"); this.VetDetail.KeepTogether = true; this.VetDetail.Name = "VetDetail"; // // xrTable3 // this.xrTable3.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable3, "xrTable3"); this.xrTable3.Name = "xrTable3"; this.xrTable3.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow22}); this.xrTable3.StylePriority.UseBorders = false; // // xrTableRow22 // this.xrTableRow22.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell39, this.xrTableCell40, this.xrTableCell47, this.xrTableCell48, this.xrTableCell49}); this.xrTableRow22.Name = "xrTableRow22"; this.xrTableRow22.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableRow22, "xrTableRow22"); // // xrTableCell39 // this.xrTableCell39.Name = "xrTableCell39"; this.xrTableCell39.StylePriority.UseFont = false; xrSummary1.Func = DevExpress.XtraReports.UI.SummaryFunc.RecordNumber; xrSummary1.Running = DevExpress.XtraReports.UI.SummaryRunning.Report; this.xrTableCell39.Summary = xrSummary1; resources.ApplyResources(this.xrTableCell39, "xrTableCell39"); // // xrTableCell40 // this.xrTableCell40.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strPrimaryDiagnosis")}); this.xrTableCell40.Name = "xrTableCell40"; this.xrTableCell40.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell40, "xrTableCell40"); // // xrTableCell47 // this.xrTableCell47.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strFarmOwner")}); this.xrTableCell47.Name = "xrTableCell47"; this.xrTableCell47.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell47, "xrTableCell47"); // // xrTableCell48 // this.xrTableCell48.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strSpecies")}); this.xrTableCell48.Name = "xrTableCell48"; this.xrTableCell48.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell48, "xrTableCell48"); // // xrTableCell49 // this.xrTableCell49.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strAnimal")}); this.xrTableCell49.Name = "xrTableCell49"; this.xrTableCell49.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell49, "xrTableCell49"); // // VetReportHeader // this.VetReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable4, this.xrPageBreak1, this.xrTable2, this.tableCustomSubheader, this.xrTable1}); resources.ApplyResources(this.VetReportHeader, "VetReportHeader"); this.VetReportHeader.Name = "VetReportHeader"; // // xrTable4 // resources.ApplyResources(this.xrTable4, "xrTable4"); this.xrTable4.Name = "xrTable4"; this.xrTable4.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow20, this.xrTableRow21}); // // xrTableRow20 // this.xrTableRow20.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell43}); this.xrTableRow20.Name = "xrTableRow20"; resources.ApplyResources(this.xrTableRow20, "xrTableRow20"); // // xrTableCell43 // resources.ApplyResources(this.xrTableCell43, "xrTableCell43"); this.xrTableCell43.Name = "xrTableCell43"; this.xrTableCell43.StylePriority.UseFont = false; this.xrTableCell43.StylePriority.UseTextAlignment = false; // // xrTableRow21 // this.xrTableRow21.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableRow21.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell41, this.xrTableCell44, this.xrTableCell45, this.xrTableCell42, this.xrTableCell46}); this.xrTableRow21.Name = "xrTableRow21"; this.xrTableRow21.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableRow21, "xrTableRow21"); // // xrTableCell41 // this.xrTableCell41.Name = "xrTableCell41"; this.xrTableCell41.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell41, "xrTableCell41"); // // xrTableCell44 // this.xrTableCell44.Name = "xrTableCell44"; this.xrTableCell44.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell44, "xrTableCell44"); // // xrTableCell45 // this.xrTableCell45.Name = "xrTableCell45"; this.xrTableCell45.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell45, "xrTableCell45"); // // xrTableCell42 // this.xrTableCell42.Name = "xrTableCell42"; this.xrTableCell42.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell42, "xrTableCell42"); // // xrTableCell46 // this.xrTableCell46.Name = "xrTableCell46"; this.xrTableCell46.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell46, "xrTableCell46"); // // xrPageBreak1 // resources.ApplyResources(this.xrPageBreak1, "xrPageBreak1"); this.xrPageBreak1.Name = "xrPageBreak1"; // // xrTable2 // resources.ApplyResources(this.xrTable2, "xrTable2"); this.xrTable2.Name = "xrTable2"; this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow6}); this.xrTable2.StylePriority.UseTextAlignment = false; // // xrTableRow6 // this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell37, this.xrTableCell36, this.xrTableCell12}); this.xrTableRow6.Name = "xrTableRow6"; resources.ApplyResources(this.xrTableRow6, "xrTableRow6"); // // xrTableCell37 // this.xrTableCell37.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strDirector")}); this.xrTableCell37.Name = "xrTableCell37"; this.xrTableCell37.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell37, "xrTableCell37"); // // xrTableCell36 // this.xrTableCell36.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strHeadOfDepartment")}); this.xrTableCell36.Name = "xrTableCell36"; this.xrTableCell36.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell36, "xrTableCell36"); // // xrTableCell12 // this.xrTableCell12.Multiline = true; this.xrTableCell12.Name = "xrTableCell12"; this.xrTableCell12.StylePriority.UseFont = false; this.xrTableCell12.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); // // tableCustomSubheader // this.tableCustomSubheader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.tableCustomSubheader, "tableCustomSubheader"); this.tableCustomSubheader.Name = "tableCustomSubheader"; this.tableCustomSubheader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow7, this.xrTableRow9, this.xrTableRow10, this.xrTableRow11, this.xrTableRow12, this.xrTableRow13, this.xrTableRow14, this.xrTableRow15, this.xrTableRow16, this.xrTableRow17, this.xrTableRow18}); this.tableCustomSubheader.StylePriority.UseBorders = false; // // xrTableRow7 // this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell14, this.xrTableCell13}); this.xrTableRow7.Name = "xrTableRow7"; resources.ApplyResources(this.xrTableRow7, "xrTableRow7"); // // xrTableCell14 // this.xrTableCell14.Name = "xrTableCell14"; this.xrTableCell14.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell14, "xrTableCell14"); // // xrTableCell13 // this.xrTableCell13.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strRegNumberAndResultDate")}); this.xrTableCell13.Name = "xrTableCell13"; this.xrTableCell13.StylePriority.UseFont = false; this.xrTableCell13.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell13, "xrTableCell13"); // // xrTableRow9 // this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell15, this.xrTableCell16}); this.xrTableRow9.Name = "xrTableRow9"; resources.ApplyResources(this.xrTableRow9, "xrTableRow9"); // // xrTableCell15 // this.xrTableCell15.Name = "xrTableCell15"; this.xrTableCell15.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell15, "xrTableCell15"); // // xrTableCell16 // this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strDateSampleReceived")}); this.xrTableCell16.Name = "xrTableCell16"; this.xrTableCell16.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell16, "xrTableCell16"); // // xrTableRow10 // this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell17, this.xrTableCell18}); this.xrTableRow10.Name = "xrTableRow10"; resources.ApplyResources(this.xrTableRow10, "xrTableRow10"); // // xrTableCell17 // this.xrTableCell17.Name = "xrTableCell17"; this.xrTableCell17.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell17, "xrTableCell17"); // // xrTableCell18 // this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strSampleOwner")}); this.xrTableCell18.Name = "xrTableCell18"; this.xrTableCell18.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); // // xrTableRow11 // this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell19, this.xrTableCell20}); this.xrTableRow11.Name = "xrTableRow11"; resources.ApplyResources(this.xrTableRow11, "xrTableRow11"); // // xrTableCell19 // this.xrTableCell19.Name = "xrTableCell19"; this.xrTableCell19.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); // // xrTableCell20 // this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strReceivedSampleType")}); this.xrTableCell20.Name = "xrTableCell20"; this.xrTableCell20.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); // // xrTableRow12 // this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell21, this.xrTableCell23}); this.xrTableRow12.Name = "xrTableRow12"; resources.ApplyResources(this.xrTableRow12, "xrTableRow12"); // // xrTableCell21 // this.xrTableCell21.Name = "xrTableCell21"; this.xrTableCell21.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell21, "xrTableCell21"); // // xrTableCell23 // this.xrTableCell23.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strSampleNumber")}); this.xrTableCell23.Name = "xrTableCell23"; this.xrTableCell23.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell23, "xrTableCell23"); // // xrTableRow13 // this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell24, this.xrTableCell25}); this.xrTableRow13.Name = "xrTableRow13"; resources.ApplyResources(this.xrTableRow13, "xrTableRow13"); // // xrTableCell24 // this.xrTableCell24.Name = "xrTableCell24"; this.xrTableCell24.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell24, "xrTableCell24"); // // xrTableCell25 // this.xrTableCell25.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strConditionSampleReceived")}); this.xrTableCell25.Name = "xrTableCell25"; this.xrTableCell25.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell25, "xrTableCell25"); // // xrTableRow14 // this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell26, this.xrTableCell27}); this.xrTableRow14.Name = "xrTableRow14"; resources.ApplyResources(this.xrTableRow14, "xrTableRow14"); // // xrTableCell26 // this.xrTableCell26.Name = "xrTableCell26"; this.xrTableCell26.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell26, "xrTableCell26"); // // xrTableCell27 // this.xrTableCell27.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strPrimaryDiagnosis")}); this.xrTableCell27.Name = "xrTableCell27"; this.xrTableCell27.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell27, "xrTableCell27"); // // xrTableRow15 // this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell28, this.xrTableCell29}); this.xrTableRow15.Name = "xrTableRow15"; resources.ApplyResources(this.xrTableRow15, "xrTableRow15"); // // xrTableCell28 // this.xrTableCell28.Name = "xrTableCell28"; this.xrTableCell28.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell28, "xrTableCell28"); // // xrTableCell29 // this.xrTableCell29.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strResultRecipient")}); this.xrTableCell29.Name = "xrTableCell29"; this.xrTableCell29.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell29, "xrTableCell29"); // // xrTableRow16 // this.xrTableRow16.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell30, this.xrTableCell31}); this.xrTableRow16.Name = "xrTableRow16"; resources.ApplyResources(this.xrTableRow16, "xrTableRow16"); // // xrTableCell30 // this.xrTableCell30.Name = "xrTableCell30"; this.xrTableCell30.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell30, "xrTableCell30"); // // xrTableCell31 // this.xrTableCell31.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strRequestedLaboratoryTests")}); this.xrTableCell31.Name = "xrTableCell31"; this.xrTableCell31.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell31, "xrTableCell31"); // // xrTableRow17 // this.xrTableRow17.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell32, this.xrTableCell33}); this.xrTableRow17.Name = "xrTableRow17"; resources.ApplyResources(this.xrTableRow17, "xrTableRow17"); // // xrTableCell32 // this.xrTableCell32.Name = "xrTableCell32"; this.xrTableCell32.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell32, "xrTableCell32"); // // xrTableCell33 // this.xrTableCell33.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strTestResult")}); this.xrTableCell33.Name = "xrTableCell33"; this.xrTableCell33.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell33, "xrTableCell33"); // // xrTableRow18 // this.xrTableRow18.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell34, this.xrTableCell35}); this.xrTableRow18.Name = "xrTableRow18"; resources.ApplyResources(this.xrTableRow18, "xrTableRow18"); // // xrTableCell34 // this.xrTableCell34.Name = "xrTableCell34"; this.xrTableCell34.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell34, "xrTableCell34"); // // xrTableCell35 // this.xrTableCell35.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strNotes")}); this.xrTableCell35.Name = "xrTableCell35"; this.xrTableCell35.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell35, "xrTableCell35"); // // xrTable1 // resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow8, this.xrTableRow5}); this.xrTable1.StylePriority.UseFont = false; this.xrTable1.StylePriority.UseTextAlignment = false; // // xrTableRow8 // this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell22}); this.xrTableRow8.Name = "xrTableRow8"; resources.ApplyResources(this.xrTableRow8, "xrTableRow8"); // // xrTableCell22 // this.xrTableCell22.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell22.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrPictureBox1, this.HeaderTable}); this.xrTableCell22.Name = "xrTableCell22"; this.xrTableCell22.StylePriority.UseBorders = false; this.xrTableCell22.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell22, "xrTableCell22"); // // xrPictureBox1 // this.xrPictureBox1.Borders = DevExpress.XtraPrinting.BorderSide.None; this.xrPictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("xrPictureBox1.Image"))); resources.ApplyResources(this.xrPictureBox1, "xrPictureBox1"); this.xrPictureBox1.Name = "xrPictureBox1"; this.xrPictureBox1.Sizing = DevExpress.XtraPrinting.ImageSizeMode.StretchImage; this.xrPictureBox1.StylePriority.UseBorders = false; // // HeaderTable // this.HeaderTable.Borders = DevExpress.XtraPrinting.BorderSide.None; resources.ApplyResources(this.HeaderTable, "HeaderTable"); this.HeaderTable.Name = "HeaderTable"; this.HeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1, this.xrTableRow2, this.xrTableRow3, this.xrTableRow4}); this.HeaderTable.StylePriority.UseBorders = false; this.HeaderTable.StylePriority.UseFont = false; this.HeaderTable.StylePriority.UseTextAlignment = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.HeaderCell, this.xrTableCell5}); this.xrTableRow1.Name = "xrTableRow1"; resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); // // HeaderCell // resources.ApplyResources(this.HeaderCell, "HeaderCell"); this.HeaderCell.Name = "HeaderCell"; this.HeaderCell.StylePriority.UseFont = false; this.HeaderCell.StylePriority.UseTextAlignment = false; // // xrTableCell5 // this.xrTableCell5.Name = "xrTableCell5"; this.xrTableCell5.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell2, this.xrTableCell1, this.xrTableCell6}); this.xrTableRow2.Name = "xrTableRow2"; resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); // // xrTableCell2 // this.xrTableCell2.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strSiteName")}); resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); this.xrTableCell2.Name = "xrTableCell2"; this.xrTableCell2.StylePriority.UseFont = false; this.xrTableCell2.StylePriority.UseTextAlignment = false; // // xrTableCell1 // this.xrTableCell1.Name = "xrTableCell1"; this.xrTableCell1.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); // // xrTableCell6 // this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strDate")}); this.xrTableCell6.Name = "xrTableCell6"; this.xrTableCell6.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); // // xrTableRow3 // this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell3, this.locationCell, this.xrTableCell9, this.xrTableCell7}); this.xrTableRow3.Name = "xrTableRow3"; resources.ApplyResources(this.xrTableRow3, "xrTableRow3"); // // xrTableCell3 // this.xrTableCell3.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strSiteAddress")}); this.xrTableCell3.Name = "xrTableCell3"; this.xrTableCell3.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); // // locationCell // this.locationCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strPhone")}); this.locationCell.Name = "locationCell"; this.locationCell.StylePriority.UseFont = false; resources.ApplyResources(this.locationCell, "locationCell"); // // xrTableCell9 // this.xrTableCell9.Name = "xrTableCell9"; this.xrTableCell9.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); // // xrTableCell7 // this.xrTableCell7.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strForm")}); this.xrTableCell7.Name = "xrTableCell7"; this.xrTableCell7.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); // // xrTableRow4 // this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell4, this.OrganizationPrefixCell, this.OrganizationCell, this.xrTableCell10, this.xrTableCell8}); this.xrTableRow4.Name = "xrTableRow4"; resources.ApplyResources(this.xrTableRow4, "xrTableRow4"); // // xrTableCell4 // this.xrTableCell4.Name = "xrTableCell4"; this.xrTableCell4.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); // // OrganizationPrefixCell // this.OrganizationPrefixCell.Name = "OrganizationPrefixCell"; this.OrganizationPrefixCell.StylePriority.UseFont = false; this.OrganizationPrefixCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.OrganizationPrefixCell, "OrganizationPrefixCell"); // // OrganizationCell // this.OrganizationCell.Name = "OrganizationCell"; this.OrganizationCell.StylePriority.UseFont = false; this.OrganizationCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.OrganizationCell, "OrganizationCell"); // // xrTableCell10 // this.xrTableCell10.Name = "xrTableCell10"; this.xrTableCell10.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); // // xrTableCell8 // this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "LaboratoryResearchResult.strVersion")}); this.xrTableCell8.Name = "xrTableCell8"; this.xrTableCell8.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); // // xrTableRow5 // this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell11}); this.xrTableRow5.Name = "xrTableRow5"; resources.ApplyResources(this.xrTableRow5, "xrTableRow5"); // // xrTableCell11 // resources.ApplyResources(this.xrTableCell11, "xrTableCell11"); this.xrTableCell11.Name = "xrTableCell11"; this.xrTableCell11.StylePriority.UseBorders = false; this.xrTableCell11.StylePriority.UseFont = false; this.xrTableCell11.StylePriority.UseTextAlignment = false; // // m_DataAdapter // this.m_DataAdapter.ClearBeforeFill = true; // // m_DataSet // this.m_DataSet.DataSetName = "VetLabReportDataSet"; this.m_DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // LaboratoryResearchReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.VetReport}); resources.ApplyResources(this, "$this"); this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.Version = "14.1"; this.Controls.SetChildIndex(this.VetReport, 0); this.Controls.SetChildIndex(this.ReportHeader, 0); this.Controls.SetChildIndex(this.PageFooter, 0); this.Controls.SetChildIndex(this.PageHeader, 0); this.Controls.SetChildIndex(this.Detail, 0); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableCustomSubheader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailReportBand VetReport; private DevExpress.XtraReports.UI.DetailBand VetDetail; private DevExpress.XtraReports.UI.ReportHeaderBand VetReportHeader; private DevExpress.XtraReports.UI.XRTable HeaderTable; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell HeaderCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow3; private DevExpress.XtraReports.UI.XRTableCell locationCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow4; private DevExpress.XtraReports.UI.XRTableCell OrganizationCell; private EIDSS.Reports.Parameterized.Human.GG.DataSet.LaboratoryResearchDataSet m_DataSet; private EIDSS.Reports.Parameterized.Human.GG.DataSet.LaboratoryResearchDataSetTableAdapters.LaboratoryResearchResultAdapter m_DataAdapter; private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter; private DevExpress.XtraReports.UI.XRTableCell OrganizationPrefixCell; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRPictureBox xrPictureBox1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell22; private DevExpress.XtraReports.UI.XRTableRow xrTableRow5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; private DevExpress.XtraReports.UI.XRTable xrTable2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTable tableCustomSubheader; private DevExpress.XtraReports.UI.XRTableRow xrTableRow7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell14; private DevExpress.XtraReports.UI.XRTableCell xrTableCell13; private DevExpress.XtraReports.UI.XRTableRow xrTableRow9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell16; private DevExpress.XtraReports.UI.XRTableRow xrTableRow10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableRow xrTableRow11; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRTableRow xrTableRow12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell21; private DevExpress.XtraReports.UI.XRTableCell xrTableCell23; private DevExpress.XtraReports.UI.XRTableRow xrTableRow13; private DevExpress.XtraReports.UI.XRTableCell xrTableCell24; private DevExpress.XtraReports.UI.XRTableCell xrTableCell25; private DevExpress.XtraReports.UI.XRTableRow xrTableRow14; private DevExpress.XtraReports.UI.XRTableCell xrTableCell26; private DevExpress.XtraReports.UI.XRTableCell xrTableCell27; private DevExpress.XtraReports.UI.XRTableRow xrTableRow15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell28; private DevExpress.XtraReports.UI.XRTableCell xrTableCell29; private DevExpress.XtraReports.UI.XRTableRow xrTableRow16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell30; private DevExpress.XtraReports.UI.XRTableCell xrTableCell31; private DevExpress.XtraReports.UI.XRTableRow xrTableRow17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell32; private DevExpress.XtraReports.UI.XRTableCell xrTableCell33; private DevExpress.XtraReports.UI.XRTableRow xrTableRow18; private DevExpress.XtraReports.UI.XRTableCell xrTableCell34; private DevExpress.XtraReports.UI.XRTableCell xrTableCell35; private DevExpress.XtraReports.UI.XRTableCell xrTableCell37; private DevExpress.XtraReports.UI.XRTableCell xrTableCell36; private DevExpress.XtraReports.UI.XRTable xrTable4; private DevExpress.XtraReports.UI.XRTableRow xrTableRow20; private DevExpress.XtraReports.UI.XRTableCell xrTableCell43; private DevExpress.XtraReports.UI.XRTableRow xrTableRow21; private DevExpress.XtraReports.UI.XRTableCell xrTableCell41; private DevExpress.XtraReports.UI.XRTableCell xrTableCell44; private DevExpress.XtraReports.UI.XRTableCell xrTableCell45; private DevExpress.XtraReports.UI.XRTableCell xrTableCell42; private DevExpress.XtraReports.UI.XRTableCell xrTableCell46; private DevExpress.XtraReports.UI.XRPageBreak xrPageBreak1; private DevExpress.XtraReports.UI.XRTable xrTable3; private DevExpress.XtraReports.UI.XRTableRow xrTableRow22; private DevExpress.XtraReports.UI.XRTableCell xrTableCell39; private DevExpress.XtraReports.UI.XRTableCell xrTableCell40; private DevExpress.XtraReports.UI.XRTableCell xrTableCell47; private DevExpress.XtraReports.UI.XRTableCell xrTableCell48; private DevExpress.XtraReports.UI.XRTableCell xrTableCell49; } }
//--------------------------------------------------------------------- // <copyright file="JsonReader.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Provides a reader implementaion for Json format // </summary> // // @owner [....] //--------------------------------------------------------------------- namespace System.Data.Services.Serializers { #region Namespaces. using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; #endregion Namespaces. /// <summary>Json text reader.</summary> /// <remarks>Does not dispose the reader, since we don't own the underlying stream.</remarks> internal sealed class JsonReader { /// <summary>Compiled Regex for DateTime Format.</summary> private static readonly Regex DateTimeFormat = new Regex(@"^/Date\((?<ticks>-?[0-9]+)\)/", RegexOptions.Compiled); /// <summary>Maximum recursion limit on reader.</summary> private const int RecursionLimit = 200; /// <summary> Reader to reader text into </summary> private readonly StreamReader reader; /// <summary>Depth of recursion.</summary> private int recursionDepth; /// <summary> /// Creates a new instance of Json reader which readers the json text /// from the given reader /// </summary> /// <param name="reader">text reader from which json payload needs to be read. /// Does not dispose the reader, since we don't own the underlying stream.</param> public JsonReader(StreamReader reader) { Debug.Assert(reader != null, "reader != null"); this.reader = reader; } /// <summary> /// Converts the given value into the right type /// </summary> /// <returns>returns the clr object instance which </returns> public object ReadValue() { this.RecurseEnter(); object value = null; bool allowNull = false; char ch = this.PeekNextSignificantCharacter(); if (ch == '[') { value = this.ReadArray(); } else if (ch == '{') { value = this.ReadObject(); } else if ((ch == '\'') || (ch == '"')) { bool hasLeadingSlash; string s = this.ReadString(out hasLeadingSlash); value = s; // may be overwritten with a DateTime if ends up being a date/time // Atlas format for date/time if (hasLeadingSlash) { Match match = DateTimeFormat.Match(s); if (match.Success) { string ticksStr = match.Groups["ticks"].Value; long ticks; if (long.TryParse(ticksStr, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out ticks)) { // The javascript ticks start from 1/1/1970 but FX DateTime ticks start from 1/1/0001 DateTime dateTime = new DateTime(ticks * 10000 + JsonWriter.DatetimeMinTimeTicks, DateTimeKind.Utc); value = dateTime; } } } } else if (Char.IsDigit(ch) || (ch == '-') || (ch == '.')) { value = this.ReadNumber(); } else if ((ch == 't') || (ch == 'f')) { value = this.ReadBoolean(); } else if (ch == 'n') { this.ReadNull(); allowNull = true; } if ((value == null) && (allowNull == false)) { throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_InvalidContent); } this.RecurseLeave(); // if there is junk data at the end of the stream ex. {...}junk // then an exception will be thrown. if (this.recursionDepth == 0) { // at the end of the stream if (this.PeekNextSignificantCharacter() != '\0') { throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_InvalidContent); } } return value; } /// <summary> /// Gets the next character from the reader. This function moves the enumerator by 1 position /// </summary> /// <returns>the next charater from the current reader position</returns> private char ReadNextCharacter() { int result = this.reader.Read(); if (result < 0) { throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_InvalidContent); } Debug.Assert(result <= char.MaxValue, "result <= char.MaxValue"); return (char)result; } /// <summary> /// peeks the next character from the reader. This does not move the current reader position. /// </summary> /// <returns>the next character from the current reader position</returns> private char PeekNextCharacter() { if (this.reader.EndOfStream) { return '\0'; } int result = this.reader.Peek(); Debug.Assert(result >= 0, "Peek must not return value < 0 since we are not at EndOfStream yet."); Debug.Assert(result <= char.MaxValue, "result <= char.MaxValue"); return (char)result; } /// <summary> /// Returns the next count characters from the reader's current position /// </summary> /// <param name="count">number of characters to return</param> /// <returns>string consisting of next count characters</returns> private string GetCharacters(int count) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < count; i++) { char ch = this.ReadNextCharacter(); stringBuilder.Append(ch); } return stringBuilder.ToString(); } /// <summary> /// Sets the readers position to the next significant character position /// </summary> /// <returns>returns the next significant character without changing the current position of the reader</returns> private char PeekNextSignificantCharacter() { char ch = this.PeekNextCharacter(); while ((ch != '\0') && Char.IsWhiteSpace(ch)) { this.ReadNextCharacter(); ch = this.PeekNextCharacter(); } return ch; } /// <summary> /// Converts the given text into an arrayList /// </summary> /// <returns>returns the arraylist containing the list of objects</returns> private ArrayList ReadArray() { ArrayList array = new ArrayList(); // Consume the '[' this.ReadNextCharacter(); while (true) { char ch = this.PeekNextSignificantCharacter(); if (ch == '\0') { throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_InvalidContent); } if (ch == ']') { this.ReadNextCharacter(); return array; } if (array.Count != 0) { if (ch != ',') { throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_MissingArrayMemberSeperator); } else { this.ReadNextCharacter(); } } object item = this.ReadValue(); array.Add(item); } } /// <summary> /// Reads the boolean value /// </summary> /// <returns>returns the boolean value as read from the reader</returns> private bool ReadBoolean() { string s = this.ReadName(/* allowQuotes */ false); if (s != null) { if (s.Equals(XmlConstants.XmlTrueLiteral, StringComparison.Ordinal)) { return true; } else if (s.Equals(XmlConstants.XmlFalseLiteral, StringComparison.Ordinal)) { return false; } } throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_InvalidKeyword(s)); } /// <summary> /// Reads the name string from the reader /// </summary> /// <param name="allowQuotes">true, if you want to allow quotes, otherwise false</param> /// <returns>string name value</returns> private string ReadName(bool allowQuotes) { char ch = this.PeekNextSignificantCharacter(); if ((ch == '"') || (ch == '\'')) { if (allowQuotes) { return this.ReadString(); } } else { StringBuilder sb = new StringBuilder(); while (true) { ch = this.PeekNextCharacter(); if ((ch == '_') || Char.IsLetterOrDigit(ch) || ch == '$') { this.ReadNextCharacter(); sb.Append(ch); } else { return sb.ToString(); } } } return null; } /// <summary> /// Reads the null literal from the reader /// </summary> private void ReadNull() { string s = this.ReadName(/* allowQuotes */ false); if (s == null) { throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_MissingMemberName); } else if (!s.Equals("null", StringComparison.Ordinal)) { throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_InvalidKeyword(s)); } } /// <summary>Reads the number from the reader.</summary> /// <returns>reads the clr number object</returns> private object ReadNumber() { char ch = this.ReadNextCharacter(); StringBuilder sb = new StringBuilder(); sb.Append(ch); while (true) { ch = this.PeekNextSignificantCharacter(); if (Char.IsDigit(ch) || (ch == '.') || (ch == 'E') || (ch == 'e') || (ch == '-') || (ch == '+')) { this.ReadNextCharacter(); sb.Append(ch); } else { break; } } string s = sb.ToString(); Double doubleValue; int intValue; // We will first try and convert this int32. If this succeeds, great. Otherwise, we will try // and convert this into a double. if (Int32.TryParse(s, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out intValue)) { return intValue; } else if (Double.TryParse(s, NumberStyles.Float, NumberFormatInfo.InvariantInfo, out doubleValue)) { return doubleValue; } throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_InvalidContent); } /// <summary> /// Reads the object from the reader /// </summary> /// <returns>returns hashtable containing the list of property names and values</returns> private JsonObjectRecords ReadObject() { JsonObjectRecords record = new JsonObjectRecords(); // Consume the '{' this.ReadNextCharacter(); while (true) { char ch = this.PeekNextSignificantCharacter(); if (ch == '\0') { // Unterminated Object literal throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_InvalidContent); } if (ch == '}') { this.ReadNextCharacter(); return record; } if (record.Count != 0) { if (ch != ',') { throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_MissingMemberSeperator); } else { this.ReadNextCharacter(); } } string name = this.ReadName(/* allowQuotes */ true); if (String.IsNullOrEmpty(name)) { throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_InvalidJsonNameSpecifiedOrExtraComma); } ch = this.PeekNextSignificantCharacter(); // Unexpected name/value pair syntax in object literal if (ch != ':') { throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_MissingNameValueSeperator(name)); } else { this.ReadNextCharacter(); } object item = this.ReadValue(); record.Add(name, item); } } /// <summary> /// Read the string value from the reader /// </summary> /// <returns>returns the string value read from the reader</returns> private string ReadString() { bool dummy; return this.ReadString(out dummy); } /// <summary> /// Read the string value from the reader /// </summary> /// <param name="hasLeadingSlash">out parameter indicating whether the string has a leading slash or not</param> /// <returns>returns the string value read from the reader</returns> private string ReadString(out bool hasLeadingSlash) { char endQuoteCharacter = this.ReadNextCharacter(); char ch = this.ReadNextCharacter(); hasLeadingSlash = (ch == '\\') ? true : false; StringBuilder sb = new StringBuilder(); while (true) { if (ch == '\\') { ch = this.ReadNextCharacter(); // From 4627, section 2.5: Strings, here's the list of characters that we should be escaping if (ch == 'u') { string unicodeSequence = this.GetCharacters(4); Debug.Assert(unicodeSequence != null, "unicodeSequence != null"); ch = (char)Int32.Parse(unicodeSequence, NumberStyles.HexNumber, CultureInfo.InvariantCulture); sb.Append(ch); } else if (ch == 'b') { sb.Append('\b'); } else if (ch == 'f') { sb.Append('\f'); } else if (ch == 'n') { sb.Append('\n'); } else if (ch == 'r') { sb.Append('\r'); } else if (ch == 't') { sb.Append('\t'); } else if (ch == '\\' || ch == '\"' || ch == '/' || ch == '\'') { sb.Append(ch); } else { throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_InvalidJsonUnrecognizedEscapeSequence); } } else if (ch == endQuoteCharacter) { return sb.ToString(); } else { sb.Append(ch); } ch = this.ReadNextCharacter(); } } /// <summary>Marks the fact that a recursive method was entered, and checks that the depth is allowed.</summary> private void RecurseEnter() { WebUtil.RecurseEnter(RecursionLimit, ref this.recursionDepth); } /// <summary>Marks the fact that a recursive method is leaving..</summary> private void RecurseLeave() { WebUtil.RecurseLeave(ref this.recursionDepth); } /// <summary> /// Represent one Json Object. /// </summary> /// <remarks>This class honors the original ordering of the inner elements of the json object.</remarks> public class JsonObjectRecords { /// <summary> /// A list of keys in the object /// </summary> private List<String> orderedKeys; /// <summary> /// The actual storage of key-value pair /// </summary> private Dictionary<String, Object> entries; /// <summary> /// Constructor /// </summary> public JsonObjectRecords() { this.orderedKeys = new List<string>(); this.entries = new Dictionary<string, object>(EqualityComparer<String>.Default); } /// <summary> /// Number of elements in this object /// </summary> public int Count { get { return this.orderedKeys.Count; } } /// <summary> /// A list of keys in the object, in the order which they are deserialized /// </summary> public List<String> OrderedKeys { get { return this.orderedKeys; } } /// <summary> /// The actual storage of key-value pair /// </summary> public Dictionary<String, Object> Entries { get { return this.entries; } } /// <summary> /// Add a new element into the object /// </summary> /// <param name="key">Key</param> /// <param name="value">Value</param> public void Add(String key, Object value) { // Json Object used to be a hashtable // It will automatically resolve duplicated keys // however, for that scenario, we must not update the order table if (!this.entries.ContainsKey(key)) { this.orderedKeys.Add(key); } this.entries[key] = value; } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.Firebasestorage.v1beta { /// <summary>The Firebasestorage Service.</summary> public class FirebasestorageService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1beta"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public FirebasestorageService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public FirebasestorageService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Projects = new ProjectsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "firebasestorage"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://firebasestorage.googleapis.com/"; #else "https://firebasestorage.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://firebasestorage.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Cloud Storage for Firebase API.</summary> public class Scope { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary>View and administer all your Firebase data and settings</summary> public static string Firebase = "https://www.googleapis.com/auth/firebase"; } /// <summary>Available OAuth 2.0 scope constants for use with the Cloud Storage for Firebase API.</summary> public static class ScopeConstants { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary>View and administer all your Firebase data and settings</summary> public const string Firebase = "https://www.googleapis.com/auth/firebase"; } /// <summary>Gets the Projects resource.</summary> public virtual ProjectsResource Projects { get; } } /// <summary>A base abstract class for Firebasestorage requests.</summary> public abstract class FirebasestorageBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new FirebasestorageBaseServiceRequest instance.</summary> protected FirebasestorageBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes Firebasestorage parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "projects" collection of methods.</summary> public class ProjectsResource { private const string Resource = "projects"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProjectsResource(Google.Apis.Services.IClientService service) { this.service = service; Buckets = new BucketsResource(service); } /// <summary>Gets the Buckets resource.</summary> public virtual BucketsResource Buckets { get; } /// <summary>The "buckets" collection of methods.</summary> public class BucketsResource { private const string Resource = "buckets"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public BucketsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Links a Google Cloud Storage bucket to a Firebase project.</summary> /// <param name="body">The body of the request.</param> /// <param name="bucket"> /// Required. Resource name of the bucket, mirrors the ID of the underlying Google Cloud Storage bucket, /// `projects/{project_number}/buckets/{bucket_id}`. /// </param> public virtual AddFirebaseRequest AddFirebase(Google.Apis.Firebasestorage.v1beta.Data.AddFirebaseRequest body, string bucket) { return new AddFirebaseRequest(service, body, bucket); } /// <summary>Links a Google Cloud Storage bucket to a Firebase project.</summary> public class AddFirebaseRequest : FirebasestorageBaseServiceRequest<Google.Apis.Firebasestorage.v1beta.Data.Bucket> { /// <summary>Constructs a new AddFirebase request.</summary> public AddFirebaseRequest(Google.Apis.Services.IClientService service, Google.Apis.Firebasestorage.v1beta.Data.AddFirebaseRequest body, string bucket) : base(service) { Bucket = bucket; Body = body; InitParameters(); } /// <summary> /// Required. Resource name of the bucket, mirrors the ID of the underlying Google Cloud Storage bucket, /// `projects/{project_number}/buckets/{bucket_id}`. /// </summary> [Google.Apis.Util.RequestParameterAttribute("bucket", Google.Apis.Util.RequestParameterType.Path)] public virtual string Bucket { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Firebasestorage.v1beta.Data.AddFirebaseRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "addFirebase"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta/{+bucket}:addFirebase"; /// <summary>Initializes AddFirebase parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("bucket", new Google.Apis.Discovery.Parameter { Name = "bucket", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/buckets/[^/]+$", }); } } /// <summary>Gets a single linked storage bucket.</summary> /// <param name="name"> /// Required. Resource name of the bucket, mirrors the ID of the underlying Google Cloud Storage bucket, /// `projects/{project_number}/buckets/{bucket_id}`. /// </param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Gets a single linked storage bucket.</summary> public class GetRequest : FirebasestorageBaseServiceRequest<Google.Apis.Firebasestorage.v1beta.Data.Bucket> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary> /// Required. Resource name of the bucket, mirrors the ID of the underlying Google Cloud Storage bucket, /// `projects/{project_number}/buckets/{bucket_id}`. /// </summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta/{+name}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/buckets/[^/]+$", }); } } /// <summary>Lists the linked storage buckets for a project.</summary> /// <param name="parent"> /// Required. Resource name of the parent Firebase project, `projects/{project_number}`. /// </param> public virtual ListRequest List(string parent) { return new ListRequest(service, parent); } /// <summary>Lists the linked storage buckets for a project.</summary> public class ListRequest : FirebasestorageBaseServiceRequest<Google.Apis.Firebasestorage.v1beta.Data.ListBucketsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service) { Parent = parent; InitParameters(); } /// <summary> /// Required. Resource name of the parent Firebase project, `projects/{project_number}`. /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary> /// The maximum number of buckets to return. If not set, the server will use a reasonable default. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary> /// A page token, received from a previous `ListBuckets` call. Provide this to retrieve the subsequent /// page. When paginating, all other parameters provided to `ListBuckets` must match the call that /// provided the page token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta/{+parent}/buckets"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+$", }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Unlinks a linked Google Cloud Storage bucket from a Firebase project.</summary> /// <param name="body">The body of the request.</param> /// <param name="bucket"> /// Required. Resource name of the bucket, mirrors the ID of the underlying Google Cloud Storage bucket, /// `projects/{project_number}/buckets/{bucket_id}`. /// </param> public virtual RemoveFirebaseRequest RemoveFirebase(Google.Apis.Firebasestorage.v1beta.Data.RemoveFirebaseRequest body, string bucket) { return new RemoveFirebaseRequest(service, body, bucket); } /// <summary>Unlinks a linked Google Cloud Storage bucket from a Firebase project.</summary> public class RemoveFirebaseRequest : FirebasestorageBaseServiceRequest<Google.Apis.Firebasestorage.v1beta.Data.Empty> { /// <summary>Constructs a new RemoveFirebase request.</summary> public RemoveFirebaseRequest(Google.Apis.Services.IClientService service, Google.Apis.Firebasestorage.v1beta.Data.RemoveFirebaseRequest body, string bucket) : base(service) { Bucket = bucket; Body = body; InitParameters(); } /// <summary> /// Required. Resource name of the bucket, mirrors the ID of the underlying Google Cloud Storage bucket, /// `projects/{project_number}/buckets/{bucket_id}`. /// </summary> [Google.Apis.Util.RequestParameterAttribute("bucket", Google.Apis.Util.RequestParameterType.Path)] public virtual string Bucket { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Firebasestorage.v1beta.Data.RemoveFirebaseRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "removeFirebase"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta/{+bucket}:removeFirebase"; /// <summary>Initializes RemoveFirebase parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("bucket", new Google.Apis.Discovery.Parameter { Name = "bucket", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/buckets/[^/]+$", }); } } } } } namespace Google.Apis.Firebasestorage.v1beta.Data { /// <summary>The request used to link a Google Cloud Storage bucket to a Firebase project.</summary> public class AddFirebaseRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A storage bucket and its relation to a parent Firebase project.</summary> public class Bucket : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Output only. Location of the storage bucket.</summary> [Newtonsoft.Json.JsonPropertyAttribute("location")] public virtual string Location { get; set; } /// <summary>Resource name of the bucket.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary> /// Output only. Represents whether a bucket is being moved to a new location, in which case reconciling is set /// to true. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("reconciling")] public virtual System.Nullable<bool> Reconciling { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical /// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc /// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON /// object `{}`. /// </summary> public class Empty : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Metadata for MigrateLocationDestructively LRO.</summary> public class GoogleFirebaseStorageControlplaneV1alphaMigrateLocationDestructivelyMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The time the LRO was created.</summary> [Newtonsoft.Json.JsonPropertyAttribute("createTime")] public virtual object CreateTime { get; set; } /// <summary>The time the LRO was last updated.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lastUpdateTime")] public virtual object LastUpdateTime { get; set; } /// <summary>The current state of the migration.</summary> [Newtonsoft.Json.JsonPropertyAttribute("state")] public virtual string State { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Metadata for MigrateLocationDestructively LRO.</summary> public class GoogleFirebaseStorageControlplaneV1betaMigrateLocationDestructivelyMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The time the LRO was created.</summary> [Newtonsoft.Json.JsonPropertyAttribute("createTime")] public virtual object CreateTime { get; set; } /// <summary>The time the LRO was last updated.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lastUpdateTime")] public virtual object LastUpdateTime { get; set; } /// <summary>The current state of the migration.</summary> [Newtonsoft.Json.JsonPropertyAttribute("state")] public virtual string State { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The response returned by `ListBuckets`.</summary> public class ListBucketsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The list of linked buckets.</summary> [Newtonsoft.Json.JsonPropertyAttribute("buckets")] public virtual System.Collections.Generic.IList<Bucket> Buckets { get; set; } /// <summary> /// A token that can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no /// subsequent pages. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The request used to unlink a Google Cloud Storage bucket from a Firebase project.</summary> public class RemoveFirebaseRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Scenes; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; using OpenSim.Tests.Common.Setup; namespace OpenSim.Region.Framework.Scenes.Tests { /// <summary> /// Basic scene object tests (create, read and delete but not update). /// </summary> [TestFixture] public class SceneObjectBasicTests { /// <summary> /// Test adding an object to a scene. /// </summary> [Test] public void TestAddSceneObject() { TestHelper.InMethod(); Scene scene = SceneSetupHelpers.SetupScene(); string objName = "obj1"; UUID objUuid = new UUID("00000000-0000-0000-0000-000000000001"); SceneObjectPart part = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = objName, UUID = objUuid }; Assert.That(scene.AddNewSceneObject(new SceneObjectGroup(part), false), Is.True); SceneObjectPart retrievedPart = scene.GetSceneObjectPart(objUuid); //m_log.Debug("retrievedPart : {0}", retrievedPart); // If the parts have the same UUID then we will consider them as one and the same Assert.That(retrievedPart.Name, Is.EqualTo(objName)); Assert.That(retrievedPart.UUID, Is.EqualTo(objUuid)); } [Test] /// <summary> /// It shouldn't be possible to add a scene object if one with that uuid already exists in the scene. /// </summary> public void TestAddExistingSceneObjectUuid() { TestHelper.InMethod(); Scene scene = SceneSetupHelpers.SetupScene(); string obj1Name = "Alfred"; string obj2Name = "Betty"; UUID objUuid = new UUID("00000000-0000-0000-0000-000000000001"); SceneObjectPart part1 = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = obj1Name, UUID = objUuid }; Assert.That(scene.AddNewSceneObject(new SceneObjectGroup(part1), false), Is.True); SceneObjectPart part2 = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = obj2Name, UUID = objUuid }; Assert.That(scene.AddNewSceneObject(new SceneObjectGroup(part2), false), Is.False); SceneObjectPart retrievedPart = scene.GetSceneObjectPart(objUuid); //m_log.Debug("retrievedPart : {0}", retrievedPart); // If the parts have the same UUID then we will consider them as one and the same Assert.That(retrievedPart.Name, Is.EqualTo(obj1Name)); Assert.That(retrievedPart.UUID, Is.EqualTo(objUuid)); } /// <summary> /// Test deleting an object from a scene. /// </summary> [Test] public void TestDeleteSceneObject() { TestHelper.InMethod(); TestScene scene = SceneSetupHelpers.SetupScene(); SceneObjectPart part = SceneSetupHelpers.AddSceneObject(scene); scene.DeleteSceneObject(part.ParentGroup, false); SceneObjectPart retrievedPart = scene.GetSceneObjectPart(part.LocalId); Assert.That(retrievedPart, Is.Null); } /// <summary> /// Test deleting an object asynchronously /// </summary> [Test] public void TestDeleteSceneObjectAsync() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); UUID agentId = UUID.Parse("00000000-0000-0000-0000-000000000001"); TestScene scene = SceneSetupHelpers.SetupScene(); // Turn off the timer on the async sog deleter - we'll crank it by hand for this test. AsyncSceneObjectGroupDeleter sogd = scene.SceneObjectGroupDeleter; sogd.Enabled = false; SceneObjectPart part = SceneSetupHelpers.AddSceneObject(scene); IClientAPI client = SceneSetupHelpers.AddRootAgent(scene, agentId); scene.DeRezObjects(client, new System.Collections.Generic.List<uint>() { part.LocalId }, UUID.Zero, DeRezAction.Delete, UUID.Zero); SceneObjectPart retrievedPart = scene.GetSceneObjectPart(part.LocalId); Assert.That(retrievedPart, Is.Not.Null); sogd.InventoryDeQueueAndDelete(); SceneObjectPart retrievedPart2 = scene.GetSceneObjectPart(part.LocalId); Assert.That(retrievedPart2, Is.Null); } /// <summary> /// Test deleting an object asynchronously to user inventory. /// </summary> //[Test] //public void TestDeleteSceneObjectAsyncToUserInventory() //{ // TestHelper.InMethod(); // //log4net.Config.XmlConfigurator.Configure(); // UUID agentId = UUID.Parse("00000000-0000-0000-0000-000000000001"); // string myObjectName = "Fred"; // TestScene scene = SceneSetupHelpers.SetupScene(); // SceneObjectPart part = SceneSetupHelpers.AddSceneObject(scene, myObjectName); // Assert.That( // scene.CommsManager.UserAdminService.AddUser( // "Bob", "Hoskins", "test", "test@test.com", 1000, 1000, agentId), // Is.EqualTo(agentId)); // IClientAPI client = SceneSetupHelpers.AddRootAgent(scene, agentId); // CachedUserInfo userInfo = scene.CommsManager.UserProfileCacheService.GetUserDetails(agentId); // Assert.That(userInfo, Is.Not.Null); // Assert.That(userInfo.RootFolder, Is.Not.Null); // SceneSetupHelpers.DeleteSceneObjectAsync(scene, part, DeRezAction.Take, userInfo.RootFolder.ID, client); // // Check that we now have the taken part in our inventory // Assert.That(myObjectName, Is.EqualTo(userInfo.RootFolder.FindItemByPath(myObjectName).Name)); // // Check that the taken part has actually disappeared // SceneObjectPart retrievedPart = scene.GetSceneObjectPart(part.LocalId); // Assert.That(retrievedPart, Is.Null); //} /// <summary> /// Changing a scene object uuid changes the root part uuid. This is a valid operation if the object is not /// in a scene and is useful if one wants to supply a UUID directly rather than use the one generated by /// OpenSim. /// </summary> [Test] public void TestChangeSceneObjectUuid() { string rootPartName = "rootpart"; UUID rootPartUuid = new UUID("00000000-0000-0000-0000-000000000001"); string childPartName = "childPart"; UUID childPartUuid = new UUID("00000000-0000-0000-0001-000000000000"); SceneObjectPart rootPart = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = rootPartName, UUID = rootPartUuid }; SceneObjectPart linkPart = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = childPartName, UUID = childPartUuid }; SceneObjectGroup sog = new SceneObjectGroup(rootPart); sog.AddPart(linkPart); Assert.That(sog.UUID, Is.EqualTo(rootPartUuid)); Assert.That(sog.RootPart.UUID, Is.EqualTo(rootPartUuid)); Assert.That(sog.Parts.Length, Is.EqualTo(2)); UUID newRootPartUuid = new UUID("00000000-0000-0000-0000-000000000002"); sog.UUID = newRootPartUuid; Assert.That(sog.UUID, Is.EqualTo(newRootPartUuid)); Assert.That(sog.RootPart.UUID, Is.EqualTo(newRootPartUuid)); Assert.That(sog.Parts.Length, Is.EqualTo(2)); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System.Diagnostics; using System.Threading.Tasks; using Microsoft.PythonTools.Intellisense; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Repl; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.Text.Classification; using TestUtilities; using TestUtilities.Python; namespace IronPythonTests { [TestClass] public class IronPythonReplEvaluatorTests { static IronPythonReplEvaluatorTests() { AssertListener.Initialize(); } protected virtual PythonVersion PythonVersion { get { return PythonPaths.IronPython27; } } private PythonInteractiveEvaluator Evaluator { get { PythonVersion.AssertInstalled(); return new PythonInteractiveEvaluator(PythonToolsTestUtilities.CreateMockServiceProvider()) { Configuration = new LaunchConfiguration(PythonVersion.Configuration) }; } } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void IronPythonModuleName() { using (var replEval = Evaluator) { var replWindow = new MockReplWindow(replEval); replEval._Initialize(replWindow).Wait(); replWindow.ClearScreen(); var execute = replEval.ExecuteText("__name__"); execute.Wait(); Assert.IsTrue(execute.Result.IsSuccessful); Assert.AreEqual(replWindow.Output, "'__main__'\n"); replWindow.ClearScreen(); } } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void IronPythonSignatures() { using (var replEval = Evaluator) { var replWindow = new MockReplWindow(replEval); replEval._Initialize(replWindow).Wait(); var execute = replEval.ExecuteText("from System import Array"); execute.Wait(); Assert.IsTrue(execute.Result.IsSuccessful); OverloadDoc[] sigs = null; for (int retries = 0; retries < 5 && sigs == null; retries += 1) { sigs = replEval.GetSignatureDocumentation("Array[int]"); } Assert.IsNotNull(sigs, "GetSignatureDocumentation timed out"); Assert.AreEqual(1, sigs.Length); Assert.AreEqual("Array[int](: int)\r\n", sigs[0].Documentation); } } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void IronPythonCommentInput() { // http://pytools.codeplex.com/workitem/649 using (var replEval = Evaluator) { var replWindow = new MockReplWindow(replEval); replEval._Initialize(replWindow).Wait(); var execute = replEval.ExecuteText("#fob\n1+2"); execute.Wait(); Assert.IsTrue(execute.Result.IsSuccessful); } } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void ConsoleWriteLineTest() { // http://pytools.codeplex.com/workitem/649 using (var replEval = Evaluator) { var replWindow = new MockReplWindow(replEval); replEval._Initialize(replWindow).Wait(); var execute = replEval.ExecuteText("import System"); execute.Wait(); Assert.IsTrue(execute.Result.IsSuccessful); replWindow.ClearScreen(); execute = replEval.ExecuteText("System.Console.WriteLine(42)"); execute.Wait(); Assert.AreEqual(replWindow.Output, "42\n"); replWindow.ClearScreen(); Assert.IsTrue(execute.Result.IsSuccessful); execute = replEval.ExecuteText("System.Console.Write(42)"); execute.Wait(); Assert.IsTrue(execute.Result.IsSuccessful); Assert.AreEqual(replWindow.Output, "42"); } } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void GenericMethodCompletions() { // http://pytools.codeplex.com/workitem/661 using (var replEval = Evaluator) { var replWindow = new MockReplWindow(replEval); replEval._Initialize(replWindow).Wait(); var execute = replEval.ExecuteText("from System.Threading.Tasks import Task"); execute.Wait(); Assert.IsTrue(execute.Result.IsSuccessful); replWindow.ClearScreen(); execute = replEval.ExecuteText("def func1(): print 'hello world'\r\n\r\n"); execute.Wait(); replWindow.ClearScreen(); Assert.IsTrue(execute.Result.IsSuccessful); execute = replEval.ExecuteText("t = Task.Factory.StartNew(func1)"); execute.Wait(); Assert.IsTrue(execute.Result.IsSuccessful); replWindow.TextView.TextBuffer.Properties.AddProperty(typeof(VsProjectAnalyzer), replEval.Analyzer); CompletionResult[] names = null; for (int retries = 0; retries < 5 && names == null; retries += 1) { names = replEval.GetMemberNames("t"); } Assert.IsNotNull(names, "GetMemberNames call timed out"); foreach (var name in names) { Debug.WriteLine(name.Name); } } } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public async Task NoTraceFunction() { // http://pytools.codeplex.com/workitem/662 using (var replEval = Evaluator) { var replWindow = new MockReplWindow(replEval); await replEval._Initialize(replWindow); var execute = await replEval.ExecuteText("import sys"); Assert.IsTrue(execute.IsSuccessful); replWindow.ClearScreen(); await replEval.ExecuteText("print '[%s]' % sys.gettrace(),"); Assert.AreEqual("[None]", replWindow.Output); replWindow.ClearScreen(); } } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void CommentFollowedByBlankLine() { // http://pytools.codeplex.com/workitem/659 using (var replEval = Evaluator) { var replWindow = new MockReplWindow(replEval); replEval._Initialize(replWindow).Wait(); var execute = replEval.ExecuteText("# fob\r\n\r\n \r\n\t\t\r\na = 42"); execute.Wait(); Assert.IsTrue(execute.Result.IsSuccessful); replWindow.ClearScreen(); } } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void AttachSupportMultiThreaded() { // http://pytools.codeplex.com/workitem/663 using (var replEval = Evaluator) { var replWindow = new MockReplWindow(replEval); replEval._Initialize(replWindow).Wait(); var code = new[] { "import threading", "def sayHello():\r\n pass", "t1 = threading.Thread(target=sayHello)", "t1.start()", "t2 = threading.Thread(target=sayHello)", "t2.start()" }; foreach (var line in code) { var execute = replEval.ExecuteText(line); execute.Wait(); Assert.IsTrue(execute.Result.IsSuccessful); } replWindow.ClearScreen(); var finalExecute = replEval.ExecuteText("42"); finalExecute.Wait(); Assert.IsTrue(finalExecute.Result.IsSuccessful); Assert.AreEqual(replWindow.Output, "42\n"); } } } [TestClass] public class IronPythonx64ReplEvaluatorTests : IronPythonReplEvaluatorTests { protected override PythonVersion PythonVersion { get { return PythonPaths.IronPython27_x64; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeDom { using System.Diagnostics; using System; using System.Collections; using System.Runtime.InteropServices; using System.Globalization; /// <devdoc> /// <para> /// Manages a collection of <see cref='Microsoft.CodeDom.CodeNamespaceImport'/> objects. /// </para> /// </devdoc> [ // ClassInterface(ClassInterfaceType.AutoDispatch), ComVisible(true), // Serializable, ] public class CodeNamespaceImportCollection : IList { private ArrayList _data = new ArrayList(); private Hashtable _keys = new Hashtable(StringComparer.OrdinalIgnoreCase); /// <devdoc> /// <para> /// Indexer method that provides collection access. /// </para> /// </devdoc> public CodeNamespaceImport this[int index] { get { return ((CodeNamespaceImport)_data[index]); } set { _data[index] = value; SyncKeys(); } } /// <devdoc> /// <para> /// Gets or sets the number of namespaces in the collection. /// </para> /// </devdoc> public int Count { get { return _data.Count; } } /// <internalonly/> bool IList.IsReadOnly { get { return false; } } /// <internalonly/> bool IList.IsFixedSize { get { return false; } } /// <devdoc> /// <para> /// Adds a namespace import to the collection. /// </para> /// </devdoc> public void Add(CodeNamespaceImport value) { if (!_keys.ContainsKey(value.Namespace)) { _keys[value.Namespace] = value; _data.Add(value); } } /// <devdoc> /// <para> /// Adds a set of <see cref='Microsoft.CodeDom.CodeNamespaceImport'/> objects to the collection. /// </para> /// </devdoc> public void AddRange(CodeNamespaceImport[] value) { if (value == null) { throw new ArgumentNullException("value"); } foreach (CodeNamespaceImport c in value) { Add(c); } } /// <devdoc> /// <para> /// Clears the collection of members. /// </para> /// </devdoc> public void Clear() { _data.Clear(); _keys.Clear(); } /// <devdoc> /// <para> /// Makes the collection of keys synchronised with the data. /// </para> /// </devdoc> private void SyncKeys() { _keys = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (CodeNamespaceImport c in this) { _keys[c.Namespace] = c; } } /// <devdoc> /// <para> /// Gets an enumerator that enumerates the collection members. /// </para> /// </devdoc> public IEnumerator GetEnumerator() { return _data.GetEnumerator(); } /// <internalonly/> object IList.this[int index] { get { return this[index]; } set { this[index] = (CodeNamespaceImport)value; SyncKeys(); } } /// <internalonly/> int ICollection.Count { get { return Count; } } /// <internalonly/> bool ICollection.IsSynchronized { get { return false; } } /// <internalonly/> object ICollection.SyncRoot { get { return null; } } /// <internalonly/> void ICollection.CopyTo(Array array, int index) { _data.CopyTo(array, index); } /// <internalonly/> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <internalonly/> int IList.Add(object value) { return _data.Add((CodeNamespaceImport)value); } /// <internalonly/> void IList.Clear() { Clear(); } /// <internalonly/> bool IList.Contains(object value) { return _data.Contains(value); } /// <internalonly/> int IList.IndexOf(object value) { return _data.IndexOf((CodeNamespaceImport)value); } /// <internalonly/> void IList.Insert(int index, object value) { _data.Insert(index, (CodeNamespaceImport)value); SyncKeys(); } /// <internalonly/> void IList.Remove(object value) { _data.Remove((CodeNamespaceImport)value); SyncKeys(); } /// <internalonly/> void IList.RemoveAt(int index) { _data.RemoveAt(index); SyncKeys(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.Extensions.Localization { public class QueryStringRequestCultureProviderTest { [Fact] public async Task GetCultureInfoFromQueryString() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = new List<CultureInfo> { new CultureInfo("ar-SA") }, SupportedUICultures = new List<CultureInfo> { new CultureInfo("ar-YE") } }); app.Run(context => { var requestCultureFeature = context.Features.Get<IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture; Assert.Equal("ar-SA", requestCulture.Culture.Name); Assert.Equal("ar-YE", requestCulture.UICulture.Name); return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-SA&ui-culture=ar-YE"); } } [Fact] public async Task GetDefaultCultureInfoIfCultureKeysAreMissing() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US") }); app.Run(context => { var requestCultureFeature = context.Features.Get<IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture; Assert.Equal("en-US", requestCulture.Culture.Name); Assert.Equal("en-US", requestCulture.UICulture.Name); return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page"); } } [Fact] public async Task GetDefaultCultureInfoIfCultureIsInSupportedCultureList() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = new List<CultureInfo> { new CultureInfo("ar-SA") }, SupportedUICultures = new List<CultureInfo> { new CultureInfo("ar-SA") } }); app.Run(context => { var requestCultureFeature = context.Features.Get<IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture; Assert.Equal("en-US", requestCulture.Culture.Name); return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-XY&ui-culture=ar-SA"); } } [Fact] public async Task GetDefaultCultureInfoIfUICultureIsNotInSupportedList() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = new List<CultureInfo> { new CultureInfo("ar-SA") }, SupportedUICultures = new List<CultureInfo> { new CultureInfo("ar-SA") } }); app.Run(context => { var requestCultureFeature = context.Features.Get<IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture; Assert.Equal("en-US", requestCulture.UICulture.Name); return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-SA&ui-culture=ar-XY"); } } [Fact] public async Task GetSameCultureInfoIfCultureKeyIsMissing() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = new List<CultureInfo> { new CultureInfo("ar-SA") }, SupportedUICultures = new List<CultureInfo> { new CultureInfo("ar-SA") } }); app.Run(context => { var requestCultureFeature = context.Features.Get<IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture; Assert.Equal("ar-SA", requestCulture.Culture.Name); Assert.Equal("ar-SA", requestCulture.UICulture.Name); return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?ui-culture=ar-SA"); } } [Fact] public async Task GetSameCultureInfoIfUICultureKeyIsMissing() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = new List<CultureInfo> { new CultureInfo("ar-SA") }, SupportedUICultures = new List<CultureInfo> { new CultureInfo("ar-SA") } }); app.Run(context => { var requestCultureFeature = context.Features.Get<IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture; Assert.Equal("ar-SA", requestCulture.Culture.Name); Assert.Equal("ar-SA", requestCulture.UICulture.Name); return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-SA"); } } [Fact] public async Task GetCultureInfoFromQueryStringWithCustomKeys() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { var options = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = new List<CultureInfo> { new CultureInfo("ar-SA") }, SupportedUICultures = new List<CultureInfo> { new CultureInfo("ar-YE") } }; var provider = new QueryStringRequestCultureProvider(); provider.QueryStringKey = "c"; provider.UIQueryStringKey = "uic"; options.RequestCultureProviders.Insert(0, provider); app.UseRequestLocalization(options); app.Run(context => { var requestCultureFeature = context.Features.Get<IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture; Assert.Equal("ar-SA", requestCulture.Culture.Name); Assert.Equal("ar-YE", requestCulture.UICulture.Name); return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?c=ar-SA&uic=ar-YE"); } } [Fact] public async Task GetTheRightCultureInfoRegardlessOfCultureNameCasing() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { var options = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = new List<CultureInfo> { new CultureInfo("FR") }, SupportedUICultures = new List<CultureInfo> { new CultureInfo("FR") } }; var provider = new QueryStringRequestCultureProvider(); provider.QueryStringKey = "c"; provider.UIQueryStringKey = "uic"; options.RequestCultureProviders.Insert(0, provider); app.UseRequestLocalization(options); app.Run(context => { var requestCultureFeature = context.Features.Get<IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture; Assert.Equal("fr", requestCulture.Culture.ToString()); Assert.Equal("fr", requestCulture.UICulture.ToString()); return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?c=FR&uic=FR"); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; using Microsoft.Azure.Management.Sql.Models; namespace Microsoft.Azure.Management.Sql.Models { /// <summary> /// Represents the properties of an Azure SQL Database. /// </summary> public partial class DatabaseProperties { private string _collation; /// <summary> /// Optional. Gets the collation of the Azure SQL Database. /// </summary> public string Collation { get { return this._collation; } set { this._collation = value; } } private string _createMode; /// <summary> /// Optional. Gets the create mode for this database. /// </summary> public string CreateMode { get { return this._createMode; } set { this._createMode = value; } } private DateTime _creationDate; /// <summary> /// Optional. Gets the creation date of the Azure SQL Database. /// </summary> public DateTime CreationDate { get { return this._creationDate; } set { this._creationDate = value; } } private string _currentServiceObjectiveId; /// <summary> /// Optional. Gets the current Service Level Objective Id of the Azure /// SQL Database. This is the Id of the Service Level Objective that /// is currently active. /// </summary> public string CurrentServiceObjectiveId { get { return this._currentServiceObjectiveId; } set { this._currentServiceObjectiveId = value; } } private string _databaseId; /// <summary> /// Optional. Gets the Id of the Azure SQL Database. /// </summary> public string DatabaseId { get { return this._databaseId; } set { this._databaseId = value; } } private string _defaultSecondaryLocation; /// <summary> /// Optional. Gets the default secondary region for this database. /// </summary> public string DefaultSecondaryLocation { get { return this._defaultSecondaryLocation; } set { this._defaultSecondaryLocation = value; } } private DateTime _earliestRestoreDate; /// <summary> /// Optional. Gets the recovery period starte date of the Azure SQL /// Database. This records the start date and time when recovery is /// available for this Azure SQL Database. /// </summary> public DateTime EarliestRestoreDate { get { return this._earliestRestoreDate; } set { this._earliestRestoreDate = value; } } private string _edition; /// <summary> /// Optional. Gets the edition of the Azure SQL Database. The /// DatabaseEditions enumeration contains all the valid editions. /// </summary> public string Edition { get { return this._edition; } set { this._edition = value; } } private string _elasticPoolName; /// <summary> /// Optional. Gets the name of the Azure SQL Database Elastic Pool the /// database is in. /// </summary> public string ElasticPoolName { get { return this._elasticPoolName; } set { this._elasticPoolName = value; } } private long _maxSizeBytes; /// <summary> /// Optional. Gets the max size of the Azure SQL Database expressed in /// bytes. /// </summary> public long MaxSizeBytes { get { return this._maxSizeBytes; } set { this._maxSizeBytes = value; } } private string _requestedServiceObjectiveId; /// <summary> /// Optional. Gets the configured Service Level Objective Id of the /// Azure SQL Database. This is the Service Level Objective that is /// being applied to the Azure SQL Database. /// </summary> public string RequestedServiceObjectiveId { get { return this._requestedServiceObjectiveId; } set { this._requestedServiceObjectiveId = value; } } private string _requestedServiceObjectiveName; /// <summary> /// Optional. Gets the name of the configured Service Level Objective /// of the Azure SQL Database. This is the Service Level Objective /// that is being applied to the Azure SQL Database. /// </summary> public string RequestedServiceObjectiveName { get { return this._requestedServiceObjectiveName; } set { this._requestedServiceObjectiveName = value; } } private IList<Schema> _schemas; /// <summary> /// Optional. Gets the schemas from this database. /// </summary> public IList<Schema> Schemas { get { return this._schemas; } set { this._schemas = value; } } private string _serviceObjective; /// <summary> /// Optional. Gets the Service Level Objective of the Azure SQL /// Database. /// </summary> public string ServiceObjective { get { return this._serviceObjective; } set { this._serviceObjective = value; } } private IList<ServiceTierAdvisor> _serviceTierAdvisors; /// <summary> /// Optional. Gets the list of service tier advisors for this database. /// Expanded property /// </summary> public IList<ServiceTierAdvisor> ServiceTierAdvisors { get { return this._serviceTierAdvisors; } set { this._serviceTierAdvisors = value; } } private string _status; /// <summary> /// Optional. Gets the status of the Azure SQL Database. /// </summary> public string Status { get { return this._status; } set { this._status = value; } } private UpgradeHint _upgradeHint; /// <summary> /// Optional. Gets the upgrade hint for this database. /// </summary> public UpgradeHint UpgradeHint { get { return this._upgradeHint; } set { this._upgradeHint = value; } } /// <summary> /// Initializes a new instance of the DatabaseProperties class. /// </summary> public DatabaseProperties() { this.Schemas = new LazyList<Schema>(); this.ServiceTierAdvisors = new LazyList<ServiceTierAdvisor>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This class represents settings specified by de jure or // de facto standards for a particular country/region. In // contrast to CultureInfo, the RegionInfo does not represent // preferences of the user and does not depend on the user's // language or culture. // // //////////////////////////////////////////////////////////////////////////// using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization { public class RegionInfo { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Variables. // // // Name of this region (ie: es-US): serialized, the field used for deserialization // internal String _name; // // The CultureData instance that we are going to read data from. // internal CultureData _cultureData; // // The RegionInfo for our current region // internal static volatile RegionInfo s_currentRegionInfo; //////////////////////////////////////////////////////////////////////// // // RegionInfo Constructors // // Note: We prefer that a region be created with a full culture name (ie: en-US) // because otherwise the native strings won't be right. // // In Silverlight we enforce that RegionInfos must be created with a full culture name // //////////////////////////////////////////////////////////////////////// public RegionInfo(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) //The InvariantCulture has no matching region { throw new ArgumentException(SR.Argument_NoRegionInvariantCulture, nameof(name)); } Contract.EndContractBlock(); // // For CoreCLR we only want the region names that are full culture names // _cultureData = CultureData.GetCultureDataForRegion(name, true); if (_cultureData == null) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, SR.Argument_InvalidCultureName, name), nameof(name)); // Not supposed to be neutral if (_cultureData.IsNeutralCulture) throw new ArgumentException(SR.Format(SR.Argument_InvalidNeutralRegionName, name), nameof(name)); SetName(name); } public RegionInfo(int culture) { if (culture == CultureInfo.LOCALE_INVARIANT) //The InvariantCulture has no matching region { throw new ArgumentException(SR.Argument_NoRegionInvariantCulture); } if (culture == CultureInfo.LOCALE_NEUTRAL) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), nameof(culture)); } if (culture == CultureInfo.LOCALE_CUSTOM_DEFAULT) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CustomCultureCannotBePassedByNumber, culture), nameof(culture)); } _cultureData = CultureData.GetCultureData(culture, true); _name = _cultureData.SREGIONNAME; if (_cultureData.IsNeutralCulture) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), nameof(culture)); } } internal RegionInfo(CultureData cultureData) { _cultureData = cultureData; _name = _cultureData.SREGIONNAME; } private void SetName(string name) { // Use the name of the region we found _name = _cultureData.SREGIONNAME; } [OnSerializing] private void OnSerializing(StreamingContext ctx) { } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { _cultureData = CultureData.GetCultureData(_name, true); if (_cultureData == null) { throw new ArgumentException( String.Format(CultureInfo.CurrentCulture, SR.Argument_InvalidCultureName, _name), "_name"); } _name = _cultureData.SREGIONNAME; } //////////////////////////////////////////////////////////////////////// // // GetCurrentRegion // // This instance provides methods based on the current user settings. // These settings are volatile and may change over the lifetime of the // thread. // //////////////////////////////////////////////////////////////////////// public static RegionInfo CurrentRegion { get { RegionInfo temp = s_currentRegionInfo; if (temp == null) { temp = new RegionInfo(CultureInfo.CurrentCulture._cultureData); // Need full name for custom cultures temp._name = temp._cultureData.SREGIONNAME; s_currentRegionInfo = temp; } return temp; } } //////////////////////////////////////////////////////////////////////// // // GetName // // Returns the name of the region (ie: en-US) // //////////////////////////////////////////////////////////////////////// public virtual String Name { get { Debug.Assert(_name != null, "Expected RegionInfo._name to be populated already"); return (_name); } } //////////////////////////////////////////////////////////////////////// // // GetEnglishName // // Returns the name of the region in English. (ie: United States) // //////////////////////////////////////////////////////////////////////// public virtual String EnglishName { get { return (_cultureData.SENGCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetDisplayName // // Returns the display name (localized) of the region. (ie: United States // if the current UI language is en-US) // //////////////////////////////////////////////////////////////////////// public virtual String DisplayName { get { return (_cultureData.SLOCALIZEDCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetNativeName // // Returns the native name of the region. (ie: Deutschland) // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// public virtual String NativeName { get { return (_cultureData.SNATIVECOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // TwoLetterISORegionName // // Returns the two letter ISO region name (ie: US) // //////////////////////////////////////////////////////////////////////// public virtual String TwoLetterISORegionName { get { return (_cultureData.SISO3166CTRYNAME); } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterISORegionName // // Returns the three letter ISO region name (ie: USA) // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterISORegionName { get { return (_cultureData.SISO3166CTRYNAME2); } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterWindowsRegionName // // Returns the three letter windows region name (ie: USA) // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterWindowsRegionName { get { // ThreeLetterWindowsRegionName is really same as ThreeLetterISORegionName return ThreeLetterISORegionName; } } //////////////////////////////////////////////////////////////////////// // // IsMetric // // Returns true if this region uses the metric measurement system // //////////////////////////////////////////////////////////////////////// public virtual bool IsMetric { get { int value = _cultureData.IMEASURE; return (value == 0); } } public virtual int GeoId { get { return (_cultureData.IGEOID); } } //////////////////////////////////////////////////////////////////////// // // CurrencyEnglishName // // English name for this region's currency, ie: Swiss Franc // //////////////////////////////////////////////////////////////////////// public virtual string CurrencyEnglishName { get { return (_cultureData.SENGLISHCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // CurrencyNativeName // // Native name for this region's currency, ie: Schweizer Franken // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// public virtual string CurrencyNativeName { get { return (_cultureData.SNATIVECURRENCY); } } //////////////////////////////////////////////////////////////////////// // // CurrencySymbol // // Currency Symbol for this locale, ie: Fr. or $ // //////////////////////////////////////////////////////////////////////// public virtual String CurrencySymbol { get { return (_cultureData.SCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // ISOCurrencySymbol // // ISO Currency Symbol for this locale, ie: CHF // //////////////////////////////////////////////////////////////////////// public virtual String ISOCurrencySymbol { get { return (_cultureData.SINTLSYMBOL); } } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same RegionInfo as the current instance. // // RegionInfos are considered equal if and only if they have the same name // (ie: en-US) // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { RegionInfo that = value as RegionInfo; if (that != null) { return this.Name.Equals(that.Name); } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CultureInfo. The hash code is guaranteed to be the same for RegionInfo // A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.Name.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns the name of the Region, ie: es-US // //////////////////////////////////////////////////////////////////////// public override String ToString() { return (Name); } } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.IO; using System.Net; using System.Runtime; using System.Threading; using System.Globalization; using System.Threading.Tasks; using Orleans.Runtime.Configuration; namespace Orleans.Runtime.Host { /// <summary> /// Allows programmatically hosting an Orleans silo in the curent app domain. /// </summary> public class SiloHost : MarshalByRefObject, IDisposable { /// <summary> Name of this silo. </summary> public string Name { get; set; } /// <summary> Type of this silo - either <c>Primary</c> or <c>Secondary</c>. </summary> public Silo.SiloType Type { get; set; } /// <summary> /// Configuration file used for this silo. /// Changing this after the silo has started (when <c>ConfigLoaded == true</c>) will have no effect. /// </summary> public string ConfigFileName { get; set; } /// <summary> /// Directory to use for the trace log file written by this silo. /// </summary> /// <remarks> /// <para> /// The values of <c>null</c> or <c>"None"</c> mean no log file will be written by Orleans Logger manager. /// </para> /// <para> /// When deciding The values of <c>null</c> or <c>"None"</c> mean no log file will be written by Orleans Logger manager. /// </para> /// </remarks> public string TraceFilePath { get; set; } /// <summary> Configuration data for the Orleans system. </summary> public ClusterConfiguration Config { get; set; } /// <summary> Configuration data for this silo. </summary> public NodeConfiguration NodeConfig { get; private set; } /// <summary> /// Silo Debug flag. /// If set to <c>true</c> then additional diagnostic info will be written during silo startup. /// </summary> public bool Debug { get; set; } /// <summary> /// Whether the silo config has been loaded and initializing it's runtime config. /// </summary> /// <remarks> /// Changes to silo config properties will be ignored after <c>ConfigLoaded == true</c>. /// </remarks> public bool ConfigLoaded { get; private set; } /// <summary> Deployment Id (if any) for the cluster this silo is running in. </summary> public string DeploymentId { get; set; } /// <summary> /// Verbose flag. /// If set to <c>true</c> then additional status and diagnostics info will be written during silo startup. /// </summary> public int Verbose { get; set; } /// <summary> Whether this silo started successfully and is currently running. </summary> public bool IsStarted { get; private set; } private TraceLogger logger; private Silo orleans; private EventWaitHandle startupEvent; private EventWaitHandle shutdownEvent; private bool disposed; /// <summary> /// Constructor /// </summary> /// <param name="siloName">Name of this silo.</param> public SiloHost(string siloName) { Name = siloName; Type = Silo.SiloType.Secondary; // Default IsStarted = false; } /// <summary> Constructor </summary> /// <param name="siloName">Name of this silo.</param> /// <param name="config">Silo config that will be used to initialize this silo.</param> public SiloHost(string siloName, ClusterConfiguration config) : this(siloName) { SetSiloConfig(config); } /// <summary> Constructor </summary> /// <param name="siloName">Name of this silo.</param> /// <param name="configFile">Silo config file that will be used to initialize this silo.</param> public SiloHost(string siloName, FileInfo configFile) : this(siloName) { ConfigFileName = configFile.FullName; var config = new ClusterConfiguration(); config.LoadFromFile(ConfigFileName); SetSiloConfig(config); } /// <summary> /// Initialize this silo. /// </summary> public void InitializeOrleansSilo() { #if DEBUG AssemblyLoaderUtils.EnableAssemblyLoadTracing(); #endif try { if (!ConfigLoaded) LoadOrleansConfig(); orleans = new Silo(Name, Type, Config); } catch (Exception exc) { ReportStartupError(exc); orleans = null; } } /// <summary> /// Uninitialize this silo. /// </summary> public void UnInitializeOrleansSilo() { Utils.SafeExecute(UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler); Utils.SafeExecute(TraceLogger.UnInitialize); } /// <summary> /// Start this silo. /// </summary> /// <returns></returns> public bool StartOrleansSilo() { try { if (string.IsNullOrEmpty(Thread.CurrentThread.Name)) Thread.CurrentThread.Name = this.GetType().Name; if (orleans != null) { var shutdownEventName = Config.Defaults.SiloShutdownEventName ?? Name + "-Shutdown"; logger.Info(ErrorCode.SiloShutdownEventName, "Silo shutdown event name: {0}", shutdownEventName); bool createdNew; shutdownEvent = new EventWaitHandle(false, EventResetMode.ManualReset, shutdownEventName, out createdNew); if (!createdNew) { logger.Info(ErrorCode.SiloShutdownEventOpened, "Opened existing shutdown event. Setting the event {0}", shutdownEventName); } else { logger.Info(ErrorCode.SiloShutdownEventCreated, "Created and set shutdown event {0}", shutdownEventName); } // Start silo orleans.Start(); // Wait for the shutdown event, and trigger a graceful shutdown if we receive it. var shutdownThread = new Thread( o => { shutdownEvent.WaitOne(); logger.Info(ErrorCode.SiloShutdownEventReceived, "Received a shutdown event. Starting graceful shutdown."); orleans.Shutdown(); }); shutdownThread.Start(); var startupEventName = Name; logger.Info(ErrorCode.SiloStartupEventName, "Silo startup event name: {0}", startupEventName); startupEvent = new EventWaitHandle(true, EventResetMode.ManualReset, startupEventName, out createdNew); if (!createdNew) { logger.Info(ErrorCode.SiloStartupEventOpened, "Opened existing startup event. Setting the event {0}", startupEventName); startupEvent.Set(); } else { logger.Info(ErrorCode.SiloStartupEventCreated, "Created and set startup event {0}", startupEventName); } logger.Info(ErrorCode.SiloStarted, "Silo {0} started successfully", Name); IsStarted = true; } else { throw new InvalidOperationException("Cannot start silo " + this.Name + " due to prior initialization error"); } } catch (Exception exc) { ReportStartupError(exc); orleans = null; IsStarted = false; return false; } return true; } /// <summary> /// Stop this silo. /// </summary> public void StopOrleansSilo() { IsStarted = false; if (orleans != null) orleans.Stop(); } /// <summary> /// Gracefully shutdown this silo. /// </summary> public void ShutdownOrleansSilo() { IsStarted = false; if (orleans != null) orleans.Shutdown(); } /// <summary> /// Wait for this silo to shutdown. /// </summary> /// <remarks> /// Note: This method call will block execution of current thread, /// and will not return control back to the caller until the silo is shutdown. /// </remarks> public void WaitForOrleansSiloShutdown() { WaitForOrleansSiloShutdownImpl(); } /// <summary> /// Wait for this silo to shutdown or to be stopped with provided cancellation token. /// </summary> /// <param name="cancellationToken">Cancellation token.</param> /// <remarks> /// Note: This method call will block execution of current thread, /// and will not return control back to the caller until the silo is shutdown or /// an external request for cancellation has been issued. /// </remarks> public void WaitForOrleansSiloShutdown(CancellationToken cancellationToken) { WaitForOrleansSiloShutdownImpl(cancellationToken); } /// <summary> /// Set the DeploymentId for this silo, /// as well as the connection string to use the silo system data, /// such as the cluster membership table.. /// </summary> /// <param name="deploymentId">DeploymentId this silo is part of.</param> /// <param name="connectionString">Azure connection string to use the silo system data.</param> public void SetDeploymentId(string deploymentId, string connectionString) { logger.Info(ErrorCode.SiloSetDeploymentId, "Setting Deployment Id to {0} and data connection string to {1}", deploymentId, ConfigUtilities.RedactConnectionStringInfo(connectionString)); Config.Globals.DeploymentId = deploymentId; Config.Globals.DataConnectionString = connectionString; } /// <summary> /// Set the main endpoint address for this silo, /// plus the silo generation value to be used to distinguish this silo instance /// from any previous silo instances previously running on this endpoint. /// </summary> /// <param name="endpoint">IP address and port of the main inter-silo socket connection.</param> /// <param name="generation">Generation number for this silo.</param> public void SetSiloEndpoint(IPEndPoint endpoint, int generation) { logger.Info(ErrorCode.SiloSetSiloEndpoint, "Setting silo endpoint address to {0}:{1}", endpoint, generation); NodeConfig.HostNameOrIPAddress = endpoint.Address.ToString(); NodeConfig.Port = endpoint.Port; NodeConfig.Generation = generation; } /// <summary> /// Set the gateway proxy endpoint address for this silo. /// </summary> /// <param name="endpoint">IP address of the gateway socket connection.</param> public void SetProxyEndpoint(IPEndPoint endpoint) { logger.Info(ErrorCode.SiloSetProxyEndpoint, "Setting silo proxy endpoint address to {0}", endpoint); NodeConfig.ProxyGatewayEndpoint = endpoint; } /// <summary> /// Set the seed node endpoint address to be used by silo. /// </summary> /// <param name="endpoint">IP address of the inter-silo connection socket on the seed node silo.</param> public void SetSeedNodeEndpoint(IPEndPoint endpoint) { logger.Info(ErrorCode.SiloSetSeedNode, "Adding seed node address={0} port={1}", endpoint.Address, endpoint.Port); Config.Globals.SeedNodes.Clear(); Config.Globals.SeedNodes.Add(endpoint); } /// <summary> /// Set the set of seed node endpoint addresses to be used by silo. /// </summary> /// <param name="endpoints">IP addresses of the inter-silo connection socket on the seed node silos.</param> public void SetSeedNodeEndpoints(IPEndPoint[] endpoints) { // Add all silos as seed nodes Config.Globals.SeedNodes.Clear(); foreach (IPEndPoint endpoint in endpoints) { logger.Info(ErrorCode.SiloAddSeedNode, "Adding seed node address={0} port={1}", endpoint.Address, endpoint.Port); Config.Globals.SeedNodes.Add(endpoint); } } /// <summary> /// Set the endpoint addresses for the Primary silo (if any). /// This silo may be Primary, in which case this address should match /// this silo's inter-silo connection socket address. /// </summary> /// <param name="endpoint">The IP address for the inter-silo connection socket on the Primary silo.</param> public void SetPrimaryNodeEndpoint(IPEndPoint endpoint) { logger.Info(ErrorCode.SiloSetPrimaryNode, "Setting primary node address={0} port={1}", endpoint.Address, endpoint.Port); Config.PrimaryNode = endpoint; } /// <summary> /// Set the type of this silo. Default is Secondary. /// </summary> /// <param name="siloType">Type of this silo.</param> public void SetSiloType(Silo.SiloType siloType) { logger.Info(ErrorCode.SiloSetSiloType, "Setting silo type {0}", siloType); Type = siloType; } /// <summary> /// Set the membership liveness type to be used by this silo. /// </summary> /// <param name="livenessType">Liveness type for this silo</param> public void SetSiloLivenessType(GlobalConfiguration.LivenessProviderType livenessType) { logger.Info(ErrorCode.SetSiloLivenessType, "Setting silo Liveness Provider Type={0}", livenessType); Config.Globals.LivenessType = livenessType; } /// <summary> /// Set the reminder service type to be used by this silo. /// </summary> /// <param name="reminderType">Reminder service type for this silo</param> public void SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType reminderType) { logger.Info(ErrorCode.SetSiloLivenessType, "Setting silo Reminder Service Provider Type={0}", reminderType); Config.Globals.SetReminderServiceType(reminderType); } /// <summary> /// Set expected deployment size. /// </summary> /// <param name="size">The expected deployment size.</param> public void SetExpectedClusterSize(int size) { logger.Info(ErrorCode.SetSiloLivenessType, "Setting Expected Cluster Size to={0}", size); Config.Globals.ExpectedClusterSize = size; } /// <summary> /// Report an error during silo startup. /// </summary> /// <remarks> /// Information on the silo startup issue will be logged to any attached Loggers, /// then a timestamped StartupError text file will be written to /// the current working directory (if possible). /// </remarks> /// <param name="exc">Exception which caused the silo startup issue.</param> public void ReportStartupError(Exception exc) { if (string.IsNullOrWhiteSpace(Name)) Name = "Silo"; var errMsg = "ERROR starting Orleans silo name=" + Name + " Exception=" + TraceLogger.PrintException(exc); if (logger != null) logger.Error(ErrorCode.Runtime_Error_100105, errMsg, exc); // Dump Startup error to a log file var now = DateTime.UtcNow; const string dateFormat = "yyyy-MM-dd-HH.mm.ss.fffZ"; var dateString = now.ToString(dateFormat, CultureInfo.InvariantCulture); var startupLog = Name + "-StartupError-" + dateString + ".txt"; try { File.AppendAllText(startupLog, dateString + "Z" + Environment.NewLine + errMsg); } catch (Exception exc2) { if (logger != null) logger.Error(ErrorCode.Runtime_Error_100106, "Error writing log file " + startupLog, exc2); } TraceLogger.Flush(); } /// <summary> /// Search for and load the config file for this silo. /// </summary> public void LoadOrleansConfig() { if (ConfigLoaded) return; var config = Config ?? new ClusterConfiguration(); try { if (ConfigFileName == null) config.StandardLoad(); else config.LoadFromFile(ConfigFileName); } catch (Exception ex) { throw new AggregateException("Error loading Config file: " + ex.Message, ex); } SetSiloConfig(config); } /// <summary> /// Allows silo config to be programmatically set. /// </summary> /// <param name="config">Configuration data for this silo & cluster.</param> private void SetSiloConfig(ClusterConfiguration config) { Config = config; if (Verbose > 0) Config.Defaults.DefaultTraceLevel = (Logger.Severity.Verbose - 1 + Verbose); if (!String.IsNullOrEmpty(DeploymentId)) Config.Globals.DeploymentId = DeploymentId; if (string.IsNullOrWhiteSpace(Name)) throw new ArgumentException("SiloName not defined - cannot initialize config"); NodeConfig = Config.GetConfigurationForNode(Name); Type = NodeConfig.IsPrimaryNode ? Silo.SiloType.Primary : Silo.SiloType.Secondary; if (TraceFilePath != null) { var traceFileName = Config.GetConfigurationForNode(Name).TraceFileName; if (traceFileName != null && !Path.IsPathRooted(traceFileName)) Config.GetConfigurationForNode(Name).TraceFileName = TraceFilePath + "\\" + traceFileName; } ConfigLoaded = true; InitializeLogger(config.GetConfigurationForNode(Name)); } private void InitializeLogger(NodeConfiguration nodeCfg) { TraceLogger.Initialize(nodeCfg); logger = TraceLogger.GetLogger("OrleansSiloHost", TraceLogger.LoggerType.Runtime); } /// <summary> /// Helper to wait for this silo to shutdown or to be stopped via a cancellation token. /// </summary> /// <param name="cancellationToken">Optional cancellation token.</param> /// <remarks> /// Note: This method call will block execution of current thread, /// and will not return control back to the caller until the silo is shutdown or /// an external request for cancellation has been issued. /// </remarks> private void WaitForOrleansSiloShutdownImpl(CancellationToken? cancellationToken = null) { if (!IsStarted) throw new InvalidOperationException("Cannot wait for silo " + this.Name + " since it was not started successfully previously."); if (startupEvent != null) startupEvent.Reset(); else throw new InvalidOperationException("Cannot wait for silo " + this.Name + " due to prior initialization error"); if (orleans != null) { // Intercept cancellation to initiate silo stop if (cancellationToken.HasValue) cancellationToken.Value.Register(HandleExternalCancellation); orleans.SiloTerminatedEvent.WaitOne(); } else throw new InvalidOperationException("Cannot wait for silo " + this.Name + " due to prior initialization error"); } /// <summary> /// Handle the silo stop request coming from an external cancellation token. /// </summary> private void HandleExternalCancellation() { // Try to perform gracefull shutdown of Silo when we a cancellation request has been made logger.Info(ErrorCode.SiloStopping, "External cancellation triggered, starting to shutdown silo."); ShutdownOrleansSilo(); } /// <summary> /// Called when this silo is being Disposed by .NET runtime. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { if (startupEvent != null) { startupEvent.Dispose(); startupEvent = null; } this.IsStarted = false; } } disposed = true; } } }
using System; using System.Runtime.InteropServices; namespace Godot { /// <summary> /// 2D axis-aligned bounding box using integers. Rect2i consists of a position, a size, and /// several utility functions. It is typically used for fast overlap tests. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Rect2i : IEquatable<Rect2i> { private Vector2i _position; private Vector2i _size; /// <summary> /// Beginning corner. Typically has values lower than End. /// </summary> /// <value>Directly uses a private field.</value> public Vector2i Position { get { return _position; } set { _position = value; } } /// <summary> /// Size from Position to End. Typically all components are positive. /// If the size is negative, you can use <see cref="Abs"/> to fix it. /// </summary> /// <value>Directly uses a private field.</value> public Vector2i Size { get { return _size; } set { _size = value; } } /// <summary> /// Ending corner. This is calculated as <see cref="Position"/> plus /// <see cref="Size"/>. Setting this value will change the size. /// </summary> /// <value>Getting is equivalent to `value = Position + Size`, setting is equivalent to `Size = value - Position`.</value> public Vector2i End { get { return _position + _size; } set { _size = value - _position; } } /// <summary> /// The area of this rect. /// </summary> /// <value>Equivalent to <see cref="GetArea()"/>.</value> public int Area { get { return GetArea(); } } /// <summary> /// Returns a Rect2i with equivalent position and size, modified so that /// the top-left corner is the origin and width and height are positive. /// </summary> /// <returns>The modified rect.</returns> public Rect2i Abs() { Vector2i end = End; Vector2i topLeft = new Vector2i(Mathf.Min(_position.x, end.x), Mathf.Min(_position.y, end.y)); return new Rect2i(topLeft, _size.Abs()); } /// <summary> /// Returns the intersection of this Rect2i and `b`. /// </summary> /// <param name="b">The other rect.</param> /// <returns>The clipped rect.</returns> public Rect2i Clip(Rect2i b) { var newRect = b; if (!Intersects(newRect)) { return new Rect2i(); } newRect._position.x = Mathf.Max(b._position.x, _position.x); newRect._position.y = Mathf.Max(b._position.y, _position.y); Vector2i bEnd = b._position + b._size; Vector2i end = _position + _size; newRect._size.x = Mathf.Min(bEnd.x, end.x) - newRect._position.x; newRect._size.y = Mathf.Min(bEnd.y, end.y) - newRect._position.y; return newRect; } /// <summary> /// Returns true if this Rect2i completely encloses another one. /// </summary> /// <param name="b">The other rect that may be enclosed.</param> /// <returns>A bool for whether or not this rect encloses `b`.</returns> public bool Encloses(Rect2i b) { return b._position.x >= _position.x && b._position.y >= _position.y && b._position.x + b._size.x < _position.x + _size.x && b._position.y + b._size.y < _position.y + _size.y; } /// <summary> /// Returns this Rect2i expanded to include a given point. /// </summary> /// <param name="to">The point to include.</param> /// <returns>The expanded rect.</returns> public Rect2i Expand(Vector2i to) { var expanded = this; Vector2i begin = expanded._position; Vector2i end = expanded._position + expanded._size; if (to.x < begin.x) { begin.x = to.x; } if (to.y < begin.y) { begin.y = to.y; } if (to.x > end.x) { end.x = to.x; } if (to.y > end.y) { end.y = to.y; } expanded._position = begin; expanded._size = end - begin; return expanded; } /// <summary> /// Returns the area of the Rect2. /// </summary> /// <returns>The area.</returns> public int GetArea() { return _size.x * _size.y; } /// <summary> /// Returns a copy of the Rect2i grown a given amount of units towards all the sides. /// </summary> /// <param name="by">The amount to grow by.</param> /// <returns>The grown rect.</returns> public Rect2i Grow(int by) { var g = this; g._position.x -= by; g._position.y -= by; g._size.x += by * 2; g._size.y += by * 2; return g; } /// <summary> /// Returns a copy of the Rect2i grown a given amount of units towards each direction individually. /// </summary> /// <param name="left">The amount to grow by on the left.</param> /// <param name="top">The amount to grow by on the top.</param> /// <param name="right">The amount to grow by on the right.</param> /// <param name="bottom">The amount to grow by on the bottom.</param> /// <returns>The grown rect.</returns> public Rect2i GrowIndividual(int left, int top, int right, int bottom) { var g = this; g._position.x -= left; g._position.y -= top; g._size.x += left + right; g._size.y += top + bottom; return g; } /// <summary> /// Returns a copy of the Rect2i grown a given amount of units towards the <see cref="Margin"/> direction. /// </summary> /// <param name="margin">The direction to grow in.</param> /// <param name="by">The amount to grow by.</param> /// <returns>The grown rect.</returns> public Rect2i GrowMargin(Margin margin, int by) { var g = this; g = g.GrowIndividual(Margin.Left == margin ? by : 0, Margin.Top == margin ? by : 0, Margin.Right == margin ? by : 0, Margin.Bottom == margin ? by : 0); return g; } /// <summary> /// Returns true if the Rect2 is flat or empty, or false otherwise. /// </summary> /// <returns>A bool for whether or not the rect has area.</returns> public bool HasNoArea() { return _size.x <= 0 || _size.y <= 0; } /// <summary> /// Returns true if the Rect2 contains a point, or false otherwise. /// </summary> /// <param name="point">The point to check.</param> /// <returns>A bool for whether or not the rect contains `point`.</returns> public bool HasPoint(Vector2i point) { if (point.x < _position.x) return false; if (point.y < _position.y) return false; if (point.x >= _position.x + _size.x) return false; if (point.y >= _position.y + _size.y) return false; return true; } /// <summary> /// Returns true if the Rect2i overlaps with `b` /// (i.e. they have at least one point in common). /// /// If `includeBorders` is true, they will also be considered overlapping /// if their borders touch, even without intersection. /// </summary> /// <param name="b">The other rect to check for intersections with.</param> /// <param name="includeBorders">Whether or not to consider borders.</param> /// <returns>A bool for whether or not they are intersecting.</returns> public bool Intersects(Rect2i b, bool includeBorders = false) { if (includeBorders) { if (_position.x > b._position.x + b._size.x) return false; if (_position.x + _size.x < b._position.x) return false; if (_position.y > b._position.y + b._size.y) return false; if (_position.y + _size.y < b._position.y) return false; } else { if (_position.x >= b._position.x + b._size.x) return false; if (_position.x + _size.x <= b._position.x) return false; if (_position.y >= b._position.y + b._size.y) return false; if (_position.y + _size.y <= b._position.y) return false; } return true; } /// <summary> /// Returns a larger Rect2i that contains this Rect2 and `b`. /// </summary> /// <param name="b">The other rect.</param> /// <returns>The merged rect.</returns> public Rect2i Merge(Rect2i b) { Rect2i newRect; newRect._position.x = Mathf.Min(b._position.x, _position.x); newRect._position.y = Mathf.Min(b._position.y, _position.y); newRect._size.x = Mathf.Max(b._position.x + b._size.x, _position.x + _size.x); newRect._size.y = Mathf.Max(b._position.y + b._size.y, _position.y + _size.y); newRect._size -= newRect._position; // Make relative again return newRect; } /// <summary> /// Constructs a Rect2i from a position and size. /// </summary> /// <param name="position">The position.</param> /// <param name="size">The size.</param> public Rect2i(Vector2i position, Vector2i size) { _position = position; _size = size; } /// <summary> /// Constructs a Rect2i from a position, width, and height. /// </summary> /// <param name="position">The position.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> public Rect2i(Vector2i position, int width, int height) { _position = position; _size = new Vector2i(width, height); } /// <summary> /// Constructs a Rect2i from x, y, and size. /// </summary> /// <param name="x">The position's X coordinate.</param> /// <param name="y">The position's Y coordinate.</param> /// <param name="size">The size.</param> public Rect2i(int x, int y, Vector2i size) { _position = new Vector2i(x, y); _size = size; } /// <summary> /// Constructs a Rect2i from x, y, width, and height. /// </summary> /// <param name="x">The position's X coordinate.</param> /// <param name="y">The position's Y coordinate.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> public Rect2i(int x, int y, int width, int height) { _position = new Vector2i(x, y); _size = new Vector2i(width, height); } public static bool operator ==(Rect2i left, Rect2i right) { return left.Equals(right); } public static bool operator !=(Rect2i left, Rect2i right) { return !left.Equals(right); } public static implicit operator Rect2(Rect2i value) { return new Rect2(value._position, value._size); } public static explicit operator Rect2i(Rect2 value) { return new Rect2i((Vector2i)value.Position, (Vector2i)value.Size); } public override bool Equals(object obj) { if (obj is Rect2i) { return Equals((Rect2i)obj); } return false; } public bool Equals(Rect2i other) { return _position.Equals(other._position) && _size.Equals(other._size); } public override int GetHashCode() { return _position.GetHashCode() ^ _size.GetHashCode(); } public override string ToString() { return String.Format("{0}, {1}", new object[] { _position.ToString(), _size.ToString() }); } public string ToString(string format) { return String.Format("{0}, {1}", new object[] { _position.ToString(format), _size.ToString(format) }); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Windows.Forms; using DemoGame.Client.Properties; using log4net; using NetGore; using NetGore.Audio; using NetGore.Content; using NetGore.Graphics; using NetGore.Graphics.GUI; using NetGore.IO; using NetGore.Network; using NetGore.World; using SFML.Graphics; using SFML.Window; using Control = NetGore.Graphics.GUI.Control; using KeyEventArgs = SFML.Window.KeyEventArgs; namespace DemoGame.Client { /// <summary> /// Root object for the Client /// </summary> public class DemoGame : GameBase { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); readonly ScreenManager _screenManager; readonly ClientSockets _sockets; IEnumerable<TextureAtlas> _globalAtlases; /// <summary> /// Initializes a new instance of the <see cref="DemoGame"/> class. /// </summary> public DemoGame() : base( new Point((int)GameData.ScreenSize.X, (int)GameData.ScreenSize.Y), new Point((int)GameData.ScreenSize.X, (int)GameData.ScreenSize.Y), GameMessageCollection.CurrentLanguage.GetMessage(GameMessage.GameTitle)) { ThreadAsserts.IsMainThread(); EngineSettingsInitializer.Initialize(); // Create the screen manager var skinManager = new SkinManager("Default"); _screenManager = new ScreenManager(this, skinManager, "Font/Arial", 24); // Initialize the socket manager ClientSockets.Initialize(ScreenManager); _sockets = ClientSockets.Instance; // Read the GrhInfo LoadGrhInfo(); var lightGD = GrhInfo.GetData("Effect", "light"); _screenManager.DrawingManager.LightManager.DefaultSprite = new Grh(lightGD); // Set up our custom chat bubbles ChatBubble.CreateChatBubbleInstance = CreateChatBubbleInstanceHandler; // Get our title song var titleSong = ScreenManager.AudioManager.MusicManager.MusicInfos.ElementAt(0); // Create the screens new OptionsScreen(ScreenManager) { ScreenMusic = titleSong }; ; new GameplayScreen(ScreenManager); new MainMenuScreen(ScreenManager) { ScreenMusic = titleSong }; new LoginScreen(ScreenManager) { ScreenMusic = titleSong }; ; new CharacterSelectionScreen(ScreenManager) { ScreenMusic = titleSong }; ; new CreateCharacterScreen(ScreenManager) { ScreenMusic = titleSong }; ; new NewAccountScreen(ScreenManager) { ScreenMusic = titleSong }; ; ScreenManager.ConsoleScreen = new ConsoleScreen(ScreenManager); ScreenManager.SetScreen<MainMenuScreen>(); ShowMouseCursor = true; KeyPressed -= DemoGame_KeyPressed; KeyPressed += DemoGame_KeyPressed; var clientSettings = ClientSettings.Default; // Apply some of the initial settings ScreenManager.AudioManager.SoundManager.Volume = clientSettings.Audio_SoundVolume; ScreenManager.AudioManager.MusicManager.Volume = clientSettings.Audio_MusicVolume; UseVerticalSync = clientSettings.Graphics_VSync; IsFullscreen = clientSettings.Graphics_Fullscreen; // Listen for changes to the settings clientSettings.PropertyChanged -= Default_PropertyChanged; clientSettings.PropertyChanged += Default_PropertyChanged; } /// <summary> /// Gets the <see cref="IScreenManager"/> instance used to display the screens for the client. /// </summary> public IScreenManager ScreenManager { get { return _screenManager; } } /// <summary> /// Gets the <see cref="IClientSocketManager"/> instance used to let the client communicate with the server. /// </summary> public IClientSocketManager Sockets { get { return _sockets; } } /// <summary> /// Decides the <see cref="ContentLevel"/> to use for <see cref="GrhData"/>s. /// </summary> /// <param name="grhData">The <see cref="GrhData"/> to get the <see cref="ContentLevel"/> for.</param> /// <returns>The <see cref="ContentLevel"/> for the <paramref name="grhData"/>.</returns> static ContentLevel ContentLevelDecider(GrhData grhData) { const StringComparison comp = StringComparison.OrdinalIgnoreCase; var cat = grhData.Categorization.Category.ToString(); // For stuff that will be put into a global atlas, use the temporary level if (cat.StartsWith("gui", comp)) return ContentLevel.Temporary; // For stuff in the map category, use Map if (cat.StartsWith("map", comp)) return ContentLevel.Map; // Everything else, return global return ContentLevel.Global; } /// <summary> /// Handles the <see cref="ChatBubble.CreateChatBubbleInstance"/> to create custom <see cref="ChatBubble"/>s. /// </summary> /// <param name="parent">The parent <see cref="NetGore.Graphics.GUI.Control"/>.</param> /// <param name="owner">The <see cref="Entity"/> the chat bubble is for.</param> /// <param name="text">The text to display.</param> /// <returns>The <see cref="ChatBubble"/> instance.</returns> static ChatBubble CreateChatBubbleInstanceHandler(Control parent, Entity owner, string text) { return new GameChatBubble(parent, owner, text); } /// <summary> /// Gets the system handle to use to display the game on when using windowed mode. If <see cref="IntPtr.Zero"/> is returned, /// a system form will be created automatically. /// </summary> /// <param name="displayContainer">When this method returns a value other than <see cref="IntPtr.Zero"/>, contains the /// object that the returned system handle belongs to. This is then later used in other virutal methods to initialize /// and dispose the container at the appropriate times.</param> /// <returns> /// The handle to the custom control to display the game on, or <see cref="IntPtr.Zero"/> to create the window /// to display the game on internally. /// </returns> protected override IntPtr CreateWindowedDisplayHandle(out object displayContainer) { var frm = new GameForm(this); // Set form title while we're at it frm.Text = GameMessageCollection.CurrentLanguage.GetMessage(GameMessage.GameTitle); displayContainer = frm; return frm.Handle; } /// <summary> /// Handles the PropertyChanged event of the <see cref="ClientSettings"/>. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.ComponentModel.PropertyChangedEventArgs"/> instance containing the event data.</param> void Default_PropertyChanged(object sender, PropertyChangedEventArgs e) { const string soundVolumeName = "Audio_SoundVolume"; const string musicVolumeName = "Audio_MusicVolume"; const string graphicsVSyncName = "Graphics_VSync"; const string graphicsFullscreenName = "Graphics_Fullscreen"; ClientSettings.Default.AssertPropertyExists(soundVolumeName); ClientSettings.Default.AssertPropertyExists(musicVolumeName); ClientSettings.Default.AssertPropertyExists(graphicsVSyncName); ClientSettings.Default.AssertPropertyExists(graphicsFullscreenName); var sc = StringComparer.Ordinal; if (sc.Equals(e.PropertyName, soundVolumeName)) { // Sound volume var value = ClientSettings.Default.Audio_SoundVolume; ScreenManager.AudioManager.SoundManager.Volume = value; } else if (sc.Equals(e.PropertyName, musicVolumeName)) { // Music volume var value = ClientSettings.Default.Audio_MusicVolume; ScreenManager.AudioManager.MusicManager.Volume = value; } else if (sc.Equals(e.PropertyName, graphicsVSyncName)) { // VSync var value = ClientSettings.Default.Graphics_VSync; UseVerticalSync = value; } else if (sc.Equals(e.PropertyName, graphicsFullscreenName)) { // Fullscreen var value = ClientSettings.Default.Graphics_Fullscreen; IsFullscreen = value; } } /// <summary> /// Handles the KeyPressed event of the DemoGame control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="SFML.Window.KeyEventArgs"/> instance containing the event data.</param> void DemoGame_KeyPressed(object sender, KeyEventArgs e) { if (e.Code == Keyboard.Key.Tilde) _screenManager.ShowConsole = !_screenManager.ShowConsole; if (e.Code == Keyboard.Key.Return && e.Alt) ClientSettings.Default.Graphics_Fullscreen = !ClientSettings.Default.Graphics_Fullscreen; } /// <summary> /// Provides the ability to dispose of a custom display container. This is only invoked when you use /// <see cref="GameBase.CreateWindowedDisplayHandle"/> and when there is an object to clean up. /// </summary> /// <param name="displayContainer">The display container reference that was used in the last call to /// <see cref="GameBase.CreateWindowedDisplayHandle"/>.</param> protected override void DestroyCustomWindowedDisplayHandle(object displayContainer) { var frm = GetDisplayContainerAsGameForm(displayContainer); if (frm == null) return; frm.DisposeGameOnClose = false; if (!frm.IsDisposed) frm.Dispose(); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposeManaged"><c>true</c> to release both managed and unmanaged resources; /// <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposeManaged) { ClientSettings.Default.Save(); if (disposeManaged) { if (_globalAtlases != null) { foreach (var atlas in _globalAtlases) { atlas.Dispose(); } } _screenManager.Dispose(); } base.Dispose(disposeManaged); } /// <summary> /// Gets a displayContainer parameter as a <see cref="GameForm"/>, and makes sure it is a <see cref="GameForm"/> like /// we expect. /// </summary> /// <param name="displayContainer">The display container.</param> /// <returns>The <see cref="GameForm"/>, or null if <paramref name="displayContainer"/> is not a <see cref="GameForm"/>.</returns> static GameForm GetDisplayContainerAsGameForm(object displayContainer) { var frm = displayContainer as GameForm; if (frm == null) { const string errmsg = "Was expecting `{0}` to be type GameForm, but was `{1}` instead."; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, displayContainer, displayContainer != null ? displayContainer.GetType().ToString() : "[NULL]"); Debug.Fail(string.Format(errmsg, displayContainer, displayContainer != null ? displayContainer.GetType().ToString() : "[NULL]")); return null; } return frm; } /// <summary> /// When overridden in the derived class, handles drawing the game. /// </summary> /// <param name="currentTime">The current time.</param> protected override void HandleDraw(TickCount currentTime) { _screenManager.Draw(TickCount.Now); } /// <summary> /// When overridden in the derived class, handles updating the game. /// </summary> /// <param name="currentTime">The current time.</param> protected override void HandleUpdate(TickCount currentTime) { // Update the sockets _sockets.Heartbeat(); // Update everything else _screenManager.Update(TickCount.Now); } /// <summary> /// Loads the GrhInfo and places them in atlases based on their category /// </summary> void LoadGrhInfo() { GrhInfo.ContentLevelDecider = ContentLevelDecider; // Read the Grh info, using the MapContent for the ContentManager since all // but the map GrhDatas should end up in an atlas. For anything that does not // end up in an atlas, this will provide them a way to load still. GrhInfo.Load(ContentPaths.Build, _screenManager.Content); // Organize the GrhDatas for the atlases var gdChars = new List<ITextureAtlasable>(); var gdGUI = new List<ITextureAtlasable>(); foreach (var gd in GrhInfo.GrhDatas.SelectMany(x => x.Frames).Distinct()) { var categoryStr = gd.Categorization.Category.ToString(); if (categoryStr.StartsWith("character", StringComparison.OrdinalIgnoreCase)) gdChars.Add(gd); else if (categoryStr.StartsWith("gui", StringComparison.OrdinalIgnoreCase)) gdGUI.Add(gd); } // Build the atlases, leaving everything but map GrhDatas in an atlas var globalAtlasesList = new List<TextureAtlas>(); if (gdChars.Count > 0) globalAtlasesList.Add(new TextureAtlas(gdChars)); if (gdGUI.Count > 0) globalAtlasesList.Add(new TextureAtlas(gdGUI)); _globalAtlases = globalAtlasesList.ToArray(); // Unload all of the textures temporarily loaded into the MapContent // from the texture atlasing process _screenManager.Content.Unload(); } /// <summary> /// Provides the ability for the derived class to enter a custom loop. This is primarily intended to allow event-driven /// objects such as the Windows Forms to run without freezing. If this method blocks, it is up to the implementation /// to call <see cref="IGameContainer.HandleFrame"/> manually. /// </summary> /// <param name="displayContainer">The display container reference that was used in the last call to /// <see cref="GameBase.CreateWindowedDisplayHandle"/>.</param> /// <example> /// When using WinForms, this should contain a call to Application.Run() where the <paramref name="displayContainer"/> /// is the Form that the game exists on. You will have to add additional logic to your form to have it call /// <see cref="IGameContainer.HandleFrame"/> whenever the form is idle. /// </example> protected override void RunCustomWindowedDisplayHandleLoop(object displayContainer) { var frm = GetDisplayContainerAsGameForm(displayContainer); if (frm == null) return; Application.Run(frm); } } }
// 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 Android.App; using Android.OS; using Android.Widget; using ArcGISRuntime.Samples.Managers; using Esri.ArcGISRuntime.ArcGISServices; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.Tasks; using Esri.ArcGISRuntime.Tasks.Offline; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Threading.Tasks; using Esri.ArcGISRuntime; namespace ArcGISRuntime.Samples.EditAndSyncFeatures { [Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("e4a398afe9a945f3b0f4dca1e4faccb5")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Edit and sync features", category: "Data", description: "Synchronize offline edits with a feature service.", instructions: "Pan and zoom to position the red rectangle around the area you want to take offline. Tap \"Generate geodatabase\" to take the area offline. When complete, the map will update to only show the offline area. To edit features, tap to select a feature, and tap again anywhere else on the map to move the selected feature to the clicked location. To sync the edits with the feature service, tap the \"Sync geodatabase\" button.", tags: new[] { "feature service", "geodatabase", "offline", "synchronize" })] public class EditAndSyncFeatures : Activity { // Enumeration to track which phase of the workflow the sample is in. private enum EditState { NotReady, // Geodatabase has not yet been generated. Editing, // A feature is in the process of being moved. Ready // The geodatabase is ready for synchronization or further edits. } // URL for a feature service that supports geodatabase generation. private Uri _featureServiceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/WildfireSync/FeatureServer"); // Path to the geodatabase file on disk. private string _gdbPath; // Task to be used for generating the geodatabase. private GeodatabaseSyncTask _gdbSyncTask; // Flag to indicate which stage of the edit process the sample is in. private EditState _readyForEdits = EditState.NotReady; // Hold a reference to the generated geodatabase. private Geodatabase _resultGdb; // Mapview. private MapView myMapView; // Generate Button. private Button myGenerateButton; // Sync Button. private Button mySyncButton; // Progress bar. private ProgressBar myProgressBar; // Help label. private TextView myHelpLabel; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Edit and Sync Features"; // Create the UI, setup the control references and execute initialization. CreateLayout(); Initialize(); } private void CreateLayout() { // Create the layout. LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical }; // Add the help label. myHelpLabel = new TextView(this) { Text = "1. Click 'Generate'" }; layout.AddView(myHelpLabel); // Add the progress bar. myProgressBar = new ProgressBar(this) { Visibility = Android.Views.ViewStates.Gone }; layout.AddView(myProgressBar); // Add the generate button. myGenerateButton = new Button(this) { Text = "Generate", Enabled = false }; myGenerateButton.Click += GenerateButton_Clicked; layout.AddView(myGenerateButton); // Add the sync button. mySyncButton = new Button(this) { Text = "Synchronize" }; mySyncButton.Click += SyncButton_Click; mySyncButton.Enabled = false; layout.AddView(mySyncButton); // Add the mapview. myMapView = new MapView(this); layout.AddView(myMapView); // Add the layout to the view. SetContentView(layout); } private async void Initialize() { // Create a tile cache and load it with the SanFrancisco streets tpk. TileCache tileCache = new TileCache(DataManager.GetDataFolder("e4a398afe9a945f3b0f4dca1e4faccb5", "SanFrancisco.tpkx")); // Create the corresponding layer based on the tile cache. ArcGISTiledLayer tileLayer = new ArcGISTiledLayer(tileCache); // Create the basemap based on the tile cache. Basemap sfBasemap = new Basemap(tileLayer); // Create the map with the tile-based basemap. Map myMap = new Map(sfBasemap); // Assign the map to the MapView. myMapView.Map = myMap; // Create a new symbol for the extent graphic. SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 2); // Create graphics overlay for the extent graphic and apply a renderer. GraphicsOverlay extentOverlay = new GraphicsOverlay { Renderer = new SimpleRenderer(lineSymbol) }; // Add graphics overlay to the map view. myMapView.GraphicsOverlays.Add(extentOverlay); // Set up an event handler for when the viewpoint (extent) changes. myMapView.ViewpointChanged += MapViewExtentChanged; // Set up event handler for mapview taps. myMapView.GeoViewTapped += GeoViewTapped; try { // Create a task for generating a geodatabase (GeodatabaseSyncTask). _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri); // Add all graphics from the service to the map. foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos) { // Get the Uri for this particular layer. Uri onlineTableUri = new Uri(_featureServiceUri + "/" + layer.Id); // Create the ServiceFeatureTable. ServiceFeatureTable onlineTable = new ServiceFeatureTable(onlineTableUri); // Wait for the table to load. await onlineTable.LoadAsync(); // Skip tables that aren't for point features. if (onlineTable.GeometryType != GeometryType.Point) { continue; } // Add the layer to the map's operational layers if load succeeds. if (onlineTable.LoadStatus == LoadStatus.Loaded) { myMap.OperationalLayers.Add(new FeatureLayer(onlineTable)); } } // Update the graphic - in case user doesn't interact with the map. UpdateMapExtent(); // Enable the generate button now that the sample is ready. myGenerateButton.Enabled = true; } catch (Exception e) { ShowStatusMessage(e.ToString()); } } private async void GeoViewTapped(object sender, GeoViewInputEventArgs e) { // Disregard if not ready for edits. try { if (_readyForEdits == EditState.NotReady) { return; } // If an edit is in process, finish it. if (_readyForEdits == EditState.Editing) { // Hold a list of any selected features. List<Feature> selectedFeatures = new List<Feature>(); // Get all selected features then clear selection. foreach (FeatureLayer layer in myMapView.Map.OperationalLayers) { // Get the selected features. FeatureQueryResult layerFeatures = await layer.GetSelectedFeaturesAsync(); // FeatureQueryResult implements IEnumerable, so it can be treated as a collection of features. selectedFeatures.AddRange(layerFeatures); // Clear the selection. layer.ClearSelection(); } // Update all selected features' geometry. foreach (Feature feature in selectedFeatures) { // Get a reference to the correct feature table for the feature. GeodatabaseFeatureTable table = (GeodatabaseFeatureTable)feature.FeatureTable; // Ensure the geometry type of the table is point. if (table.GeometryType != GeometryType.Point) { continue; } // Set the new geometry. feature.Geometry = e.Location; try { // Update the feature in the table. await table.UpdateFeatureAsync(feature); } catch (Esri.ArcGISRuntime.ArcGISException) { ShowStatusMessage("Feature must be within extent of geodatabase."); } } // Update the edit state. _readyForEdits = EditState.Ready; // Enable the sync button. mySyncButton.Enabled = true; // Update the help label. myHelpLabel.Text = "4. Click 'Synchronize' or edit more features"; } // Otherwise, start an edit. else { // Define a tolerance for use with identifying the feature. double tolerance = 15 * myMapView.UnitsPerPixel; // Define the selection envelope. Envelope selectionEnvelope = new Envelope(e.Location.X - tolerance, e.Location.Y - tolerance, e.Location.X + tolerance, e.Location.Y + tolerance); // Define query parameters for feature selection. QueryParameters query = new QueryParameters() { Geometry = selectionEnvelope }; // Track whether any selections were made. bool selectedFeature = false; // Select the feature in all applicable tables. foreach (FeatureLayer layer in myMapView.Map.OperationalLayers) { FeatureQueryResult res = await layer.SelectFeaturesAsync(query, SelectionMode.New); selectedFeature = selectedFeature || res.Any(); } // Only update state if a feature was selected. if (selectedFeature) { // Set the edit state. _readyForEdits = EditState.Editing; // Update the help label. myHelpLabel.Text = "3. Tap on the map to move the point"; } } } catch (Exception ex) { ShowStatusMessage(ex.ToString()); } } private void UpdateMapExtent() { // Return if mapview is null. if (myMapView == null) { return; } // Get the new viewpoint. Viewpoint myViewPoint = myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry); // Return if viewpoint is null. if (myViewPoint == null) { return; } // Get the updated extent for the new viewpoint. Envelope extent = myViewPoint.TargetGeometry as Envelope; // Return if extent is null. if (extent == null) { return; } // Create an envelope that is a bit smaller than the extent. EnvelopeBuilder envelopeBldr = new EnvelopeBuilder(extent); envelopeBldr.Expand(0.80); // Get the (only) graphics overlay in the map view. GraphicsOverlay extentOverlay = myMapView.GraphicsOverlays.FirstOrDefault(); // Return if the extent overlay is null. if (extentOverlay == null) { return; } // Get the extent graphic. Graphic extentGraphic = extentOverlay.Graphics.FirstOrDefault(); // Create the extent graphic and add it to the overlay if it doesn't exist. if (extentGraphic == null) { extentGraphic = new Graphic(envelopeBldr.ToGeometry()); extentOverlay.Graphics.Add(extentGraphic); } else { // Otherwise, update the graphic's geometry. extentGraphic.Geometry = envelopeBldr.ToGeometry(); } } private async Task StartGeodatabaseGeneration() { // Update geodatabase path. _gdbPath = $"{Path.GetTempFileName()}.geodatabase"; // Create a task for generating a geodatabase (GeodatabaseSyncTask). _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri); // Get the (only) graphic in the map view. Graphic redPreviewBox = myMapView.GraphicsOverlays.First().Graphics.First(); // Get the current extent of the red preview box. Envelope extent = redPreviewBox.Geometry as Envelope; // Get the default parameters for the generate geodatabase task. GenerateGeodatabaseParameters generateParams = await _gdbSyncTask.CreateDefaultGenerateGeodatabaseParametersAsync(extent); // Create a generate geodatabase job. GenerateGeodatabaseJob generateGdbJob = _gdbSyncTask.GenerateGeodatabase(generateParams, _gdbPath); // Handle the progress changed event with an inline (lambda) function to show the progress bar. generateGdbJob.ProgressChanged += (sender, e) => { // Get the job. GenerateGeodatabaseJob job = (GenerateGeodatabaseJob)sender; // Update the progress bar. UpdateProgressBar(job.Progress); }; // Show the progress bar. myProgressBar.Visibility = Android.Views.ViewStates.Visible; // Start the job. generateGdbJob.Start(); // Wait for the result. _resultGdb = await generateGdbJob.GetResultAsync(); // Hide the progress bar. myProgressBar.Visibility = Android.Views.ViewStates.Gone; // Do the rest of the work. HandleGenerationCompleted(generateGdbJob); } private async void HandleGenerationCompleted(GenerateGeodatabaseJob job) { JobStatus status = job.Status; // If the job completed successfully, add the geodatabase data to the map. if (status == JobStatus.Succeeded) { // Clear out the existing layers. myMapView.Map.OperationalLayers.Clear(); // Loop through all feature tables in the geodatabase and add a new layer to the map. foreach (GeodatabaseFeatureTable table in _resultGdb.GeodatabaseFeatureTables) { // Skip non-point tables. await table.LoadAsync(); if (table.GeometryType != GeometryType.Point) { continue; } // Create a new feature layer for the table. FeatureLayer layer = new FeatureLayer(table); // Add the new layer to the map. myMapView.Map.OperationalLayers.Add(layer); } // Enable editing features. _readyForEdits = EditState.Ready; // Update the help label. myHelpLabel.Text = "2. Tap a point feature to select"; } // See if the job failed. if (status == JobStatus.Failed) { // Create a message to show the user. string message = "Generate geodatabase job failed"; // Show an error message (if there is one). if (job.Error != null) { message += ": " + job.Error.Message; } else { // If no error, show messages from the job. foreach (JobMessage m in job.Messages) { // Get the text from the JobMessage and add it to the output string. message += "\n" + m.Message; } } // Show the message. ShowStatusMessage(message); } } private void HandleSyncCompleted(SyncGeodatabaseJob job) { JobStatus status = job.Status; // Tell the user about job completion. if (status == JobStatus.Succeeded) { ShowStatusMessage("Sync task completed"); } // See if the job failed. if (status == JobStatus.Failed) { // Create a message to show the user. string message = "Sync geodatabase job failed"; // Show an error message (if there is one). if (job.Error != null) { message += ": " + job.Error.Message; } else { // If no error, show messages from the job. foreach (JobMessage m in job.Messages) { // Get the text from the JobMessage and add it to the output string. message += "\n" + m.Message; } } // Show the message. ShowStatusMessage(message); } } private async Task SyncGeodatabase() { // Return if not ready. if (_readyForEdits != EditState.Ready) { return; } // Disable the sync button. mySyncButton.Enabled = false; // Create parameters for the sync task. SyncGeodatabaseParameters parameters = new SyncGeodatabaseParameters() { GeodatabaseSyncDirection = SyncDirection.Bidirectional, RollbackOnFailure = false }; // Get the layer Id for each feature table in the geodatabase, then add to the sync job. foreach (GeodatabaseFeatureTable table in _resultGdb.GeodatabaseFeatureTables) { // Get the ID for the layer. long id = table.ServiceLayerId; // Create the SyncLayerOption. SyncLayerOption option = new SyncLayerOption(id); // Add the option. parameters.LayerOptions.Add(option); } // Create job. SyncGeodatabaseJob job = _gdbSyncTask.SyncGeodatabase(parameters, _resultGdb); // Subscribe to progress updates. job.ProgressChanged += (o, e) => { // Update the progress bar. UpdateProgressBar(job.Progress); }; // Show the progress bar. myProgressBar.Visibility = Android.Views.ViewStates.Visible; // Start the sync. job.Start(); // Wait for the job to finish. await job.GetResultAsync(); // Hide the progress bar. myProgressBar.Visibility = Android.Views.ViewStates.Gone; // Do the rest of the work. HandleSyncCompleted(job); // Re-enable the sync button. mySyncButton.Enabled = true; } private void ShowStatusMessage(string message) { // Display the message to the user. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.SetMessage(message).SetTitle("Alert").Show(); } private async void GenerateButton_Clicked(object sender, EventArgs e) { // Fix the selection graphic extent. myMapView.ViewpointChanged -= MapViewExtentChanged; // Disable the generate button. try { myGenerateButton.Enabled = false; // Call the geodatabase generation method. await StartGeodatabaseGeneration(); } catch (Exception ex) { ShowStatusMessage(ex.ToString()); } } private void MapViewExtentChanged(object sender, EventArgs e) { // Call the map extent update method. UpdateMapExtent(); } private void UpdateProgressBar(int progress) { // Due to the nature of the threading implementation, // the dispatcher needs to be used to interact with the UI. // The dispatcher takes an Action, provided here as a lambda function. RunOnUiThread(() => { // Update the progress bar value. myProgressBar.Progress = progress; }); } private async void SyncButton_Click(object sender, EventArgs e) { try { await SyncGeodatabase(); } catch (Exception ex) { ShowStatusMessage(ex.ToString()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Orleans; using Orleans.Runtime; using Orleans.Streams; using UnitTests.GrainInterfaces; using UnitTests.Grains; using UnitTests.TestHelper; namespace UnitTests.StreamingTests { public class Streaming_ConsumerClientObject : IAsyncObserver<StreamItem>, IStreaming_ConsumerGrain { private readonly IClusterClient client; private readonly ConsumerObserver _consumer; private string _providerToUse; private Streaming_ConsumerClientObject(ILogger logger, IClusterClient client) { this.client = client; _consumer = ConsumerObserver.NewObserver(logger); } public static Streaming_ConsumerClientObject NewObserver(ILogger logger, IClusterClient client) { return new Streaming_ConsumerClientObject(logger, client); } public Task OnNextAsync(StreamItem item, StreamSequenceToken token = null) { return _consumer.OnNextAsync(item, token); } public Task OnCompletedAsync() { return _consumer.OnCompletedAsync(); } public Task OnErrorAsync(Exception ex) { return _consumer.OnErrorAsync(ex); } public Task BecomeConsumer(Guid streamId, string providerToUse) { _providerToUse = providerToUse; return _consumer.BecomeConsumer(streamId, this.client.GetStreamProvider(providerToUse), null); } public Task BecomeConsumer(Guid streamId, string providerToUse, string streamNamespace) { _providerToUse = providerToUse; return _consumer.BecomeConsumer(streamId, this.client.GetStreamProvider(providerToUse), streamNamespace); } public Task StopBeingConsumer() { return _consumer.StopBeingConsumer(this.client.GetStreamProvider(_providerToUse)); } public Task<int> GetConsumerCount() { return _consumer.ConsumerCount; } public Task<int> GetItemsConsumed() { return _consumer.ItemsConsumed; } public Task DeactivateConsumerOnIdle() { return Task.CompletedTask; } } public class Streaming_ProducerClientObject : IStreaming_ProducerGrain { private readonly ProducerObserver producer; private readonly IClusterClient client; private Streaming_ProducerClientObject(ILogger logger, IClusterClient client) { this.client = client; this.producer = ProducerObserver.NewObserver(logger, client); } public static Streaming_ProducerClientObject NewObserver(ILogger logger, IClusterClient client) { if (null == logger) throw new ArgumentNullException("logger"); return new Streaming_ProducerClientObject(logger, client); } public Task BecomeProducer(Guid streamId, string providerToUse, string streamNamespace) { this.producer.BecomeProducer(streamId, this.client.GetStreamProvider(providerToUse), streamNamespace); return Task.CompletedTask; } public Task ProduceSequentialSeries(int count) { return this.producer.ProduceSequentialSeries(count); } public Task ProduceParallelSeries(int count) { return this.producer.ProduceParallelSeries(count); } public Task<int> GetItemsProduced() { return this.producer.ItemsProduced; } public Task ProducePeriodicSeries(int count) { return this.producer.ProducePeriodicSeries(timerCallback => { return new AsyncTaskSafeTimer(NullLogger.Instance, timerCallback, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(10)); }, count); } public Task<Guid> GetStreamId() { return this.producer.StreamId; } public Task<string> GetProviderName() { return Task.FromResult(this.producer.ProviderName); } public Task AddNewConsumerGrain(Guid consumerGrainId) { return this.producer.AddNewConsumerGrain(consumerGrainId); } public Task<int> GetExpectedItemsProduced() { return this.producer.ExpectedItemsProduced; } public Task<int> GetProducerCount() { return this.producer.ProducerCount; } public Task StopBeingProducer() { return this.producer.StopBeingProducer(); } public Task VerifyFinished() { return this.producer.VerifyFinished(); } public Task DeactivateProducerOnIdle() { return Task.CompletedTask; } } internal class ConsumerProxy { private readonly IStreaming_ConsumerGrain[] _targets; private readonly ILogger _logger; private readonly IInternalGrainFactory grainFactory; private ConsumerProxy(IStreaming_ConsumerGrain[] targets, ILogger logger, IInternalGrainFactory grainFactory) { _targets = targets; _logger = logger; this.grainFactory = grainFactory; } private static async Task<ConsumerProxy> NewConsumerProxy(Guid streamId, string streamProvider, IStreaming_ConsumerGrain[] targets, ILogger logger, IInternalGrainFactory grainFactory) { if (targets == null) throw new ArgumentNullException("targets"); if (targets.Length == 0) throw new ArgumentException("caller must specify at least one target"); if (String.IsNullOrWhiteSpace(streamProvider)) throw new ArgumentException("Stream provider name is either null or whitespace", "streamProvider"); if (logger == null) throw new ArgumentNullException("logger"); ConsumerProxy newObj = new ConsumerProxy(targets, logger, grainFactory); await newObj.BecomeConsumer(streamId, streamProvider); return newObj; } public static Task<ConsumerProxy> NewConsumerGrainsAsync(Guid streamId, string streamProvider, ILogger logger, IInternalGrainFactory grainFactory, Guid[] grainIds = null, int grainCount = 1) { grainCount = grainIds != null ? grainIds.Length : grainCount; if (grainCount < 1) throw new ArgumentOutOfRangeException("grainCount", "The grain count must be at least one"); logger.Info("ConsumerProxy.NewConsumerGrainsAsync: multiplexing {0} consumer grains for stream {1}.", grainCount, streamId); var grains = new IStreaming_ConsumerGrain[grainCount]; var dedup = new Dictionary<Guid, IStreaming_ConsumerGrain>(); var grainFullName = typeof(Streaming_ConsumerGrain).FullName; for (var i = 0; i < grainCount; ++i) { if (grainIds != null) { // we deduplicate the grain references to ensure that IEnumerable.Distinct() works as intended. if (dedup.ContainsKey(grainIds[i])) grains[i] = dedup[grainIds[i]]; else { var gref = grainFactory.GetGrain<IStreaming_ConsumerGrain>(grainIds[i], grainFullName); grains[i] = gref; dedup[grainIds[i]] = gref; } } else { grains[i] = grainFactory.GetGrain<IStreaming_ConsumerGrain>(Guid.NewGuid(), grainFullName); } } return NewConsumerProxy(streamId, streamProvider, grains, logger, grainFactory); } public static Task<ConsumerProxy> NewProducerConsumerGrainsAsync(Guid streamId, string streamProvider, ILogger logger, int[] grainIds, bool useReentrantGrain, IInternalGrainFactory grainFactory) { int grainCount = grainIds.Length; if (grainCount < 1) throw new ArgumentOutOfRangeException("grainIds", "The grain count must be at least one"); logger.Info("ConsumerProxy.NewProducerConsumerGrainsAsync: multiplexing {0} consumer grains for stream {1}.", grainCount, streamId); var grains = new IStreaming_ConsumerGrain[grainCount]; var dedup = new Dictionary<int, IStreaming_ConsumerGrain>(); for (var i = 0; i < grainCount; ++i) { // we deduplicate the grain references to ensure that IEnumerable.Distinct() works as intended. if (dedup.ContainsKey(grainIds[i])) grains[i] = dedup[grainIds[i]]; else { if (useReentrantGrain) { grains[i] = grainFactory.GetGrain<IStreaming_Reentrant_ProducerConsumerGrain>(grainIds[i]); } else { var grainFullName = typeof(Streaming_ProducerConsumerGrain).FullName; grains[i] = grainFactory.GetGrain<IStreaming_ProducerConsumerGrain>(grainIds[i], grainFullName); } dedup[grainIds[i]] = grains[i]; } } return NewConsumerProxy(streamId, streamProvider, grains, logger, grainFactory); } public static Task<ConsumerProxy> NewConsumerClientObjectsAsync(Guid streamId, string streamProvider, ILogger logger, IInternalClusterClient client, int consumerCount = 1) { if (consumerCount < 1) throw new ArgumentOutOfRangeException("consumerCount", "argument must be 1 or greater"); logger.Info("ConsumerProxy.NewConsumerClientObjectsAsync: multiplexing {0} consumer client objects for stream {1}.", consumerCount, streamId); var objs = new IStreaming_ConsumerGrain[consumerCount]; for (var i = 0; i < consumerCount; ++i) objs[i] = Streaming_ConsumerClientObject.NewObserver(logger, client); return NewConsumerProxy(streamId, streamProvider, objs, logger, client); } public static ConsumerProxy NewConsumerGrainAsync_WithoutBecomeConsumer(Guid consumerGrainId, ILogger logger, IInternalGrainFactory grainFactory, string grainClassName = "") { if (logger == null) throw new ArgumentNullException("logger"); if (string.IsNullOrEmpty(grainClassName)) { grainClassName = typeof(Streaming_ConsumerGrain).FullName; } var grains = new IStreaming_ConsumerGrain[1]; grains[0] = grainFactory.GetGrain<IStreaming_ConsumerGrain>(consumerGrainId, grainClassName); ConsumerProxy newObj = new ConsumerProxy(grains, logger, grainFactory); return newObj; } private async Task BecomeConsumer(Guid streamId, string providerToUse) { List<Task> tasks = new List<Task>(); foreach (var target in _targets) { Task t = target.BecomeConsumer(streamId, providerToUse, null); // Consider: remove this await, let the calls go in parallel. // Have to do it for now to prevent multithreaded scheduler bug from happening. // await t; tasks.Add(t); } await Task.WhenAll(tasks); } private async Task<int> GetItemsConsumed() { var tasks = _targets.Distinct().Select(t => t.GetItemsConsumed()).ToArray(); await Task.WhenAll(tasks); return tasks.Sum(t => t.Result); } public Task<int> ItemsConsumed { get { return GetItemsConsumed(); } } private async Task<int> GetConsumerCount() { var tasks = _targets.Distinct().Select(p => p.GetConsumerCount()).ToArray(); await Task.WhenAll(tasks); return tasks.Sum(t => t.Result); } public Task<int> ConsumerCount { get { return GetConsumerCount(); } } public Task StopBeingConsumer() { var tasks = _targets.Distinct().Select(c => c.StopBeingConsumer()).ToArray(); return Task.WhenAll(tasks); } public async Task DeactivateOnIdle() { var tasks = _targets.Distinct().Select(t => t.DeactivateConsumerOnIdle()).ToArray(); await Task.WhenAll(tasks); } public Task<int> GetNumActivations(IInternalGrainFactory grainFactory) { return GetNumActivations(_targets.Distinct(), grainFactory); } public static async Task<int> GetNumActivations(IEnumerable<IGrain> targets, IInternalGrainFactory grainFactory) { var grainIds = targets.Distinct().Where(t => t is GrainReference).Select(t => ((GrainReference)t).GrainId).ToArray(); IManagementGrain systemManagement = grainFactory.GetGrain<IManagementGrain>(0); var tasks = grainIds.Select(g => systemManagement.GetGrainActivationCount((GrainReference)grainFactory.GetGrain(g))).ToArray(); await Task.WhenAll(tasks); return tasks.Sum(t => t.Result); } } internal class ProducerProxy { private readonly IStreaming_ProducerGrain[] _targets; private readonly ILogger _logger; private readonly Guid _streamId; private readonly string _providerName; private readonly InterlockedFlag _cleanedUpFlag; public Task<int> ExpectedItemsProduced { get { return GetExpectedItemsProduced(); } } public string ProviderName { get { return _providerName; } } public Guid StreamIdGuid { get { return _streamId; } } public StreamId StreamId { get; } private ProducerProxy(IStreaming_ProducerGrain[] targets, Guid streamId, string providerName, ILogger logger) { _targets = targets; _logger = logger; _streamId = streamId; _providerName = providerName; _cleanedUpFlag = new InterlockedFlag(); StreamId = StreamId.Create(null, streamId); } private static async Task<ProducerProxy> NewProducerProxy(IStreaming_ProducerGrain[] targets, Guid streamId, string streamProvider, string streamNamespace, ILogger logger) { if (targets == null) throw new ArgumentNullException("targets"); if (String.IsNullOrWhiteSpace(streamProvider)) throw new ArgumentException("Stream provider name is either null or whitespace", "streamProvider"); if (logger == null) throw new ArgumentNullException("logger"); ProducerProxy newObj = new ProducerProxy(targets, streamId, streamProvider, logger); await newObj.BecomeProducer(streamId, streamProvider, streamNamespace); return newObj; } public static Task<ProducerProxy> NewProducerGrainsAsync(Guid streamId, string streamProvider, string streamNamespace, ILogger logger, IInternalGrainFactory grainFactory, Guid[] grainIds = null, int grainCount = 1) { grainCount = grainIds != null ? grainIds.Length : grainCount; if (grainCount < 1) throw new ArgumentOutOfRangeException("grainCount", "The grain count must be at least one"); logger.Info("ProducerProxy.NewProducerGrainsAsync: multiplexing {0} producer grains for stream {1}.", grainCount, streamId); var grains = new IStreaming_ProducerGrain[grainCount]; var dedup = new Dictionary<Guid, IStreaming_ProducerGrain>(); var producerGrainFullName = typeof(Streaming_ProducerGrain).FullName; for (var i = 0; i < grainCount; ++i) { if (grainIds != null) { // we deduplicate the grain references to ensure that IEnumerable.Distinct() works as intended. if (dedup.ContainsKey(grainIds[i])) grains[i] = dedup[grainIds[i]]; else { var gref = grainFactory.GetGrain<IStreaming_ProducerGrain>(grainIds[i], producerGrainFullName); grains[i] = gref; dedup[grainIds[i]] = gref; } } else { grains[i] = grainFactory.GetGrain<IStreaming_ProducerGrain>(Guid.NewGuid(), producerGrainFullName); } } return NewProducerProxy(grains, streamId, streamProvider, streamNamespace, logger); } public static Task<ProducerProxy> NewProducerConsumerGrainsAsync(Guid streamId, string streamProvider, ILogger logger, int[] grainIds, bool useReentrantGrain, IInternalGrainFactory grainFactory) { int grainCount = grainIds.Length; if (grainCount < 1) throw new ArgumentOutOfRangeException("grainIds", "The grain count must be at least one"); logger.Info("ConsumerProxy.NewProducerConsumerGrainsAsync: multiplexing {0} producer grains for stream {1}.", grainCount, streamId); var grains = new IStreaming_ProducerGrain[grainCount]; var dedup = new Dictionary<int, IStreaming_ProducerGrain>(); for (var i = 0; i < grainCount; ++i) { // we deduplicate the grain references to ensure that IEnumerable.Distinct() works as intended. if (dedup.ContainsKey(grainIds[i])) grains[i] = dedup[grainIds[i]]; else { if (useReentrantGrain) { grains[i] = grainFactory.GetGrain<IStreaming_Reentrant_ProducerConsumerGrain>(grainIds[i]); } else { var grainFullName = typeof(Streaming_ProducerConsumerGrain).FullName; grains[i] = grainFactory.GetGrain<IStreaming_ProducerConsumerGrain>(grainIds[i], grainFullName); } dedup[grainIds[i]] = grains[i]; } } return NewProducerProxy(grains, streamId, streamProvider, null, logger); } public static Task<ProducerProxy> NewProducerClientObjectsAsync(Guid streamId, string streamProvider, string streamNamespace, ILogger logger, IClusterClient client, int producersCount = 1) { if (producersCount < 1) throw new ArgumentOutOfRangeException("producersCount", "The producer count must be at least one"); var producers = new IStreaming_ProducerGrain[producersCount]; for (var i = 0; i < producersCount; ++i) producers[i] = Streaming_ProducerClientObject.NewObserver(logger, client); logger.Info("ProducerProxy.NewProducerClientObjectsAsync: multiplexing {0} producer client objects for stream {1}.", producersCount, streamId); return NewProducerProxy(producers, streamId, streamProvider, streamNamespace, logger); } private Task BecomeProducer(Guid streamId, string providerToUse, string streamNamespace) { _cleanedUpFlag.ThrowNotInitializedIfSet(); return Task.WhenAll(_targets.Select( target => target.BecomeProducer(streamId, providerToUse, streamNamespace)).ToArray()); } public async Task ProduceSequentialSeries(int count) { _cleanedUpFlag.ThrowNotInitializedIfSet(); foreach (var t in _targets.Distinct()) await t.ProduceSequentialSeries(count); } public Task ProduceParallelSeries(int count) { _cleanedUpFlag.ThrowNotInitializedIfSet(); return Task.WhenAll(_targets.Distinct().Select(t => t.ProduceParallelSeries(count)).ToArray()); } public Task ProducePeriodicSeries(int count) { _cleanedUpFlag.ThrowNotInitializedIfSet(); return Task.WhenAll(_targets.Distinct().Select(t => t.ProducePeriodicSeries(count)).ToArray()); } public async Task<Guid> AddNewConsumerGrain() { _cleanedUpFlag.ThrowNotInitializedIfSet(); if (_targets.Length != 1) throw new InvalidOperationException("This method is only supported for singular producer cases"); // disabled temporarily. // return _targets[0].AddNewConsumerGrain(); Guid consumerGrainId = Guid.NewGuid(); await _targets[0].AddNewConsumerGrain(consumerGrainId); return consumerGrainId; } private async Task<int> GetExpectedItemsProduced() { _cleanedUpFlag.ThrowNotInitializedIfSet(); var tasks = _targets.Distinct().Select(t => t.GetExpectedItemsProduced()).ToArray(); await Task.WhenAll(tasks); return tasks.Sum(t => t.Result); } private async Task<int> GetProducerCount() { var tasks = _targets.Distinct().Select(p => p.GetProducerCount()).ToArray(); await Task.WhenAll(tasks); return tasks.Sum(t => t.Result); } public Task<int> ProducerCount { get { // This method is used by the test code to verify that the object has in fact been disposed properly, // so we choose not to throw if the object has already been disposed. return GetProducerCount(); } } public async Task StopBeingProducer() { if (!_cleanedUpFlag.TrySet()) return; var tasks = new List<Task>(); foreach (var i in _targets.Distinct()) { tasks.Add(i.StopBeingProducer()); } await Task.WhenAll(tasks); tasks = new List<Task>(); foreach (var i in _targets.Distinct()) { tasks.Add(i.VerifyFinished()); } await Task.WhenAll(tasks); } public Task DeactivateOnIdle() { var tasks = _targets.Distinct().Select(t => t.DeactivateProducerOnIdle()).ToArray(); return Task.WhenAll(tasks); } public Task<int> GetNumActivations(IInternalGrainFactory grainFactory) { return ConsumerProxy.GetNumActivations(_targets.Distinct(), grainFactory); } } }
//--------------------------------------------------------------------------- // // <copyright file="IBrowserCallbackServices.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // Managed definition for IBrowserCallbackServices & IHostBrowser, used for // communicating from managed code back to the native DocObject code and the // in-proc handlers in the host browser. // // ***********************IMPORTANT************************** // // If you change any of the interface definitions here // make sure you also change the interface definitions // on the native side (src\host\inc\HostServices.idl & HostSupport.idl). // If you are not sure about how to define it // here, TEMPORARILY mark the interface as // ComVisible in the managed side, use tlbexp to generate // a typelibrary from the managed dll and copy the method // signatures from there. REMEMBER to remove the ComVisible // in the managed code when you are done. // Defining the interfaces at both ends prevents us from // publicly exposing these interfaces to the outside world. // In order for marshaling to work correctly, the vtable // and data types should match EXACTLY in both the managed // and unmanaged worlds // // // History: // 07/08/2001: mwatt: Created // 06/04/2003: kusumav: Ported to WCP tree // 04/25/2009: ChangoV Imported IHostBrowser to managed code; removed overlapping methods from IBCS. // //--------------------------------------------------------------------------- using System; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using System.Windows.Interop; using MS.Internal; using MS.Utility; using MS.Internal.Interop; namespace MS.Internal.AppModel { //********************************************************************************************// // IMPORTANT: IMPORTANT: IMPORTANT: IMPORTANT: // //********************************************************************************************// // If you change or update this interface, make sure you update the definitions in // wcp\host\inc\hostservices.idl /// <summary> /// Internal interface used for Interop in browser hosting scenarios. This /// interface is passed in by the Docobj Server hosted in the browser and is /// used to communicate from the Windows Client application back to the browser /// The master definition is in HostServices.idl. /// </summary> /// <remarks> /// The original (v1) interface has been partly superseded by IHostBrowser. /// </remarks> [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("5FFAD804-61C8-445c-8C31-A2101C64C510")] //CASRemoval:[System.Security.SuppressUnmanagedCodeSecurity] internal interface IBrowserCallbackServices { /// <SecurityNote> /// Critical due to SUC. /// A caller can treat the opearion as safe. /// </SecurityNote> [SecurityCritical, SuppressUnmanagedCodeSecurity] void OnBeforeShowNavigationWindow(); /// <summary> /// Causes the browser host to fire a ReadyState change to Complete to let /// shdocvw know that the navigation is complete /// </summary> /// <param name="readyState"></param> /// <SecurityNote> /// Critical due to SUC and because the operation is inherently unsafe. /// </SecurityNote> [SecurityCritical, SuppressUnmanagedCodeSecurity] void PostReadyStateChange([In, MarshalAs(UnmanagedType.I4)] int readyState); /// <summary> /// Allows browser host to navigate to the url. This method is typically called /// to delegate navigation back to the browser for mime types we don't handle eg: html /// </summary> /// <param name="url"></param> /// <param name="targetName"></param> /// <param name="headers"></param> /// <returns></returns> /// <SecurityNote> /// Critical - may allow listening to fully qualified uris (path discovery) /// </SecurityNote> [SecurityCritical, SuppressUnmanagedCodeSecurity] void DelegateNavigation([In, MarshalAs(UnmanagedType.BStr)] string url, [In, MarshalAs(UnmanagedType.BStr)] string targetName, [In, MarshalAs(UnmanagedType.BStr)] string headers); /// <summary> /// Notifies the avalon host to update the address bar with the current url /// </summary> /// <param name="url"></param> /// <returns></returns> /// <SecurityNote> /// Critical - may allow listening to fully qualified uris (path discovery) /// Can be used for URL spoofing. /// </SecurityNote> [PreserveSig] [return: MarshalAs(UnmanagedType.Bool)] [SecurityCritical, SuppressUnmanagedCodeSecurity] bool UpdateAddressBar([In, MarshalAs(UnmanagedType.BStr)] string url); /// <summary> /// When the internal Journal state changes, we need to make sure it is reflected /// appropriately in the browser. Adding entries will make this happen automatically /// since we explicitly add entries to the browser's TravelLog /// We need this callback for the following purposes /// 1.. Deleting visible entries will not reflect the change immediately unless /// we explicitly notify the browser (think the browser calls CanInvoke but its nice /// to update UI immediately) /// 2. Back/Forward state needs to be updated automatically when frames are /// programmatically removed from the tree. Since frames don't have their own /// journal, reparenting a frame to a new tree doesn't affect the new tree. /// Its only the tree state where it is being removed from that is affected. /// </summary> /// <SecurityNote> /// Critical - Pinvoke call for back and forward /// </SecurityNote> [PreserveSig] [SecurityCritical, SuppressUnmanagedCodeSecurity] void UpdateBackForwardState(); /// <summary> /// Add entry to shdocvw's TravelLog. Will fail on downlevel platform. /// </summary> /// <param name="topLevelNav"></param> /// <param name="addNewEntry"></param> /// <returns></returns> /// <SecurityNote> /// Critical - Pinvoke call to update travel log /// </SecurityNote> [SecurityCritical, SuppressUnmanagedCodeSecurity] void UpdateTravelLog([In, MarshalAs(UnmanagedType.Bool)]bool addNewEntry); /// <summary> /// Change status of progress bar. /// </summary> /// <returns></returns> [PreserveSig] [return: MarshalAs(UnmanagedType.Bool)] bool UpdateProgress([In, MarshalAs(UnmanagedType.I8)]long cBytesCompleted, [In, MarshalAs(UnmanagedType.I8)]long cBytesTotal); /// <summary> /// Change the download state (spin the globe/wave the flag). /// </summary> /// <returns></returns> /// <SecurityNote> /// Critical - Elevates to change the browser download state. /// </SecurityNote> [PreserveSig] [return: MarshalAs(UnmanagedType.Bool)] [SecurityCritical, SuppressUnmanagedCodeSecurity] bool ChangeDownloadState([In]bool fIsDownloading); /// <summary> /// Is this a downlevel platform that is not fully integrated /// </summary> /// <SecurityNote> /// Critical - call is SUC'ed /// </SecurityNote> [PreserveSig] [return: MarshalAs(UnmanagedType.Bool)] [SecurityCritical, SuppressUnmanagedCodeSecurity] bool IsDownlevelPlatform(); /// <summary> /// Check if browser is shutting us down /// </summary> /// <SecurityNote> /// Critical - call is SUC'ed /// </SecurityNote> [PreserveSig] [return: MarshalAs(UnmanagedType.Bool)] [SecurityCritical, SuppressUnmanagedCodeSecurity] bool IsShuttingDown(); /// <summary> /// Moves focus out of the application, to the browser frame. /// </summary> /// <SecurityNote> /// Critical - call is SUC'ed /// </SecurityNote> [PreserveSig] [SecurityCritical, SuppressUnmanagedCodeSecurity] bool TabOut(bool forward); /// <summary> /// When an unhandled exception occurs in PresentationHost a stack trace is generated /// and passed to native code via this method. Then an html error page is generated /// and the browser navigates to it. /// NOTE: There's also a DLL-exported function from PresentationHostDll for this purpose. /// See DocObjHost.ProcessUnhandledException(). /// </summary> /// <SecurityNote> /// Critical - call is SUC'ed /// </SecurityNote> [PreserveSig] [SecurityCritical, SuppressUnmanagedCodeSecurity] void ProcessUnhandledException([In, MarshalAs(UnmanagedType.BStr)] string pErrorMsg); /// <summary> /// Returns the IOleClientSite interface /// </summary> /// <SecurityNote> /// Critical - call is SUC'ed /// </SecurityNote> [PreserveSig] [SecurityCritical, SuppressUnmanagedCodeSecurity] int GetOleClientSite([Out, MarshalAs(UnmanagedType.IUnknown)] out object oleClientSite); /// <summary> /// Asks the browser to re-query for command status /// </summary> /// <SecurityNote> /// Critical - Call is SUC'ed /// </SecurityNote> [PreserveSig] [SecurityCritical, SuppressUnmanagedCodeSecurity] int UpdateCommands(); /// <remarks> /// The return value is declared as an IntPtr, not as a typed IWebBrowser2 interface, to prevent CLR /// Remoting from getting involved when the object is passed cross-AppDomain. When making calls on this /// interface, there is no point in switching to the default AppDomain, given that that object actually /// lives in another process. /// The caller must call Release() on the COM interface. /// </remarks> /// <SecurityNote> /// Critical - Call is SUC'ed. The WebOC should not be exposed to partial-trust code. /// </SecurityNote> [SecurityCritical, SuppressUnmanagedCodeSecurity] IntPtr CreateWebBrowserControlInBrowserProcess(); } /// <summary> /// [See master definition in HostSupport.idl.] /// </summary> /// <SecurityNote> /// Critical due to SUC. /// Even if a partilar method is considered safe, which many are, applying [SecurityTreatAsSafe] to it /// here won't help much, because the transparency model still requires SUC-d methods to be called only /// from SecurityCritical ones. /// </SecurityNote> [ComImport, Guid("AD5D6F02-5F4E-4D77-9FC0-381981317144"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [SecurityCritical(SecurityCriticalScope.Everything), SuppressUnmanagedCodeSecurity] interface IHostBrowser { /// <summary> /// Returns the browser's top-level URL and whether the DocObject is top-level or in a frame. /// If querying from a frame in a less secure zone than the top window, NULL may be returned for top-level URL. /// </summary> string DetermineTopLevel(out bool pbIsTopLevel); /// <summary> /// Delegates a navigation to the browser. This may cause the Avalon application to be shut down. /// targetName is the name of a frame/window or one of the predefined targets: _parent, _blank, etc. /// Normally, IBCS.DelegateNavigation() should be used instead. It calls CoAllowSetForegroundWindow() /// to let a new browser window become active. /// </summary> void Navigate(string url, string targetName = null, string headers = null); void GoBack(); void GoForward(); void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title); [PreserveSig] long SetStatusText([MarshalAs(UnmanagedType.LPWStr)] string text); void SetWidth(uint width); void SetHeight(uint height); uint GetWidth(); uint GetHeight(); int GetLeft(); int GetTop(); // These methods should not be used directly. They are used in the implementation of the cookie shim in PHDLL. // Managed code can use Application.Get/SetCookie(). string GetCookie_DoNotUse(string url, string cookieName, bool thirdParty); void SetCookie_NoNotUse(string url, string cookieName, string cookieData, bool thirdParty, string P3PHeader = null); [PreserveSig] MS.Internal.Interop.HRESULT GetUserAgentString(out string userAgent); // The implementation of IBCS.CreateWebBrowserControlInBrowserProcess() performs an important security // check before calling this method. void CreateWebBrowserControl_DoNotUse([Out] out IntPtr ppWebBrowser); void TabOut_v35SP1QFE(bool forward); }; [ComImport, Guid("AD5D6F03-0002-4D77-9FC0-381981317144"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [SecurityCritical(SecurityCriticalScope.Everything), SuppressUnmanagedCodeSecurity] interface IHostBrowser2 { // Use IBCS.TabOut() instead. The implementation of TabOut is not fully factored out yet. void TabOut_DoNotUse(bool forward); object HostScriptObject { [return:MarshalAs(UnmanagedType.IDispatch)] get; } string PluginName { get; } string PluginVersion { get; } }; }