context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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 MassTransit.Transports.RabbitMq
{
using System;
using System.Collections.Generic;
using System.Linq;
using Logging;
#if NET40
using System.Threading.Tasks;
#endif
using Magnum.Caching;
using Magnum.Extensions;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
public class RabbitMqProducer :
ConnectionBinding<RabbitMqConnection>
{
#if NET40
readonly Cache<ulong, TaskCompletionSource<bool>> _confirms;
#endif
static readonly ILog _log = Logger.Get<RabbitMqProducer>();
readonly IRabbitMqEndpointAddress _address;
readonly bool _bindToQueue;
readonly object _lock = new object();
IModel _channel;
bool _immediate;
bool _mandatory;
public RabbitMqProducer(IRabbitMqEndpointAddress address, bool bindToQueue)
{
_address = address;
_bindToQueue = bindToQueue;
#if NET40
_confirms = new ConcurrentCache<ulong, TaskCompletionSource<bool>>();
#endif
}
public void Bind(RabbitMqConnection connection)
{
lock (_lock)
{
IModel channel = null;
try
{
channel = connection.Connection.CreateModel();
DeclareAndBindQueue(connection, channel);
BindEvents(channel);
_channel = channel;
}
catch (Exception ex)
{
channel.Cleanup(500, ex.Message);
throw new InvalidConnectionException(_address.Uri, "Invalid connection to host", ex);
}
}
}
void DeclareAndBindQueue(RabbitMqConnection connection, IModel channel)
{
if (_bindToQueue)
{
connection.DeclareExchange(channel, _address.Name, _address.Durable, _address.AutoDelete);
connection.BindQueue(channel, _address.Name, _address.Durable, _address.Exclusive, _address.AutoDelete,
_address.QueueArguments());
}
}
void BindEvents(IModel channel)
{
channel.BasicAcks += HandleAck;
channel.BasicNacks += HandleNack;
channel.BasicReturn += HandleReturn;
channel.FlowControl += HandleFlowControl;
channel.ModelShutdown += HandleModelShutdown;
channel.ConfirmSelect();
}
public void Unbind(RabbitMqConnection connection)
{
lock (_lock)
{
try
{
if (_channel != null)
{
#if NET40
WaitForPendingConfirms();
#endif
UnbindEvents(_channel);
_channel.Cleanup(200, "Producer Unbind");
}
}
finally
{
if (_channel != null)
_channel.Dispose();
_channel = null;
FailPendingConfirms();
}
}
}
void WaitForPendingConfirms()
{
try
{
bool timedOut;
_channel.WaitForConfirms(60.Seconds(), out timedOut);
if (timedOut)
_log.WarnFormat("Timeout waiting for all pending confirms on {0}", _address.Uri);
}
catch (Exception ex)
{
_log.Error("Waiting for pending confirms threw an exception", ex);
}
}
void UnbindEvents(IModel channel)
{
channel.BasicAcks -= HandleAck;
channel.BasicNacks -= HandleNack;
channel.BasicReturn -= HandleReturn;
channel.FlowControl -= HandleFlowControl;
channel.ModelShutdown -= HandleModelShutdown;
}
void FailPendingConfirms()
{
#if NET40
try
{
var exception = new MessageNotConfirmedException(_address.Uri,
"Publish not confirmed before channel closed");
_confirms.Each((id, task) => task.TrySetException(exception));
}
catch (Exception ex)
{
_log.Error("Exception while failing pending confirms", ex);
}
_confirms.Clear();
#endif
}
public IBasicProperties CreateProperties()
{
lock (_lock)
{
if (_channel == null)
throw new InvalidConnectionException(_address.Uri, "Channel should not be null");
return _channel.CreateBasicProperties();
}
}
public void Publish(string exchangeName, IBasicProperties properties, byte[] body)
{
lock (_lock)
{
if (_channel == null)
throw new InvalidConnectionException(_address.Uri, "No connection to RabbitMQ Host");
_channel.BasicPublish(exchangeName, "", properties, body);
}
}
#if NET40
public Task PublishAsync(string exchangeName, IBasicProperties properties, byte[] body)
{
lock (_lock)
{
if (_channel == null)
throw new InvalidConnectionException(_address.Uri, "No connection to RabbitMQ Host");
ulong deliveryTag = _channel.NextPublishSeqNo;
var task = new TaskCompletionSource<bool>();
_confirms.Add(deliveryTag, task);
try
{
_channel.BasicPublish(exchangeName, "", _mandatory, _immediate, properties, body);
}
catch
{
_confirms.Remove(deliveryTag);
throw;
}
return task.Task;
}
}
#endif
void HandleModelShutdown(IModel model, ShutdownEventArgs reason)
{
try
{
FailPendingConfirms();
}
catch (Exception ex)
{
_log.Error("Fail pending confirms failed during model shutdown", ex);
}
}
void HandleFlowControl(IModel sender, FlowControlEventArgs args)
{
}
void HandleReturn(IModel model, BasicReturnEventArgs args)
{
}
void HandleNack(IModel model, BasicNackEventArgs args)
{
#if NET40
IEnumerable<ulong> ids = Enumerable.Repeat(args.DeliveryTag, 1);
if (args.Multiple)
ids = _confirms.GetAllKeys().Where(x => x <= args.DeliveryTag);
var exception = new InvalidOperationException("Publish was nacked by the broker");
foreach (ulong id in ids)
{
_confirms[id].TrySetException(exception);
_confirms.Remove(id);
}
#endif
}
void HandleAck(IModel model, BasicAckEventArgs args)
{
#if NET40
IEnumerable<ulong> ids = Enumerable.Repeat(args.DeliveryTag, 1);
if (args.Multiple)
ids = _confirms.GetAllKeys().Where(x => x <= args.DeliveryTag);
foreach (ulong id in ids)
{
_confirms[id].TrySetResult(true);
_confirms.Remove(id);
}
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using MusicStoreServices.Areas.HelpPage.Models;
namespace MusicStoreServices.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 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 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)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.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 Rhea.API.Areas.HelpPage.ModelDescriptions;
using Rhea.API.Areas.HelpPage.Models;
namespace Rhea.API.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
// This class implements a text reader that reads from a string.
public class StringReader : TextReader
{
private string _s;
private int _pos;
private int _length;
public StringReader(string s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
_s = s;
_length = s.Length;
}
public override void Close()
{
Dispose(true);
}
protected override void Dispose(bool disposing)
{
_s = null;
_pos = 0;
_length = 0;
base.Dispose(disposing);
}
// Returns the next available character without actually reading it from
// the underlying string. The current position of the StringReader is not
// changed by this operation. The returned value is -1 if no further
// characters are available.
//
[Pure]
public override int Peek()
{
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
if (_pos == _length)
{
return -1;
}
return _s[_pos];
}
// Reads the next character from the underlying string. The returned value
// is -1 if no further characters are available.
//
public override int Read()
{
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
if (_pos == _length)
{
return -1;
}
return _s[_pos++];
}
// Reads a block of characters. This method will read up to count
// characters from this StringReader into the buffer character
// array starting at position index. Returns the actual number of
// characters read, or zero if the end of the string is reached.
//
public override int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
int n = _length - _pos;
if (n > 0)
{
if (n > count)
{
n = count;
}
_s.CopyTo(_pos, buffer, index, n);
_pos += n;
}
return n;
}
public override int Read(Span<char> buffer)
{
if (GetType() != typeof(StringReader))
{
// This overload was added affter the Read(char[], ...) overload, and so in case
// a derived type may have overridden it, we need to delegate to it, which the base does.
return base.Read(buffer);
}
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
int n = _length - _pos;
if (n > 0)
{
if (n > buffer.Length)
{
n = buffer.Length;
}
_s.AsReadOnlySpan().Slice(_pos, n).CopyTo(buffer);
_pos += n;
}
return n;
}
public override int ReadBlock(Span<char> buffer) => Read(buffer);
public override string ReadToEnd()
{
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
string s;
if (_pos == 0)
{
s = _s;
}
else
{
s = _s.Substring(_pos, _length - _pos);
}
_pos = _length;
return s;
}
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the underlying string has been reached.
//
public override string ReadLine()
{
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
int i = _pos;
while (i < _length)
{
char ch = _s[i];
if (ch == '\r' || ch == '\n')
{
string result = _s.Substring(_pos, i - _pos);
_pos = i + 1;
if (ch == '\r' && _pos < _length && _s[_pos] == '\n')
{
_pos++;
}
return result;
}
i++;
}
if (i > _pos)
{
string result = _s.Substring(_pos, i - _pos);
_pos = i;
return result;
}
return null;
}
#region Task based Async APIs
public override Task<string> ReadLineAsync()
{
return Task.FromResult(ReadLine());
}
public override Task<string> ReadToEndAsync()
{
return Task.FromResult(ReadToEnd());
}
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return Task.FromResult(ReadBlock(buffer, index, count));
}
public override ValueTask<int> ReadBlockAsync(Memory<char> buffer, CancellationToken cancellationToken = default) =>
cancellationToken.IsCancellationRequested ? new ValueTask<int>(Task.FromCanceled<int>(cancellationToken)) :
new ValueTask<int>(ReadBlock(buffer.Span));
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return Task.FromResult(Read(buffer, index, count));
}
public override ValueTask<int> ReadAsync(Memory<char> buffer, CancellationToken cancellationToken = default) =>
cancellationToken.IsCancellationRequested ? new ValueTask<int>(Task.FromCanceled<int>(cancellationToken)) :
new ValueTask<int>(Read(buffer.Span));
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
// Put the file to Assets/Plugins/Rider/Editor/ for Unity 5.2.2+
// the file to Assets/Plugins/Editor/Rider for Unity prior 5.2.2
namespace Assets.Plugins.Editor.Rider
{
[InitializeOnLoad]
public static class RiderPlugin
{
public static readonly string SlnFile;
private static readonly string DefaultApp = EditorPrefs.GetString("kScriptsDefaultApp");
private static readonly FileInfo RiderFileInfo = new FileInfo(DefaultApp);
public static bool IsDotNetFrameworkUsed {get { return RiderFileInfo.Extension == ".exe"; }}
internal static bool Enabled
{
get
{
if (string.IsNullOrEmpty(DefaultApp))
return false;
return DefaultApp.ToLower().Contains("rider"); // seems like .app doesn't exist as file
}
}
static RiderPlugin()
{
if (Enabled)
{
var newPath = RiderFileInfo.FullName;
// try to search the new version
switch (RiderFileInfo.Extension)
{
/*
Unity itself transforms lnk to exe
case ".lnk":
{
if (riderFileInfo.Directory != null && riderFileInfo.Directory.Exists)
{
var possibleNew = riderFileInfo.Directory.GetFiles("*ider*.lnk");
if (possibleNew.Length > 0)
newPath = possibleNew.OrderBy(a => a.LastWriteTime).Last().FullName;
}
break;
}*/
case ".exe":
{
var possibleNew =
RiderFileInfo.Directory.Parent.Parent.GetDirectories("*ider*")
.SelectMany(a => a.GetDirectories("bin"))
.SelectMany(a => a.GetFiles(RiderFileInfo.Name))
.ToArray();
if (possibleNew.Length > 0)
newPath = possibleNew.OrderBy(a => a.LastWriteTime).Last().FullName;
break;
}
default:
{
break;
}
}
if (newPath != RiderFileInfo.FullName)
{
Log(string.Format("Update {0} to {1}", RiderFileInfo.FullName, newPath));
EditorPrefs.SetString("kScriptsDefaultApp", newPath);
}
}
var projectDirectory = Directory.GetParent(Application.dataPath).FullName;
var projectName = Path.GetFileName(projectDirectory);
SlnFile = Path.Combine(projectDirectory, string.Format("{0}.sln", projectName));
}
/// <summary>
/// Asset Open Callback (from Unity)
/// </summary>
/// <remarks>
/// Called when Unity is about to open an asset.
/// </remarks>
[UnityEditor.Callbacks.OnOpenAssetAttribute()]
static bool OnOpenedAsset(int instanceID, int line)
{
if (Enabled && (RiderFileInfo.Exists || RiderFileInfo.Extension == ".app"))
{
string appPath = Path.GetDirectoryName(Application.dataPath);
// determine asset that has been double clicked in the project view
var selected = EditorUtility.InstanceIDToObject(instanceID);
if (selected.GetType().ToString() == "UnityEditor.MonoScript" ||
selected.GetType().ToString() == "UnityEngine.Shader")
{
var completeFilepath = appPath + Path.DirectorySeparatorChar +
AssetDatabase.GetAssetPath(selected);
var args = string.Format("{0}{1}{0} -l {2} {0}{3}{0}", "\"", SlnFile, line, completeFilepath);
CallRider(RiderFileInfo.FullName, args);
return true;
}
}
return false;
}
private static void CallRider(string riderPath, string args)
{
var proc = new Process();
if (new FileInfo(riderPath).Extension == ".app")
{
proc.StartInfo.FileName = "open";
proc.StartInfo.Arguments = string.Format("-n {0}{1}{0} --args {2}", "\"", "/" + riderPath, args);
Log(proc.StartInfo.FileName + " " + proc.StartInfo.Arguments);
}
else
{
proc.StartInfo.FileName = riderPath;
proc.StartInfo.Arguments = args;
Log("\"" + proc.StartInfo.FileName + "\"" + " " + proc.StartInfo.Arguments);
}
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
if (new FileInfo(riderPath).Extension == ".exe")
{
try
{
ActivateWindow();
}
catch (Exception e)
{
Log("Exception on ActivateWindow: " + e);
}
}
}
private static void ActivateWindow()
{
var process = Process.GetProcesses().FirstOrDefault(b => !b.HasExited && b.ProcessName.Contains("Rider"));
if (process != null)
{
// Collect top level windows
var topLevelWindows = User32Dll.GetTopLevelWindowHandles();
// Get process main window title
var windowHandle = topLevelWindows.FirstOrDefault(hwnd => User32Dll.GetWindowProcessId(hwnd) == process.Id);
if (windowHandle != IntPtr.Zero)
User32Dll.SetForegroundWindow(windowHandle);
}
}
[MenuItem("Assets/Open C# Project in Rider", false, 1000)]
static void MenuOpenProject()
{
// Force the project files to be sync
SyncSolution();
// Load Project
CallRider(RiderFileInfo.FullName, string.Format("{0}{1}{0}", "\"", SlnFile));
}
[MenuItem("Assets/Open C# Project in Rider", true, 1000)]
static bool ValidateMenuOpenProject()
{
return Enabled;
}
/// <summary>
/// Force Unity To Write Project File
/// </summary>
private static void SyncSolution()
{
System.Type T = System.Type.GetType("UnityEditor.SyncVS,UnityEditor");
System.Reflection.MethodInfo SyncSolution = T.GetMethod("SyncSolution",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
SyncSolution.Invoke(null, null);
}
public static void Log(object message)
{
Debug.Log("[Rider] " + message);
}
static class User32Dll
{
/// <summary>
/// Gets the ID of the process that owns the window.
/// Note that creating a <see cref="Process"/> wrapper for that is very expensive because it causes an enumeration of all the system processes to happen.
/// </summary>
public static int GetWindowProcessId(IntPtr hwnd)
{
uint dwProcessId;
GetWindowThreadProcessId(hwnd, out dwProcessId);
return unchecked((int) dwProcessId);
}
/// <summary>
/// Lists the handles of all the top-level windows currently available in the system.
/// </summary>
public static List<IntPtr> GetTopLevelWindowHandles()
{
var retval = new List<IntPtr>();
EnumWindowsProc callback = (hwnd, param) =>
{
retval.Add(hwnd);
return 1;
};
EnumWindows(Marshal.GetFunctionPointerForDelegate(callback), IntPtr.Zero);
GC.KeepAlive(callback);
return retval;
}
public delegate Int32 EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true, ExactSpelling = true)]
public static extern Int32 EnumWindows(IntPtr lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true, ExactSpelling = true)]
public static extern Int32 SetForegroundWindow(IntPtr hWnd);
}
}
}
// Developed using JetBrains Rider =)
| |
// 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: The structure for holding all of the data needed
** for object serialization and deserialization.
**
**
===========================================================*/
namespace System.Runtime.Serialization
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Remoting;
#if FEATURE_REMOTING
using System.Runtime.Remoting.Proxies;
#endif
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Security;
#if FEATURE_CORECLR
using System.Runtime.CompilerServices;
#endif
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SerializationInfo
{
private const int defaultSize = 4;
private const string s_mscorlibAssemblySimpleName = System.CoreLib.Name;
private const string s_mscorlibFileName = s_mscorlibAssemblySimpleName + ".dll";
// Even though we have a dictionary, we're still keeping all the arrays around for back-compat.
// Otherwise we may run into potentially breaking behaviors like GetEnumerator() not returning entries in the same order they were added.
internal String[] m_members;
internal Object[] m_data;
internal Type[] m_types;
private Dictionary<string, int> m_nameToIndex;
internal int m_currMember;
internal IFormatterConverter m_converter;
private String m_fullTypeName;
private String m_assemName;
private Type objectType;
private bool isFullTypeNameSetExplicit;
private bool isAssemblyNameSetExplicit;
private bool requireSameTokenInPartialTrust;
[CLSCompliant(false)]
public SerializationInfo(Type type, IFormatterConverter converter)
: this(type, converter, false)
{
}
[CLSCompliant(false)]
public SerializationInfo(Type type, IFormatterConverter converter, bool requireSameTokenInPartialTrust)
{
if ((object)type == null)
{
throw new ArgumentNullException("type");
}
if (converter == null)
{
throw new ArgumentNullException("converter");
}
Contract.EndContractBlock();
objectType = type;
m_fullTypeName = type.FullName;
m_assemName = type.Module.Assembly.FullName;
m_members = new String[defaultSize];
m_data = new Object[defaultSize];
m_types = new Type[defaultSize];
m_nameToIndex = new Dictionary<string, int>();
m_converter = converter;
this.requireSameTokenInPartialTrust = requireSameTokenInPartialTrust;
}
public String FullTypeName
{
get
{
return m_fullTypeName;
}
set
{
if (null == value)
{
throw new ArgumentNullException("value");
}
Contract.EndContractBlock();
m_fullTypeName = value;
isFullTypeNameSetExplicit = true;
}
}
public String AssemblyName
{
get
{
return m_assemName;
}
[SecuritySafeCritical]
set
{
if (null == value)
{
throw new ArgumentNullException("value");
}
Contract.EndContractBlock();
if (this.requireSameTokenInPartialTrust)
{
DemandForUnsafeAssemblyNameAssignments(this.m_assemName, value);
}
m_assemName = value;
isAssemblyNameSetExplicit = true;
}
}
[SecuritySafeCritical]
public void SetType(Type type)
{
if ((object)type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
if (this.requireSameTokenInPartialTrust)
{
DemandForUnsafeAssemblyNameAssignments(this.ObjectType.Assembly.FullName, type.Assembly.FullName);
}
if (!Object.ReferenceEquals(objectType, type))
{
objectType = type;
m_fullTypeName = type.FullName;
m_assemName = type.Module.Assembly.FullName;
isFullTypeNameSetExplicit = false;
isAssemblyNameSetExplicit = false;
}
}
private static bool Compare(byte[] a, byte[] b)
{
// if either or both assemblies do not have public key token, we should demand, hence, returning false will force a demand
if (a == null || b == null || a.Length == 0 || b.Length == 0 || a.Length != b.Length)
{
return false;
}
else
{
for (int i = 0; i < a.Length; i++)
{
if (a[i] != b[i]) return false;
}
return true;
}
}
[SecuritySafeCritical]
internal static void DemandForUnsafeAssemblyNameAssignments(string originalAssemblyName, string newAssemblyName)
{
#if !FEATURE_CORECLR
if (!IsAssemblyNameAssignmentSafe(originalAssemblyName, newAssemblyName))
{
CodeAccessPermission.Demand(PermissionType.SecuritySerialization);
}
#endif
}
internal static bool IsAssemblyNameAssignmentSafe(string originalAssemblyName, string newAssemblyName)
{
if (originalAssemblyName == newAssemblyName)
{
return true;
}
AssemblyName originalAssembly = new AssemblyName(originalAssemblyName);
AssemblyName newAssembly = new AssemblyName(newAssemblyName);
// mscorlib will get loaded by the runtime regardless of its string casing or its public key token,
// so setting the assembly name to mscorlib must always be protected by a demand
if (string.Equals(newAssembly.Name, s_mscorlibAssemblySimpleName, StringComparison.OrdinalIgnoreCase) ||
string.Equals(newAssembly.Name, s_mscorlibFileName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return Compare(originalAssembly.GetPublicKeyToken(), newAssembly.GetPublicKeyToken());
}
public int MemberCount
{
get
{
return m_currMember;
}
}
public Type ObjectType
{
get
{
return objectType;
}
}
public bool IsFullTypeNameSetExplicit
{
get
{
return isFullTypeNameSetExplicit;
}
}
public bool IsAssemblyNameSetExplicit
{
get
{
return isAssemblyNameSetExplicit;
}
}
public SerializationInfoEnumerator GetEnumerator()
{
return new SerializationInfoEnumerator(m_members, m_data, m_types, m_currMember);
}
private void ExpandArrays()
{
int newSize;
Contract.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember");
newSize = (m_currMember * 2);
//
// In the pathological case, we may wrap
//
if (newSize < m_currMember)
{
if (Int32.MaxValue > m_currMember)
{
newSize = Int32.MaxValue;
}
}
//
// Allocate more space and copy the data
//
String[] newMembers = new String[newSize];
Object[] newData = new Object[newSize];
Type[] newTypes = new Type[newSize];
Array.Copy(m_members, newMembers, m_currMember);
Array.Copy(m_data, newData, m_currMember);
Array.Copy(m_types, newTypes, m_currMember);
//
// Assign the new arrys back to the member vars.
//
m_members = newMembers;
m_data = newData;
m_types = newTypes;
}
public void AddValue(String name, Object value, Type type)
{
if (null == name)
{
throw new ArgumentNullException("name");
}
if ((object)type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
AddValueInternal(name, value, type);
}
public void AddValue(String name, Object value)
{
if (null == value)
{
AddValue(name, value, typeof(Object));
}
else
{
AddValue(name, value, value.GetType());
}
}
public void AddValue(String name, bool value)
{
AddValue(name, (Object)value, typeof(bool));
}
public void AddValue(String name, char value)
{
AddValue(name, (Object)value, typeof(char));
}
[CLSCompliant(false)]
public void AddValue(String name, sbyte value)
{
AddValue(name, (Object)value, typeof(sbyte));
}
public void AddValue(String name, byte value)
{
AddValue(name, (Object)value, typeof(byte));
}
public void AddValue(String name, short value)
{
AddValue(name, (Object)value, typeof(short));
}
[CLSCompliant(false)]
public void AddValue(String name, ushort value)
{
AddValue(name, (Object)value, typeof(ushort));
}
public void AddValue(String name, int value)
{
AddValue(name, (Object)value, typeof(int));
}
[CLSCompliant(false)]
public void AddValue(String name, uint value)
{
AddValue(name, (Object)value, typeof(uint));
}
public void AddValue(String name, long value)
{
AddValue(name, (Object)value, typeof(long));
}
[CLSCompliant(false)]
public void AddValue(String name, ulong value)
{
AddValue(name, (Object)value, typeof(ulong));
}
public void AddValue(String name, float value)
{
AddValue(name, (Object)value, typeof(float));
}
public void AddValue(String name, double value)
{
AddValue(name, (Object)value, typeof(double));
}
public void AddValue(String name, decimal value)
{
AddValue(name, (Object)value, typeof(decimal));
}
public void AddValue(String name, DateTime value)
{
AddValue(name, (Object)value, typeof(DateTime));
}
internal void AddValueInternal(String name, Object value, Type type)
{
if (m_nameToIndex.ContainsKey(name))
{
BCLDebug.Trace("SER", "[SerializationInfo.AddValue]Tried to add ", name, " twice to the SI.");
throw new SerializationException(Environment.GetResourceString("Serialization_SameNameTwice"));
}
m_nameToIndex.Add(name, m_currMember);
//
// If we need to expand the arrays, do so.
//
if (m_currMember >= m_members.Length)
{
ExpandArrays();
}
//
// Add the data and then advance the counter.
//
m_members[m_currMember] = name;
m_data[m_currMember] = value;
m_types[m_currMember] = type;
m_currMember++;
}
/*=================================UpdateValue==================================
**Action: Finds the value if it exists in the current data. If it does, we replace
** the values, if not, we append it to the end. This is useful to the
** ObjectManager when it's performing fixups.
**Returns: void
**Arguments: name -- the name of the data to be updated.
** value -- the new value.
** type -- the type of the data being added.
**Exceptions: None. All error checking is done with asserts. Although public in coreclr,
** it's not exposed in a contract and is only meant to be used by corefx.
==============================================================================*/
#if FEATURE_CORECLR
// This should not be used by clients: exposing out this functionality would allow children
// to overwrite their parent's values. It is public in order to give corefx access to it for
// its ObjectManager implementation, but it should not be exposed out of a contract.
public
#else
internal
#endif
void UpdateValue(String name, Object value, Type type)
{
Contract.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null");
Contract.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null");
Contract.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null");
int index = FindElement(name);
if (index < 0)
{
AddValueInternal(name, value, type);
}
else
{
m_data[index] = value;
m_types[index] = type;
}
}
private int FindElement(String name)
{
if (null == name)
{
throw new ArgumentNullException("name");
}
Contract.EndContractBlock();
BCLDebug.Trace("SER", "[SerializationInfo.FindElement]Looking for ", name, " CurrMember is: ", m_currMember);
int index;
if (m_nameToIndex.TryGetValue(name, out index))
{
return index;
}
return -1;
}
/*==================================GetElement==================================
**Action: Use FindElement to get the location of a particular member and then return
** the value of the element at that location. The type of the member is
** returned in the foundType field.
**Returns: The value of the element at the position associated with name.
**Arguments: name -- the name of the element to find.
** foundType -- the type of the element associated with the given name.
**Exceptions: None. FindElement does null checking and throws for elements not
** found.
==============================================================================*/
private Object GetElement(String name, out Type foundType)
{
int index = FindElement(name);
if (index == -1)
{
throw new SerializationException(Environment.GetResourceString("Serialization_NotFound", name));
}
Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
foundType = m_types[index];
Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
return m_data[index];
}
[System.Runtime.InteropServices.ComVisible(true)]
private Object GetElementNoThrow(String name, out Type foundType)
{
int index = FindElement(name);
if (index == -1)
{
foundType = null;
return null;
}
Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
foundType = m_types[index];
Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
return m_data[index];
}
//
// The user should call one of these getters to get the data back in the
// form requested.
//
[System.Security.SecuritySafeCritical] // auto-generated
public Object GetValue(String name, Type type)
{
if ((object)type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
RuntimeType rt = type as RuntimeType;
if (rt == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
Type foundType;
Object value;
value = GetElement(name, out foundType);
#if FEATURE_REMOTING
if (RemotingServices.IsTransparentProxy(value))
{
RealProxy proxy = RemotingServices.GetRealProxy(value);
if (RemotingServices.ProxyCheckCast(proxy, rt))
return value;
}
else
#endif
if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
{
return value;
}
Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
return m_converter.Convert(value, type);
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
internal Object GetValueNoThrow(String name, Type type)
{
Type foundType;
Object value;
Contract.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null");
Contract.Assert(type is RuntimeType, "[SerializationInfo.GetValue]type is not a runtime type");
value = GetElementNoThrow(name, out foundType);
if (value == null)
return null;
#if FEATURE_REMOTING
if (RemotingServices.IsTransparentProxy(value))
{
RealProxy proxy = RemotingServices.GetRealProxy(value);
if (RemotingServices.ProxyCheckCast(proxy, (RuntimeType)type))
return value;
}
else
#endif
if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
{
return value;
}
Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
return m_converter.Convert(value, type);
}
public bool GetBoolean(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(bool)))
{
return (bool)value;
}
return m_converter.ToBoolean(value);
}
public char GetChar(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(char)))
{
return (char)value;
}
return m_converter.ToChar(value);
}
[CLSCompliant(false)]
public sbyte GetSByte(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(sbyte)))
{
return (sbyte)value;
}
return m_converter.ToSByte(value);
}
public byte GetByte(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(byte)))
{
return (byte)value;
}
return m_converter.ToByte(value);
}
public short GetInt16(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(short)))
{
return (short)value;
}
return m_converter.ToInt16(value);
}
[CLSCompliant(false)]
public ushort GetUInt16(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(ushort)))
{
return (ushort)value;
}
return m_converter.ToUInt16(value);
}
public int GetInt32(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(int)))
{
return (int)value;
}
return m_converter.ToInt32(value);
}
[CLSCompliant(false)]
public uint GetUInt32(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(uint)))
{
return (uint)value;
}
return m_converter.ToUInt32(value);
}
public long GetInt64(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(long)))
{
return (long)value;
}
return m_converter.ToInt64(value);
}
[CLSCompliant(false)]
public ulong GetUInt64(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(ulong)))
{
return (ulong)value;
}
return m_converter.ToUInt64(value);
}
public float GetSingle(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(float)))
{
return (float)value;
}
return m_converter.ToSingle(value);
}
public double GetDouble(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(double)))
{
return (double)value;
}
return m_converter.ToDouble(value);
}
public decimal GetDecimal(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(decimal)))
{
return (decimal)value;
}
return m_converter.ToDecimal(value);
}
public DateTime GetDateTime(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(DateTime)))
{
return (DateTime)value;
}
return m_converter.ToDateTime(value);
}
public String GetString(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(String)) || value == null)
{
return (String)value;
}
return m_converter.ToString(value);
}
internal string[] MemberNames
{
get
{
return m_members;
}
}
internal object[] MemberValues
{
get
{
return m_data;
}
}
}
}
| |
#region License and Terms
//
// NCrontab - Crontab for .NET
// Copyright (c) 2008 Atif Aziz. All rights reserved.
// Portions Copyright (c) 2001 The OpenSymphony Group. 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
namespace NCrontab
{
#region Imports
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Debug = System.Diagnostics.Debug;
#endregion
/// <summary>
/// Represents a schedule initialized from the crontab expression.
/// </summary>
// ReSharper disable once PartialTypeWithSinglePart
public sealed partial class CrontabSchedule
{
readonly CrontabField? _seconds;
readonly CrontabField _minutes;
readonly CrontabField _hours;
readonly CrontabField _days;
readonly CrontabField _months;
readonly CrontabField _daysOfWeek;
static readonly CrontabField SecondZero = CrontabField.Seconds("0");
// ReSharper disable once PartialTypeWithSinglePart
public sealed partial class ParseOptions
{
public bool IncludingSeconds { get; set; }
}
//
// Crontab expression format:
//
// * * * * *
// - - - - -
// | | | | |
// | | | | +----- day of week (0 - 6) (Sunday=0)
// | | | +------- month (1 - 12)
// | | +--------- day of month (1 - 31)
// | +----------- hour (0 - 23)
// +------------- min (0 - 59)
//
// Star (*) in the value field above means all legal values as in
// braces for that column. The value column can have a * or a list
// of elements separated by commas. An element is either a number in
// the ranges shown above or two numbers in the range separated by a
// hyphen (meaning an inclusive range).
//
// Source: http://www.adminschoice.com/docs/crontab.htm
//
// Six-part expression format:
//
// * * * * * *
// - - - - - -
// | | | | | |
// | | | | | +--- day of week (0 - 6) (Sunday=0)
// | | | | +----- month (1 - 12)
// | | | +------- day of month (1 - 31)
// | | +--------- hour (0 - 23)
// | +----------- min (0 - 59)
// +------------- sec (0 - 59)
//
// The six-part expression behaves similarly to the traditional
// crontab format except that it can denotate more precise schedules
// that use a seconds component.
//
public static CrontabSchedule Parse(string expression) => Parse(expression, null);
public static CrontabSchedule Parse(string expression, ParseOptions? options) =>
TryParse(expression, options, v => v, e => throw e());
public static CrontabSchedule? TryParse(string expression) => TryParse(expression, null);
public static CrontabSchedule? TryParse(string expression, ParseOptions? options) =>
TryParse(expression ?? string.Empty, options, v => v, _ => (CrontabSchedule?)null);
public static T TryParse<T>(string expression,
Func<CrontabSchedule, T> valueSelector,
Func<ExceptionProvider, T> errorSelector) =>
TryParse(expression ?? string.Empty, null, valueSelector, errorSelector);
public static T TryParse<T>(string expression, ParseOptions? options, Func<CrontabSchedule, T> valueSelector, Func<ExceptionProvider, T> errorSelector)
{
if (expression == null) throw new ArgumentNullException(nameof(expression));
var tokens = expression.Split(StringSeparatorStock.Space, StringSplitOptions.RemoveEmptyEntries);
var includingSeconds = options != null && options.IncludingSeconds;
var expectedTokenCount = includingSeconds ? 6 : 5;
if (tokens.Length < expectedTokenCount || tokens.Length > expectedTokenCount)
{
return errorSelector(() =>
{
var components =
includingSeconds
? "6 components of a schedule in the sequence of seconds, minutes, hours, days, months, and days of week"
: "5 components of a schedule in the sequence of minutes, hours, days, months, and days of week";
return new CrontabException($"'{expression}' is an invalid crontab expression. It must contain {components}.");
});
}
var fields = new CrontabField[6];
var offset = includingSeconds ? 0 : 1;
for (var i = 0; i < tokens.Length; i++)
{
var kind = (CrontabFieldKind)i + offset;
var field = CrontabField.TryParse(kind, tokens[i], v => new { ErrorProvider = (ExceptionProvider?)null, Value = (CrontabField?)v },
e => new { ErrorProvider = (ExceptionProvider?)e , Value = (CrontabField?)null }) ;
if (field.ErrorProvider != null)
return errorSelector(field.ErrorProvider);
fields[i + offset] = field.Value!; // non-null by mutual exclusivity!
}
return valueSelector(new CrontabSchedule(fields[0], fields[1], fields[2], fields[3], fields[4], fields[5]));
}
CrontabSchedule(
CrontabField? seconds,
CrontabField minutes, CrontabField hours,
CrontabField days, CrontabField months,
CrontabField daysOfWeek)
{
_seconds = seconds;
_minutes = minutes;
_hours = hours;
_days = days;
_months = months;
_daysOfWeek = daysOfWeek;
}
/// <summary>
/// Enumerates all the occurrences of this schedule starting with a
/// base time and up to an end time limit. This method uses deferred
/// execution such that the occurrences are only calculated as they
/// are enumerated.
/// </summary>
/// <remarks>
/// This method does not return the value of <paramref name="baseTime"/>
/// itself if it falls on the schedule. For example, if <paramref name="baseTime" />
/// is midnight and the schedule was created from the expression <c>* * * * *</c>
/// (meaning every minute) then the next occurrence of the schedule
/// will be at one minute past midnight and not midnight itself.
/// The method returns the <em>next</em> occurrence <em>after</em>
/// <paramref name="baseTime"/>. Also, <param name="endTime" /> is
/// exclusive.
/// </remarks>
public IEnumerable<DateTime> GetNextOccurrences(DateTime baseTime, DateTime endTime)
{
for (var occurrence = TryGetNextOccurrence(baseTime, endTime);
occurrence != null && occurrence < endTime;
occurrence = TryGetNextOccurrence(occurrence.Value, endTime))
{
yield return occurrence.Value;
}
}
/// <summary>
/// Gets the next occurrence of this schedule starting with a base time.
/// </summary>
public DateTime GetNextOccurrence(DateTime baseTime) =>
GetNextOccurrence(baseTime, DateTime.MaxValue);
/// <summary>
/// Gets the next occurrence of this schedule starting with a base
/// time and up to an end time limit.
/// </summary>
/// <remarks>
/// This method does not return the value of <paramref name="baseTime"/>
/// itself if it falls on the schedule. For example, if <paramref name="baseTime" />
/// is midnight and the schedule was created from the expression <c>* * * * *</c>
/// (meaning every minute) then the next occurrence of the schedule
/// will be at one minute past midnight and not midnight itself.
/// The method returns the <em>next</em> occurrence <em>after</em>
/// <paramref name="baseTime"/>. Also, <param name="endTime" /> is
/// exclusive.
/// </remarks>
public DateTime GetNextOccurrence(DateTime baseTime, DateTime endTime) =>
TryGetNextOccurrence(baseTime, endTime) ?? endTime;
DateTime? TryGetNextOccurrence(DateTime baseTime, DateTime endTime)
{
const int nil = -1;
var baseYear = baseTime.Year;
var baseMonth = baseTime.Month;
var baseDay = baseTime.Day;
var baseHour = baseTime.Hour;
var baseMinute = baseTime.Minute;
var baseSecond = baseTime.Second;
var endYear = endTime.Year;
var endMonth = endTime.Month;
var endDay = endTime.Day;
var year = baseYear;
var month = baseMonth;
var day = baseDay;
var hour = baseHour;
var minute = baseMinute;
var second = baseSecond + 1;
//
// Second
//
var seconds = _seconds ?? SecondZero;
second = seconds.Next(second);
if (second == nil)
{
second = seconds.GetFirst();
minute++;
}
//
// Minute
//
minute = _minutes.Next(minute);
if (minute == nil)
{
second = seconds.GetFirst();
minute = _minutes.GetFirst();
hour++;
}
else if (minute > baseMinute)
{
second = seconds.GetFirst();
}
//
// Hour
//
hour = _hours.Next(hour);
if (hour == nil)
{
minute = _minutes.GetFirst();
hour = _hours.GetFirst();
day++;
}
else if (hour > baseHour)
{
second = seconds.GetFirst();
minute = _minutes.GetFirst();
}
//
// Day
//
day = _days.Next(day);
RetryDayMonth:
if (day == nil)
{
second = seconds.GetFirst();
minute = _minutes.GetFirst();
hour = _hours.GetFirst();
day = _days.GetFirst();
month++;
}
else if (day > baseDay)
{
second = seconds.GetFirst();
minute = _minutes.GetFirst();
hour = _hours.GetFirst();
}
//
// Month
//
month = _months.Next(month);
if (month == nil)
{
second = seconds.GetFirst();
minute = _minutes.GetFirst();
hour = _hours.GetFirst();
day = _days.GetFirst();
month = _months.GetFirst();
year++;
}
else if (month > baseMonth)
{
second = seconds.GetFirst();
minute = _minutes.GetFirst();
hour = _hours.GetFirst();
day = _days.GetFirst();
}
//
// Stop processing when year is too large for the datetime or calendar
// object. Otherwise we would get an exception.
//
if (year > Calendar.MaxSupportedDateTime.Year)
return null;
//
// The day field in a cron expression spans the entire range of days
// in a month, which is from 1 to 31. However, the number of days in
// a month tend to be variable depending on the month (and the year
// in case of February). So a check is needed here to see if the
// date is a border case. If the day happens to be beyond 28
// (meaning that we're dealing with the suspicious range of 29-31)
// and the date part has changed then we need to determine whether
// the day still makes sense for the given year and month. If the
// day is beyond the last possible value, then the day/month part
// for the schedule is re-evaluated. So an expression like "0 0
// 15,31 * *" will yield the following sequence starting on midnight
// of Jan 1, 2000:
//
// Jan 15, Jan 31, Feb 15, Mar 15, Apr 15, Apr 31, ...
//
var dateChanged = day != baseDay || month != baseMonth || year != baseYear;
if (day > 28 && dateChanged && day > Calendar.GetDaysInMonth(year, month))
{
if (year >= endYear && month >= endMonth && day >= endDay)
return endTime;
day = nil;
goto RetryDayMonth;
}
var nextTime = new DateTime(year, month, day, hour, minute, second, 0, baseTime.Kind);
if (nextTime >= endTime)
return endTime;
//
// Day of week
//
if (_daysOfWeek.Contains((int)nextTime.DayOfWeek))
return nextTime;
return TryGetNextOccurrence(new DateTime(year, month, day, 23, 59, 59, 0, baseTime.Kind), endTime);
}
/// <summary>
/// Returns a string in crontab expression (expanded) that represents
/// this schedule.
/// </summary>
public override string ToString()
{
var writer = new StringWriter(CultureInfo.InvariantCulture);
if (_seconds != null)
{
_seconds.Format(writer, true);
writer.Write(' ');
}
_minutes.Format(writer, true); writer.Write(' ');
_hours.Format(writer, true); writer.Write(' ');
_days.Format(writer, true); writer.Write(' ');
_months.Format(writer, true); writer.Write(' ');
_daysOfWeek.Format(writer, true);
return writer.ToString();
}
static Calendar Calendar => CultureInfo.InvariantCulture.Calendar;
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.Mvc;
namespace Coevery.UI.Resources {
public class ResourceDefinition {
private static readonly Dictionary<string, string> _resourceTypeTagNames = new Dictionary<string, string> {
{ "script", "script" },
{ "stylesheet", "link" }
};
private static readonly Dictionary<string, string> _filePathAttributes = new Dictionary<string, string> {
{ "script", "src" },
{ "link", "href" }
};
private static readonly Dictionary<string, Dictionary<string,string>> _resourceAttributes = new Dictionary<string, Dictionary<string,string>> {
{ "script", new Dictionary<string, string> { {"type", "text/javascript"} } },
{ "stylesheet", new Dictionary<string, string> { {"type", "text/css"}, {"rel", "stylesheet"} } }
};
private static readonly Dictionary<string, TagRenderMode> _fileTagRenderModes = new Dictionary<string, TagRenderMode> {
{ "script", TagRenderMode.Normal },
{ "link", TagRenderMode.SelfClosing }
};
private static readonly Dictionary<string, string> _resourceTypeDirectories = new Dictionary<string, string> {
{"script", "scripts/"},
{"stylesheet", "styles/"}
};
private string _basePath;
private readonly Dictionary<RequireSettings, string> _urlResolveCache = new Dictionary<RequireSettings, string>();
public ResourceDefinition(ResourceManifest manifest, string type, string name) {
Manifest = manifest;
Type = type;
Name = name;
TagBuilder = new TagBuilder(_resourceTypeTagNames.ContainsKey(type) ? _resourceTypeTagNames[type] : "meta");
TagRenderMode = _fileTagRenderModes.ContainsKey(TagBuilder.TagName) ? _fileTagRenderModes[TagBuilder.TagName] : TagRenderMode.Normal;
Dictionary<string, string> attributes;
if (_resourceAttributes.TryGetValue(type, out attributes)) {
foreach(var pair in attributes) {
TagBuilder.Attributes[pair.Key] = pair.Value;
}
}
FilePathAttributeName = _filePathAttributes.ContainsKey(TagBuilder.TagName) ? _filePathAttributes[TagBuilder.TagName] : null;
}
internal static string GetBasePathFromViewPath(string resourceType, string viewPath) {
if (String.IsNullOrEmpty(viewPath)) {
return null;
}
string basePath = null;
var viewsPartIndex = viewPath.IndexOf("/Views", StringComparison.OrdinalIgnoreCase);
if (viewsPartIndex >= 0) {
basePath = viewPath.Substring(0, viewsPartIndex + 1) + GetResourcePath(resourceType);
}
return basePath;
}
internal static string GetResourcePath(string resourceType) {
string path;
_resourceTypeDirectories.TryGetValue(resourceType, out path);
return path ?? "";
}
private static string Coalesce(params string[] strings) {
foreach (var str in strings) {
if (!String.IsNullOrEmpty(str)) {
return str;
}
}
return null;
}
public IResourceManifest Manifest { get; private set; }
public string TagName {
get { return TagBuilder.TagName; }
}
public TagRenderMode TagRenderMode { get; private set; }
public string Name { get; private set; }
public string Type { get; private set; }
public string Version { get; private set; }
public string BasePath {
get {
if (!String.IsNullOrEmpty(_basePath)) {
return _basePath;
}
var basePath = Manifest.BasePath;
if (!String.IsNullOrEmpty(basePath)) {
basePath += GetResourcePath(Type);
}
return basePath ?? "";
}
}
public string Url { get; private set; }
public string UrlDebug { get; private set; }
public string UrlCdn { get; private set; }
public string UrlCdnDebug { get; private set; }
public string[] Cultures { get; private set; }
public bool CdnSupportsSsl { get; private set; }
public IEnumerable<string> Dependencies { get; private set; }
public string FilePathAttributeName { get; private set; }
public TagBuilder TagBuilder { get; private set; }
public ResourceDefinition AddAttribute(string name, string value) {
TagBuilder.MergeAttribute(name, value);
return this;
}
public ResourceDefinition SetAttribute(string name, string value) {
TagBuilder.MergeAttribute(name, value, true);
return this;
}
public ResourceDefinition SetBasePath(string virtualPath) {
_basePath = virtualPath;
return this;
}
public ResourceDefinition SetUrl(string url) {
return SetUrl(url, null);
}
public ResourceDefinition SetUrl(string url, string urlDebug) {
if (String.IsNullOrEmpty(url)) {
throw new ArgumentNullException("url");
}
Url = url;
if (urlDebug != null) {
UrlDebug = urlDebug;
}
return this;
}
public ResourceDefinition SetCdn(string cdnUrl) {
return SetCdn(cdnUrl, null, null);
}
public ResourceDefinition SetCdn(string cdnUrl, string cdnUrlDebug) {
return SetCdn(cdnUrl, cdnUrlDebug, null);
}
public ResourceDefinition SetCdn(string cdnUrl, string cdnUrlDebug, bool? cdnSupportsSsl) {
if (String.IsNullOrEmpty(cdnUrl)) {
throw new ArgumentNullException("cdnUrl");
}
UrlCdn = cdnUrl;
if (cdnUrlDebug != null) {
UrlCdnDebug = cdnUrlDebug;
}
if (cdnSupportsSsl.HasValue) {
CdnSupportsSsl = cdnSupportsSsl.Value;
}
return this;
}
public ResourceDefinition SetVersion(string version) {
Version = version;
return this;
}
public ResourceDefinition SetCultures(params string[] cultures) {
Cultures = cultures;
return this;
}
public ResourceDefinition SetDependencies(params string[] dependencies) {
Dependencies = dependencies;
return this;
}
public string ResolveUrl(RequireSettings settings, string applicationPath) {
string url;
if (_urlResolveCache.TryGetValue(settings, out url)) {
return url;
}
// Url priority:
if (settings.DebugMode) {
url = settings.CdnMode
? Coalesce(UrlCdnDebug, UrlDebug, UrlCdn, Url)
: Coalesce(UrlDebug, Url, UrlCdnDebug, UrlCdn);
}
else {
url = settings.CdnMode
? Coalesce(UrlCdn, Url, UrlCdnDebug, UrlDebug)
: Coalesce(Url, UrlDebug, UrlCdn, UrlCdnDebug);
}
if (String.IsNullOrEmpty(url)) {
return null;
}
if (!String.IsNullOrEmpty(settings.Culture)) {
string nearestCulture = FindNearestCulture(settings.Culture);
if (!String.IsNullOrEmpty(nearestCulture)) {
url = Path.ChangeExtension(url, nearestCulture + Path.GetExtension(url));
}
}
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute) && !VirtualPathUtility.IsAbsolute(url) && !VirtualPathUtility.IsAppRelative(url) && !String.IsNullOrEmpty(BasePath)) {
// relative urls are relative to the base path of the module that defined the manifest
url = VirtualPathUtility.Combine(BasePath, url);
}
if (VirtualPathUtility.IsAppRelative(url)) {
url = VirtualPathUtility.ToAbsolute(url, applicationPath);
}
_urlResolveCache[settings] = url;
return url;
}
public string FindNearestCulture(string culture) {
// go for an exact match
if (Cultures == null) {
return null;
}
int selectedIndex = Array.IndexOf(Cultures, culture);
if (selectedIndex != -1) {
return Cultures[selectedIndex];
}
// try parent culture if any
var cultureInfo = CultureInfo.GetCultureInfo(culture);
if (cultureInfo.Parent.Name != culture) {
var selectedCulture = FindNearestCulture(cultureInfo.Parent.Name);
if (selectedCulture != null) {
return selectedCulture;
}
}
return null;
}
public override bool Equals(object obj) {
if (obj == null || obj.GetType() != GetType()) {
return false;
}
var that = (ResourceDefinition)obj;
return string.Equals(that.Name, Name, StringComparison.Ordinal) &&
string.Equals(that.Type, Type, StringComparison.Ordinal) &&
string.Equals(that.Version, Version, StringComparison.Ordinal);
}
public override int GetHashCode() {
return (Name ?? "").GetHashCode() ^ (Type ?? "").GetHashCode();
}
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
namespace Fungus
{
/// <summary>
/// Controls a character portrait.
/// </summary>
[CommandInfo("Narrative",
"Portrait",
"Controls a character portrait.")]
public class Portrait : ControlWithDisplay<DisplayType>
{
[Tooltip("Stage to display portrait on")]
[SerializeField] protected Stage stage;
[Tooltip("Character to display")]
[SerializeField] protected Character character;
[Tooltip("Character to swap with")]
[SerializeField] protected Character replacedCharacter;
[Tooltip("Portrait to display")]
[SerializeField] protected Sprite portrait;
[Tooltip("Move the portrait from/to this offset position")]
[SerializeField] protected PositionOffset offset;
[Tooltip("Move the portrait from this position")]
[SerializeField] protected RectTransform fromPosition;
[Tooltip("Move the portrait to this position")]
[SerializeField] protected RectTransform toPosition;
[Tooltip("Direction character is facing")]
[SerializeField] protected FacingDirection facing;
[Tooltip("Use Default Settings")]
[SerializeField] protected bool useDefaultSettings = true;
[Tooltip("Fade Duration")]
[SerializeField] protected float fadeDuration = 0.5f;
[Tooltip("Movement Duration")]
[SerializeField] protected float moveDuration = 1f;
[Tooltip("Shift Offset")]
[SerializeField] protected Vector2 shiftOffset;
[Tooltip("Move portrait into new position")]
[SerializeField] protected bool move;
[Tooltip("Start from offset position")]
[SerializeField] protected bool shiftIntoPlace;
[Tooltip("Wait until the tween has finished before executing the next command")]
[SerializeField] protected bool waitUntilFinished = false;
#region Public members
/// <summary>
/// Stage to display portrait on.
/// </summary>
public virtual Stage _Stage { get { return stage; } set { stage = value; } }
/// <summary>
/// Character to display.
/// </summary>
public virtual Character _Character { get { return character; } set { character = value; } }
/// <summary>
/// Portrait to display.
/// </summary>
public virtual Sprite _Portrait { get { return portrait; } set { portrait = value; } }
/// <summary>
/// Move the portrait from/to this offset position.
/// </summary>
public virtual PositionOffset Offset { get { return offset; } set { offset = value; } }
/// <summary>
/// Move the portrait from this position.
/// </summary>
public virtual RectTransform FromPosition { get { return fromPosition; } set { fromPosition = value;} }
/// <summary>
/// Move the portrait to this position.
/// </summary>
public virtual RectTransform ToPosition { get { return toPosition; } set { toPosition = value;} }
/// <summary>
/// Direction character is facing.
/// </summary>
public virtual FacingDirection Facing { get { return facing; } set { facing = value; } }
/// <summary>
/// Use Default Settings.
/// </summary>
public virtual bool UseDefaultSettings { get { return useDefaultSettings; } set { useDefaultSettings = value; } }
/// <summary>
/// Move portrait into new position.
/// </summary>
public virtual bool Move { get { return move; } set { move = value; } }
/// <summary>
/// Start from offset position.
/// </summary>
public virtual bool ShiftIntoPlace { get { return shiftIntoPlace; } set { shiftIntoPlace = value; } }
public override void OnEnter()
{
// Selected "use default Portrait Stage"
if (stage == null)
{
// If no default specified, try to get any portrait stage in the scene
stage = FindObjectOfType<Stage>();
// If portrait stage does not exist, do nothing
if (stage == null)
{
Continue();
return;
}
}
// If no display specified, do nothing
if (IsDisplayNone(display))
{
Continue();
return;
}
PortraitOptions options = new PortraitOptions();
options.character = character;
options.replacedCharacter = replacedCharacter;
options.portrait = portrait;
options.display = display;
options.offset = offset;
options.fromPosition = fromPosition;
options.toPosition = toPosition;
options.facing = facing;
options.useDefaultSettings = useDefaultSettings;
options.fadeDuration = fadeDuration;
options.moveDuration = moveDuration;
options.shiftOffset = shiftOffset;
options.move = move;
options.shiftIntoPlace = shiftIntoPlace;
options.waitUntilFinished = waitUntilFinished;
stage.RunPortraitCommand(options, Continue);
}
public override string GetSummary()
{
if (display == DisplayType.None && character == null)
{
return "Error: No character or display selected";
}
else if (display == DisplayType.None)
{
return "Error: No display selected";
}
else if (character == null)
{
return "Error: No character selected";
}
string displaySummary = "";
string characterSummary = "";
string fromPositionSummary = "";
string toPositionSummary = "";
string stageSummary = "";
string portraitSummary = "";
string facingSummary = "";
displaySummary = StringFormatter.SplitCamelCase(display.ToString());
if (display == DisplayType.Replace)
{
if (replacedCharacter != null)
{
displaySummary += " \"" + replacedCharacter.name + "\" with";
}
}
characterSummary = character.name;
if (stage != null)
{
stageSummary = " on \"" + stage.name + "\"";
}
if (portrait != null)
{
portraitSummary = " " + portrait.name;
}
if (shiftIntoPlace)
{
if (offset != 0)
{
fromPositionSummary = offset.ToString();
fromPositionSummary = " from " + "\"" + fromPositionSummary + "\"";
}
}
else if (fromPosition != null)
{
fromPositionSummary = " from " + "\"" + fromPosition.name + "\"";
}
if (toPosition != null)
{
string toPositionPrefixSummary = "";
if (move)
{
toPositionPrefixSummary = " to ";
}
else
{
toPositionPrefixSummary = " at ";
}
toPositionSummary = toPositionPrefixSummary + "\"" + toPosition.name + "\"";
}
if (facing != FacingDirection.None)
{
if (facing == FacingDirection.Left)
{
facingSummary = "<--";
}
if (facing == FacingDirection.Right)
{
facingSummary = "-->";
}
facingSummary = " facing \"" + facingSummary + "\"";
}
return displaySummary + " \"" + characterSummary + portraitSummary + "\"" + stageSummary + facingSummary + fromPositionSummary + toPositionSummary;
}
public override Color GetButtonColor()
{
return new Color32(230, 200, 250, 255);
}
public override void OnCommandAdded(Block parentBlock)
{
//Default to display type: show
display = DisplayType.Show;
}
#endregion
}
}
| |
using NBitcoin;
using NBitcoin.Protocol;
using NBitcoin.Protocol.Behaviors;
using System;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.BitcoinCore;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Models;
using WalletWasabi.Services;
namespace WalletWasabi.Wallets
{
/// <summary>
/// P2pBlockProvider is a blocks provider that provides blocks
/// from bitcoin nodes using the P2P bitcoin protocol.
/// </summary>
public class P2pBlockProvider : IBlockProvider
{
private Node _localBitcoinCoreNode = null;
public P2pBlockProvider(NodesGroup nodes, CoreNode coreNode, WasabiSynchronizer syncer, ServiceConfiguration serviceConfiguration, Network network)
{
Nodes = nodes;
CoreNode = coreNode;
Synchronizer = syncer;
ServiceConfiguration = serviceConfiguration;
Network = network;
}
public static event EventHandler<bool>? DownloadingBlockChanged;
public NodesGroup Nodes { get; }
public CoreNode CoreNode { get; }
public WasabiSynchronizer Synchronizer { get; }
public ServiceConfiguration ServiceConfiguration { get; }
public Network Network { get; }
public Node LocalBitcoinCoreNode
{
get
{
if (Network == Network.RegTest)
{
return Nodes.ConnectedNodes.First();
}
return _localBitcoinCoreNode;
}
private set => _localBitcoinCoreNode = value;
}
private int NodeTimeouts { get; set; }
/// <summary>
/// Gets a bitcoin block from bitcoin nodes using the p2p bitcoin protocol.
/// If a bitcoin node is available it fetches the blocks using the rpc interface.
/// </summary>
/// <param name="hash">The block's hash that identifies the requested block.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The requested bitcoin block.</returns>
public async Task<Block> GetBlockAsync(uint256 hash, CancellationToken cancellationToken)
{
Block? block = null;
try
{
DownloadingBlockChanged?.Invoke(null, true);
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
// Try to get block information from local running Core node first.
block = await TryDownloadBlockFromLocalNodeAsync(hash, cancellationToken).ConfigureAwait(false);
if (block is { })
{
break;
}
// If no connection, wait, then continue.
while (Nodes.ConnectedNodes.Count == 0)
{
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
}
// Select a random node we are connected to.
Node node = Nodes.ConnectedNodes.RandomElement();
if (node is null || !node.IsConnected)
{
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
continue;
}
// Download block from selected node.
try
{
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(RuntimeParams.Instance.NetworkNodeTimeout))) // 1/2 ADSL 512 kbit/s 00:00:32
{
using var lts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken);
block = await node.DownloadBlockAsync(hash, lts.Token).ConfigureAwait(false);
}
// Validate block
if (!block.Check())
{
DisconnectNode(node, $"Disconnected node: {node.RemoteSocketAddress}, because invalid block received.", force: true);
continue;
}
DisconnectNode(node, $"Disconnected node: {node.RemoteSocketAddress}. Block downloaded: {block.GetHash()}.");
await NodeTimeoutsAsync(false).ConfigureAwait(false);
}
catch (Exception ex) when (ex is OperationCanceledException or TimeoutException)
{
await NodeTimeoutsAsync(true).ConfigureAwait(false);
DisconnectNode(node, $"Disconnected node: {node.RemoteSocketAddress}, because block download took too long."); // it could be a slow connection and not a misbehaving node
continue;
}
catch (Exception ex)
{
Logger.LogDebug(ex);
DisconnectNode(node,
$"Disconnected node: {node.RemoteSocketAddress}, because block download failed: {ex.Message}.",
force: true);
continue;
}
break; // If got this far, then we have the block and it's valid. Break.
}
catch (Exception ex)
{
Logger.LogDebug(ex);
}
}
}
finally
{
DownloadingBlockChanged?.Invoke(null, false);
}
return block;
}
private async Task<Block?> TryDownloadBlockFromLocalNodeAsync(uint256 hash, CancellationToken cancellationToken)
{
if (CoreNode?.RpcClient is null)
{
try
{
if (LocalBitcoinCoreNode is null || (!LocalBitcoinCoreNode.IsConnected && Network != Network.RegTest)) // If RegTest then we're already connected do not try again.
{
DisconnectDisposeNullLocalBitcoinCoreNode();
using var handshakeTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
handshakeTimeout.CancelAfter(TimeSpan.FromSeconds(10));
var nodeConnectionParameters = new NodeConnectionParameters()
{
ConnectCancellation = handshakeTimeout.Token,
IsRelay = false,
UserAgent = $"/Wasabi:{Constants.ClientVersion}/"
};
// If an onion was added must try to use Tor.
// onlyForOnionHosts should connect to it if it's an onion endpoint automatically and non-Tor endpoints through clearnet/localhost
if (Synchronizer.HttpClientFactory.IsTorEnabled)
{
nodeConnectionParameters.TemplateBehaviors.Add(new SocksSettingsBehavior(Synchronizer.HttpClientFactory.TorEndpoint, onlyForOnionHosts: true, networkCredential: null, streamIsolation: false));
}
var localEndPoint = ServiceConfiguration.BitcoinCoreEndPoint;
var localNode = await Node.ConnectAsync(Network, localEndPoint, nodeConnectionParameters).ConfigureAwait(false);
try
{
Logger.LogInfo("TCP Connection succeeded, handshaking...");
localNode.VersionHandshake(Constants.LocalNodeRequirements, handshakeTimeout.Token);
var peerServices = localNode.PeerVersion.Services;
Logger.LogInfo("Handshake completed successfully.");
if (!localNode.IsConnected)
{
throw new InvalidOperationException($"Wasabi could not complete the handshake with the local node and dropped the connection.{Environment.NewLine}" +
"Probably this is because the node does not support retrieving full blocks or segwit serialization.");
}
LocalBitcoinCoreNode = localNode;
}
catch (OperationCanceledException) when (handshakeTimeout.IsCancellationRequested)
{
Logger.LogWarning($"Wasabi could not complete the handshake with the local node. Probably Wasabi is not whitelisted by the node.{Environment.NewLine}" +
"Use \"whitebind\" in the node configuration. (Typically whitebind=127.0.0.1:8333 if Wasabi and the node are on the same machine and whitelist=1.2.3.4 if they are not.)");
throw;
}
}
// Get Block from local node
Block blockFromLocalNode = null;
// Should timeout faster. Not sure if it should ever fail though. Maybe let's keep like this later for remote node connection.
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(64)))
{
blockFromLocalNode = await LocalBitcoinCoreNode.DownloadBlockAsync(hash, cts.Token).ConfigureAwait(false);
}
// Validate retrieved block
if (!blockFromLocalNode.Check())
{
throw new InvalidOperationException("Disconnected node, because invalid block received!");
}
// Retrieved block from local node and block is valid
Logger.LogInfo($"Block acquired from local P2P connection: {hash}.");
return blockFromLocalNode;
}
catch (Exception ex)
{
DisconnectDisposeNullLocalBitcoinCoreNode();
if (ex is SocketException)
{
Logger.LogTrace("Did not find local listening and running full node instance. Trying to fetch needed block from other source.");
}
else
{
Logger.LogWarning(ex);
}
}
}
else
{
try
{
var block = await CoreNode.RpcClient.GetBlockAsync(hash).ConfigureAwait(false);
Logger.LogInfo($"Block acquired from RPC connection: {hash}.");
return block;
}
catch (Exception ex)
{
Logger.LogWarning(ex);
}
}
return null;
}
private void DisconnectDisposeNullLocalBitcoinCoreNode()
{
if (LocalBitcoinCoreNode is { })
{
try
{
LocalBitcoinCoreNode?.Disconnect();
}
catch (Exception ex)
{
Logger.LogDebug(ex);
}
finally
{
try
{
LocalBitcoinCoreNode?.Dispose();
}
catch (Exception ex)
{
Logger.LogDebug(ex);
}
finally
{
LocalBitcoinCoreNode = null;
Logger.LogInfo($"Local {Constants.BuiltinBitcoinNodeName} node disconnected.");
}
}
}
}
private void DisconnectNode(Node node, string logIfDisconnect, bool force = false)
{
if (Nodes.ConnectedNodes.Count > 3 || force)
{
Logger.LogInfo(logIfDisconnect);
node.DisconnectAsync(logIfDisconnect);
}
}
/// <summary>
/// Current timeout used when downloading a block from the remote node. It is defined in seconds.
/// </summary>
private async Task NodeTimeoutsAsync(bool increaseDecrease)
{
if (increaseDecrease)
{
NodeTimeouts++;
}
else
{
NodeTimeouts--;
}
var timeout = RuntimeParams.Instance.NetworkNodeTimeout;
// If it times out 2 times in a row then increase the timeout.
if (NodeTimeouts >= 2)
{
NodeTimeouts = 0;
timeout *= 2;
}
else if (NodeTimeouts <= -3) // If it does not time out 3 times in a row, lower the timeout.
{
NodeTimeouts = 0;
timeout = (int)Math.Round(timeout * 0.7);
}
// Sanity check
if (timeout < 32)
{
timeout = 32;
}
else if (timeout > 600)
{
timeout = 600;
}
if (timeout == RuntimeParams.Instance.NetworkNodeTimeout)
{
return;
}
RuntimeParams.Instance.NetworkNodeTimeout = timeout;
await RuntimeParams.Instance.SaveAsync().ConfigureAwait(false);
Logger.LogInfo($"Current timeout value used on block download is: {timeout} seconds.");
}
}
}
| |
using System;
using System.IO;
using IdSharp.Common.Utils;
using IdSharp.Tagging.ID3v2.Extensions;
namespace IdSharp.Tagging.ID3v2.Frames
{
internal sealed class AudioText : Frame, IAudioText
{
private static readonly byte[] _scrambleTable;
private EncodingType _textEncoding;
private string _mimeType;
private string _equivalentText;
private byte[] _audioData;
private bool _isMpegOrAac;
static AudioText()
{
_scrambleTable = new byte[127];
_scrambleTable[0] = 0xFE;
for (int i = 0; ; i++)
{
byte n = NextByte(_scrambleTable[i]);
if (n == 0xFE)
break;
_scrambleTable[i + 1] = n;
}
}
private static byte[] Scramble(byte[] audioData)
{
byte[] newAudioData = new byte[audioData.Length];
for (int i = 0, j = 0; i < audioData.Length; i++, j++)
{
newAudioData[i] = (byte)(audioData[i] ^ _scrambleTable[j]);
if (j == 126) j = -1;
}
return newAudioData;
}
private static byte NextByte(byte n)
{
byte bit7 = (byte)((n >> 7) & 0x01);
byte bit6 = (byte)((n >> 6) & 0x01);
byte bit5 = (byte)((n >> 5) & 0x01);
byte bit4 = (byte)((n >> 4) & 0x01);
byte bit3 = (byte)((n >> 3) & 0x01);
byte bit2 = (byte)((n >> 2) & 0x01);
byte bit1 = (byte)((n >> 1) & 0x01);
byte bit0 = (byte)(n & 0x01);
byte newByte = (byte)(((bit6 ^ bit5) << 7) +
((bit5 ^ bit4) << 6) +
((bit4 ^ bit3) << 5) +
((bit3 ^ bit2) << 4) +
((bit2 ^ bit1) << 3) +
((bit1 ^ bit0) << 2) +
((bit7 ^ bit5) << 1) +
(bit6 ^ bit4));
return newByte;
}
public EncodingType TextEncoding
{
get { return _textEncoding; }
set
{
_textEncoding = value;
RaisePropertyChanged("TextEncoding");
}
}
public string MimeType
{
get { return _mimeType; }
set
{
_mimeType = value;
RaisePropertyChanged("MimeType");
}
}
public string EquivalentText
{
get { return _equivalentText; }
set
{
_equivalentText = value;
RaisePropertyChanged("EquivalentText");
}
}
public void SetAudioData(string mimeType, byte[] audioData, bool isMpegOrAac)
{
MimeType = mimeType;
_isMpegOrAac = isMpegOrAac;
if (audioData == null)
{
_audioData = null;
}
else
{
if (_isMpegOrAac)
_audioData = ID3v2Utils.ConvertToUnsynchronized(_audioData);
else
_audioData = Scramble(_audioData);
}
RaisePropertyChanged("AudioData");
}
public byte[] GetAudioData(AudioScramblingMode audioScramblingMode)
{
if (audioScramblingMode == AudioScramblingMode.Default)
audioScramblingMode = (_isMpegOrAac ? AudioScramblingMode.Unsynchronization : AudioScramblingMode.Scrambling);
switch (audioScramblingMode)
{
case AudioScramblingMode.Scrambling:
return Scramble(_audioData);
case AudioScramblingMode.Unsynchronization:
return ID3v2Utils.ReadUnsynchronized(_audioData);
default:
if (_audioData == null)
return null;
else
return (byte[])_audioData.Clone();
}
}
public override string GetFrameID(ID3v2TagVersion tagVersion)
{
switch (tagVersion)
{
case ID3v2TagVersion.ID3v24:
case ID3v2TagVersion.ID3v23:
return "ATXT";
case ID3v2TagVersion.ID3v22:
return null;
default:
throw new ArgumentException("Unknown tag version");
}
}
public override void Read(TagReadingInfo tagReadingInfo, Stream stream)
{
_frameHeader.Read(tagReadingInfo, ref stream);
int bytesLeft = _frameHeader.FrameSizeExcludingAdditions;
if (bytesLeft > 0)
{
TextEncoding = (EncodingType)stream.Read1(ref bytesLeft);
if (bytesLeft > 0)
{
MimeType = ID3v2Utils.ReadString(EncodingType.ISO88591, stream, ref bytesLeft);
if (bytesLeft > 1)
{
byte flags = stream.Read1(ref bytesLeft);
_isMpegOrAac = ((flags & 0x01) == 0x00);
EquivalentText = ID3v2Utils.ReadString(TextEncoding, stream, ref bytesLeft);
if (bytesLeft > 0)
{
_audioData = stream.Read(bytesLeft);
bytesLeft = 0;
}
}
else
{
EquivalentText = null;
_audioData = null;
}
}
else
{
MimeType = null;
EquivalentText = null;
_audioData = null;
}
}
else
{
TextEncoding = EncodingType.ISO88591;
MimeType = null;
EquivalentText = null;
_audioData = null;
}
if (bytesLeft > 0)
{
stream.Seek(bytesLeft, SeekOrigin.Current);
}
}
public override byte[] GetBytes(ID3v2TagVersion tagVersion)
{
if (_audioData == null || _audioData.Length == 0)
return new byte[0];
string frameID = GetFrameID(tagVersion);
if (frameID == null)
return new byte[0];
using (MemoryStream frameData = new MemoryStream())
{
byte[] mimeType = ID3v2Utils.GetStringBytes(tagVersion, EncodingType.ISO88591, MimeType, true);
byte[] equivText;
do
{
equivText = ID3v2Utils.GetStringBytes(tagVersion, TextEncoding, EquivalentText, true);
} while (this.RequiresFix(tagVersion, EquivalentText, equivText));
frameData.WriteByte((byte)TextEncoding);
frameData.Write(mimeType, 0, mimeType.Length);
frameData.WriteByte((byte)(_isMpegOrAac ? 0 : 1));
frameData.Write(equivText, 0, equivText.Length);
frameData.Write(_audioData, 0, _audioData.Length);
return _frameHeader.GetBytes(frameData, tagVersion, frameID);
}
}
}
}
| |
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityStandardAssets.Utility
{
using System;
using UnityEngine;
public class WaypointCircuit : MonoBehaviour
{
public WaypointList waypointList = new WaypointList();
[SerializeField] private bool smoothRoute = true;
private int numPoints;
private Vector3[] points;
private float[] distances;
public float editorVisualisationSubsteps = 100;
public float Length { get; private set; }
public Transform[] Waypoints
{
get { return waypointList.items; }
}
//this being here will save GC allocs
private int p0n;
private int p1n;
private int p2n;
private int p3n;
private float i;
private Vector3 P0;
private Vector3 P1;
private Vector3 P2;
private Vector3 P3;
// Use this for initialization
private void Awake()
{
if (Waypoints.Length > 1)
{
CachePositionsAndDistances();
}
numPoints = Waypoints.Length;
}
public RoutePoint GetRoutePoint(float dist)
{
// position and direction
Vector3 p1 = GetRoutePosition(dist);
Vector3 p2 = GetRoutePosition(dist + 0.1f);
Vector3 delta = p2 - p1;
return new RoutePoint(p1, delta.normalized);
}
public Vector3 GetRoutePosition(float dist)
{
int point = 0;
if (Length == 0)
{
Length = distances[distances.Length - 1];
}
dist = Mathf.Repeat(dist, Length);
while (distances[point] < dist)
{
++point;
}
// get nearest two points, ensuring points wrap-around start & end of circuit
p1n = ((point - 1) + numPoints)%numPoints;
p2n = point;
// found point numbers, now find interpolation value between the two middle points
i = Mathf.InverseLerp(distances[p1n], distances[p2n], dist);
if (smoothRoute)
{
// smooth catmull-rom calculation between the two relevant points
// get indices for the surrounding 2 points, because
// four points are required by the catmull-rom function
p0n = ((point - 2) + numPoints)%numPoints;
p3n = (point + 1)%numPoints;
// 2nd point may have been the 'last' point - a dupe of the first,
// (to give a value of max track distance instead of zero)
// but now it must be wrapped back to zero if that was the case.
p2n = p2n%numPoints;
P0 = points[p0n];
P1 = points[p1n];
P2 = points[p2n];
P3 = points[p3n];
return CatmullRom(P0, P1, P2, P3, i);
}
// simple linear lerp between the two points:
this.p1n = ((point - 1) + this.numPoints)%this.numPoints;
this.p2n = point;
return Vector3.Lerp(this.points[this.p1n], this.points[this.p2n], this.i);
}
private Vector3 CatmullRom(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float i)
{
// comments are no use here... it's the catmull-rom equation.
// Un-magic this, lord vector!
return 0.5f*
((2*p1) + (-p0 + p2)*i + (2*p0 - 5*p1 + 4*p2 - p3)*i*i +
(-p0 + 3*p1 - 3*p2 + p3)*i*i*i);
}
private void CachePositionsAndDistances()
{
// transfer the position of each point and distances between points to arrays for
// speed of lookup at runtime
points = new Vector3[Waypoints.Length + 1];
distances = new float[Waypoints.Length + 1];
float accumulateDistance = 0;
for (int i = 0; i < points.Length; ++i)
{
var t1 = Waypoints[(i)%Waypoints.Length];
var t2 = Waypoints[(i + 1)%Waypoints.Length];
if (t1 != null && t2 != null)
{
Vector3 p1 = t1.position;
Vector3 p2 = t2.position;
points[i] = Waypoints[i%Waypoints.Length].position;
distances[i] = accumulateDistance;
accumulateDistance += (p1 - p2).magnitude;
}
}
}
private void OnDrawGizmos()
{
DrawGizmos(false);
}
private void OnDrawGizmosSelected()
{
DrawGizmos(true);
}
private void DrawGizmos(bool selected)
{
waypointList.circuit = this;
if (Waypoints.Length > 1)
{
numPoints = Waypoints.Length;
CachePositionsAndDistances();
Length = distances[distances.Length - 1];
Gizmos.color = selected ? Color.yellow : new Color(1, 1, 0, 0.5f);
Vector3 prev = Waypoints[0].position;
if (smoothRoute)
{
for (float dist = 0; dist < Length; dist += Length/editorVisualisationSubsteps)
{
Vector3 next = GetRoutePosition(dist + 1);
Gizmos.DrawLine(prev, next);
prev = next;
}
Gizmos.DrawLine(prev, Waypoints[0].position);
}
else
{
for (int n = 0; n < Waypoints.Length; ++n)
{
Vector3 next = Waypoints[(n + 1)%Waypoints.Length].position;
Gizmos.DrawLine(prev, next);
prev = next;
}
}
}
}
[Serializable]
public class WaypointList
{
public WaypointCircuit circuit;
public Transform[] items = new Transform[0];
}
public struct RoutePoint
{
public Vector3 position;
public Vector3 direction;
public RoutePoint(Vector3 position, Vector3 direction)
{
this.position = position;
this.direction = direction;
}
}
}
}
namespace UnityStandardAssets.Utility.Inspector
{
using System;
using System.Collections;
using UnityEngine;
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof (WaypointCircuit.WaypointList))]
public class WaypointListDrawer : PropertyDrawer
{
private float lineHeight = 18;
private float spacing = 4;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
float x = position.x;
float y = position.y;
float inspectorWidth = position.width;
// Draw label
// Don't make child fields be indented
var indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
var items = property.FindPropertyRelative("items");
var titles = new[] {"Transform", "", "", ""};
var props = new[] {"transform", "^", "v", "-"};
var widths = new[] {.7f, .1f, .1f, .1f};
float lineHeight = 18;
bool changedLength = false;
if (items.arraySize > 0)
{
for (int i = -1; i < items.arraySize; ++i)
{
var item = items.GetArrayElementAtIndex(i);
float rowX = x;
for (int n = 0; n < props.Length; ++n)
{
float w = widths[n]*inspectorWidth;
// Calculate rects
Rect rect = new Rect(rowX, y, w, lineHeight);
rowX += w;
if (i == -1)
{
EditorGUI.LabelField(rect, titles[n]);
}
else
{
if (n == 0)
{
EditorGUI.ObjectField(rect, item.objectReferenceValue, typeof (Transform), true);
}
else
{
if (GUI.Button(rect, props[n]))
{
switch (props[n])
{
case "-":
items.DeleteArrayElementAtIndex(i);
items.DeleteArrayElementAtIndex(i);
changedLength = true;
break;
case "v":
if (i > 0)
{
items.MoveArrayElement(i, i + 1);
}
break;
case "^":
if (i < items.arraySize - 1)
{
items.MoveArrayElement(i, i - 1);
}
break;
}
}
}
}
}
y += lineHeight + spacing;
if (changedLength)
{
break;
}
}
}
else
{
// add button
var addButtonRect = new Rect((x + position.width) - widths[widths.Length - 1]*inspectorWidth, y,
widths[widths.Length - 1]*inspectorWidth, lineHeight);
if (GUI.Button(addButtonRect, "+"))
{
items.InsertArrayElementAtIndex(items.arraySize);
}
y += lineHeight + spacing;
}
// add all button
var addAllButtonRect = new Rect(x, y, inspectorWidth, lineHeight);
if (GUI.Button(addAllButtonRect, "Assign using all child objects"))
{
var circuit = property.FindPropertyRelative("circuit").objectReferenceValue as WaypointCircuit;
var children = new Transform[circuit.transform.childCount];
int n = 0;
foreach (Transform child in circuit.transform)
{
children[n++] = child;
}
Array.Sort(children, new TransformNameComparer());
circuit.waypointList.items = new Transform[children.Length];
for (n = 0; n < children.Length; ++n)
{
circuit.waypointList.items[n] = children[n];
}
}
y += lineHeight + spacing;
// rename all button
var renameButtonRect = new Rect(x, y, inspectorWidth, lineHeight);
if (GUI.Button(renameButtonRect, "Auto Rename numerically from this order"))
{
var circuit = property.FindPropertyRelative("circuit").objectReferenceValue as WaypointCircuit;
int n = 0;
foreach (Transform child in circuit.waypointList.items)
{
child.name = "Waypoint " + (n++).ToString("000");
}
}
y += lineHeight + spacing;
// Set indent back to what it was
EditorGUI.indentLevel = indent;
EditorGUI.EndProperty();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
SerializedProperty items = property.FindPropertyRelative("items");
float lineAndSpace = lineHeight + spacing;
return 40 + (items.arraySize*lineAndSpace) + lineAndSpace;
}
// comparer for check distances in ray cast hits
public class TransformNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Transform) x).name.CompareTo(((Transform) y).name);
}
}
}
#endif
}
| |
namespace Sharpen
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
public class FilePath
{
private string path;
private static long tempCounter;
public FilePath ()
{
}
public FilePath (string path)
: this ((string) null, path)
{
}
public FilePath (FilePath other, string child)
: this ((string) other, child)
{
}
public FilePath (string other, string child)
{
if (other == null) {
this.path = child;
} else {
while (child != null && child.Length > 0 && (child[0] == Path.DirectorySeparatorChar || child[0] == Path.AltDirectorySeparatorChar))
child = child.Substring (1);
if (!string.IsNullOrEmpty(other) && other[other.Length - 1] == Path.VolumeSeparatorChar)
other += Path.DirectorySeparatorChar;
this.path = Path.Combine (other, child);
}
}
public static implicit operator FilePath (string name)
{
return new FilePath (name);
}
public static implicit operator string (FilePath filePath)
{
return filePath == null ? null : filePath.path;
}
public override bool Equals (object obj)
{
FilePath other = obj as FilePath;
if (other == null)
return false;
return GetCanonicalPath () == other.GetCanonicalPath ();
}
public override int GetHashCode ()
{
return path.GetHashCode ();
}
public bool CanWrite ()
{
return FileHelper.Instance.CanWrite (this);
}
public bool CreateNewFile ()
{
try {
File.Open (path, FileMode.CreateNew).Close ();
return true;
} catch {
return false;
}
}
public static FilePath CreateTempFile ()
{
return new FilePath (Path.GetTempFileName ());
}
public static FilePath CreateTempFile (string prefix, string suffix)
{
return CreateTempFile (prefix, suffix, null);
}
public static FilePath CreateTempFile (string prefix, string suffix, FilePath directory)
{
string file;
if (prefix == null) {
throw new ArgumentNullException ("prefix");
}
if (prefix.Length < 3) {
throw new ArgumentException ("prefix must have at least 3 characters");
}
string str = (directory == null) ? Path.GetTempPath () : directory.GetPath ();
do {
file = Path.Combine (str, prefix + Interlocked.Increment (ref tempCounter) + suffix);
} while (File.Exists (file));
new FileOutputStream (file).Close ();
return new FilePath (file);
}
public bool Delete ()
{
try {
return FileHelper.Instance.Delete (this);
} catch (Exception exception) {
Console.WriteLine (exception);
return false;
}
}
public void DeleteOnExit ()
{
}
public bool Exists ()
{
return FileHelper.Instance.Exists (this);
}
public FilePath GetAbsoluteFile ()
{
return new FilePath (Path.GetFullPath (path));
}
public string GetAbsolutePath ()
{
return Path.GetFullPath (path);
}
public FilePath GetCanonicalFile ()
{
return new FilePath (GetCanonicalPath ());
}
public string GetCanonicalPath ()
{
string p = Path.GetFullPath (path);
p.TrimEnd (Path.DirectorySeparatorChar);
return p;
}
public string GetName ()
{
return Path.GetFileName (path);
}
public FilePath GetParentFile ()
{
return new FilePath (Path.GetDirectoryName (path));
}
public string GetPath ()
{
return path;
}
public bool IsAbsolute ()
{
return Path.IsPathRooted (path);
}
public bool IsDirectory ()
{
return FileHelper.Instance.IsDirectory (this);
}
public bool IsFile ()
{
return FileHelper.Instance.IsFile (this);
}
public long LastModified ()
{
return FileHelper.Instance.LastModified (this);
}
public long Length ()
{
return FileHelper.Instance.Length (this);
}
public string[] List ()
{
return List (null);
}
public string[] List (FilenameFilter filter)
{
try {
if (IsFile ())
return null;
List<string> list = new List<string> ();
foreach (string filePth in Directory.GetFileSystemEntries (path)) {
string fileName = Path.GetFileName (filePth);
if ((filter == null) || filter.Accept (this, fileName)) {
list.Add (fileName);
}
}
return list.ToArray ();
} catch {
return null;
}
}
public FilePath[] ListFiles ()
{
try {
if (IsFile ())
return null;
List<FilePath> list = new List<FilePath> ();
foreach (string filePath in Directory.GetFileSystemEntries (path)) {
list.Add (new FilePath (filePath));
}
return list.ToArray ();
} catch {
return null;
}
}
public FilePath[] ListFiles(FileFilter filter)
{
try
{
if (IsFile())
return null;
List<FilePath> list = new List<FilePath>();
foreach (string filePath in Directory.GetFileSystemEntries(path))
{
var item = new FilePath(filePath);
if (filter.Accept(item))
list.Add(item);
}
return list.ToArray();
}
catch
{
return null;
}
}
static void MakeDirWritable (string dir)
{
FileHelper.Instance.MakeDirWritable (dir);
}
static void MakeFileWritable (string file)
{
FileHelper.Instance.MakeFileWritable (file);
}
public bool Mkdir ()
{
try {
if (Directory.Exists (path))
return false;
Directory.CreateDirectory (path);
return true;
} catch (Exception) {
return false;
}
}
public bool Mkdirs ()
{
try {
if (Directory.Exists (path))
return false;
Directory.CreateDirectory (this.path);
return true;
} catch {
return false;
}
}
public bool RenameTo (FilePath file)
{
return RenameTo (file.path);
}
public bool RenameTo (string name)
{
return FileHelper.Instance.RenameTo (this, name);
}
public bool SetLastModified (long milis)
{
return FileHelper.Instance.SetLastModified(this, milis);
}
public bool SetReadOnly ()
{
return FileHelper.Instance.SetReadOnly (this);
}
public Uri ToURI ()
{
return new Uri (path);
}
// Don't change the case of this method, since ngit does reflection on it
public bool canExecute ()
{
return FileHelper.Instance.CanExecute (this);
}
// Don't change the case of this method, since ngit does reflection on it
public bool setExecutable (bool exec)
{
return FileHelper.Instance.SetExecutable (this, exec);
}
public string GetParent ()
{
string p = Path.GetDirectoryName (path);
if (string.IsNullOrEmpty(p) || p == path)
return null;
else
return p;
}
public override string ToString ()
{
return path;
}
static public string pathSeparator {
get { return Path.PathSeparator.ToString (); }
}
static public char pathSeparatorChar {
get { return Path.PathSeparator; }
}
static public char separatorChar {
get { return Path.DirectorySeparatorChar; }
}
static public string separator {
get { return Path.DirectorySeparatorChar.ToString (); }
}
}
}
| |
/*
*
* (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.ComponentModel;
using System.Globalization;
using System.Runtime.Serialization;
using ASC.Api.Interfaces;
using ASC.Core;
using Newtonsoft.Json;
namespace ASC.Specific
{
[DataContract(Name = "date", Namespace = "")]
[JsonConverter(typeof(ApiDateTimeConverter))]
[TypeConverter(typeof(ApiDateTimeTypeConverter))]
public class ApiDateTime : IComparable<ApiDateTime>, IApiDateTime, IComparable
{
private static readonly string[] Formats = new[]
{
"o",
"yyyy'-'MM'-'dd'T'HH'-'mm'-'ss'.'fffffffK",
"yyyy'-'MM'-'dd'T'HH'-'mm'-'ss'.'fffK",
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK",
"yyyy'-'MM'-'dd'T'HH'-'mm'-'ssK",
"yyyy'-'MM'-'dd'T'HH':'mm':'ssK",
"yyyy'-'MM'-'dd"
};
public ApiDateTime()
: this(null)
{
}
public ApiDateTime(DateTime? dateTime)
: this(dateTime, null)
{
}
public ApiDateTime(DateTime? dateTime, TimeZoneInfo timeZone)
{
if (dateTime.HasValue && dateTime.Value > DateTime.MinValue && dateTime.Value < DateTime.MaxValue)
{
SetDate(dateTime.Value, timeZone);
}
else
{
UtcTime = DateTime.MinValue;
TimeZoneOffset = TimeSpan.Zero;
}
}
public ApiDateTime(DateTime utcTime, TimeSpan offset)
{
UtcTime = new DateTime(utcTime.Ticks, DateTimeKind.Utc);
TimeZoneOffset = offset;
}
public static ApiDateTime Parse(string data)
{
return Parse(data, null);
}
public static ApiDateTime Parse(string data, TimeZoneInfo tz)
{
if (string.IsNullOrEmpty(data)) throw new ArgumentNullException("data");
if (data.Length < 7) throw new ArgumentException("invalid date time format");
var offsetPart = data.Substring(data.Length - 6, 6);
DateTime dateTime;
if (DateTime.TryParseExact(data, Formats, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out dateTime))
{
//Parse time
TimeSpan tzOffset = TimeSpan.Zero;
if (offsetPart.Contains(":") && TimeSpan.TryParse(offsetPart.TrimStart('+'), out tzOffset))
{
return new ApiDateTime(dateTime, tzOffset);
}
if (!data.EndsWith("Z", true, CultureInfo.InvariantCulture))
{
if (tz == null)
{
tz = GetTimeZoneInfo();
}
tzOffset = tz.GetUtcOffset(dateTime);
dateTime = dateTime.Subtract(tzOffset);
}
return new ApiDateTime(dateTime, tzOffset);
}
throw new ArgumentException("invalid date time format: " + data);
}
private void SetDate(DateTime value, TimeZoneInfo timeZone)
{
TimeZoneOffset = TimeSpan.Zero;
UtcTime = DateTime.MinValue;
if (timeZone == null)
{
timeZone = GetTimeZoneInfo();
}
//Hack
if (timeZone.IsInvalidTime(new DateTime(value.Ticks, DateTimeKind.Unspecified)))
{
value = value.AddHours(1);
}
if (value.Kind == DateTimeKind.Local)
{
value = TimeZoneInfo.ConvertTimeToUtc(new DateTime(value.Ticks, DateTimeKind.Unspecified), timeZone);
}
if (value.Kind == DateTimeKind.Unspecified)
{
//Assume it's utc
value = new DateTime(value.Ticks, DateTimeKind.Utc);
}
if (value.Kind == DateTimeKind.Utc)
{
UtcTime = value; //Set UTC time
TimeZoneOffset = timeZone.GetUtcOffset(value);
}
}
private static TimeZoneInfo GetTimeZoneInfo()
{
var timeZone = TimeZoneInfo.Local;
try
{
timeZone = CoreContext.TenantManager.GetCurrentTenant().TimeZone;
}
catch (Exception)
{
//Tenant failed
}
return timeZone;
}
private string ToRoundTripString(DateTime date, TimeSpan offset)
{
var dateString = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff", CultureInfo.InvariantCulture);
var offsetString = offset.Ticks == 0 ? "Z" : ((offset < TimeSpan.Zero) ? "-" : "+") + offset.ToString("hh\\:mm", CultureInfo.InvariantCulture);
return dateString + offsetString;
}
public static explicit operator ApiDateTime(DateTime d)
{
var date = new ApiDateTime(d);
return date;
}
public static explicit operator ApiDateTime(DateTime? d)
{
if (d.HasValue)
{
var date = new ApiDateTime(d);
return date;
}
return null;
}
public static bool operator >(ApiDateTime left, ApiDateTime right)
{
if (ReferenceEquals(left, right)) return false;
if (left == null) return false;
return left.CompareTo(right) > 0;
}
public static bool operator >=(ApiDateTime left, ApiDateTime right)
{
if (ReferenceEquals(left, right)) return false;
if (left == null) return false;
return left.CompareTo(right) >= 0;
}
public static bool operator <=(ApiDateTime left, ApiDateTime right)
{
return !(left >= right);
}
public static bool operator <(ApiDateTime left, ApiDateTime right)
{
return !(left > right);
}
public static bool operator ==(ApiDateTime left, ApiDateTime right)
{
return Equals(left, right);
}
public static bool operator !=(ApiDateTime left, ApiDateTime right)
{
return !(left == right);
}
public static implicit operator DateTime(ApiDateTime d)
{
if (d == null) return DateTime.MinValue;
return d.UtcTime;
}
public static implicit operator DateTime?(ApiDateTime d)
{
if (d == null) return null;
return d.UtcTime;
}
public int CompareTo(DateTime other)
{
return this.CompareTo(new ApiDateTime(other));
}
public int CompareTo(ApiDateTime other)
{
if (other == null) return 1;
return UtcTime.CompareTo(other.UtcTime);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(ApiDateTime)) return false;
return Equals((ApiDateTime)obj);
}
public bool Equals(ApiDateTime other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return UtcTime.Equals(other.UtcTime) && TimeZoneOffset.Equals(other.TimeZoneOffset);
}
public override int GetHashCode()
{
unchecked
{
return UtcTime.GetHashCode() * 397 + TimeZoneOffset.GetHashCode();
}
}
public int CompareTo(object obj)
{
if (obj is DateTime)
return CompareTo((DateTime)obj);
return obj is ApiDateTime ? CompareTo((ApiDateTime)obj) : 0;
}
public override string ToString()
{
DateTime localUtcTime = UtcTime;
if (!UtcTime.Equals(DateTime.MinValue))
localUtcTime = UtcTime.Add(TimeZoneOffset);
return ToRoundTripString(localUtcTime, TimeZoneOffset);
}
public DateTime UtcTime { get; private set; }
public TimeSpan TimeZoneOffset { get; private set; }
public static ApiDateTime GetSample()
{
return new ApiDateTime(DateTime.UtcNow, TimeSpan.Zero);
}
}
public class ApiDateTimeTypeConverter : DateTimeConverter
{
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
return value.ToString();
return base.ConvertTo(context, culture, value, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
return ApiDateTime.Parse((string)value);
}
if (value is DateTime)
{
return new ApiDateTime((DateTime)value);
}
return base.ConvertFrom(context, culture, value);
}
}
public class ApiDateTimeConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is IApiDateTime)
{
writer.WriteValue(value.ToString());
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return typeof(IApiDateTime).IsAssignableFrom(objectType);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace Lokad.Cqrs
{
public sealed class RedirectToCommand : HideObjectMembersFromIntelliSense
{
public readonly IDictionary<Type, Action<object>> Dict = new Dictionary<Type, Action<object>>();
static readonly MethodInfo InternalPreserveStackTraceMethod =
typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
public void WireToWhen(object o)
{
WireToMethod(o,"When");
}
public void WireToMethod(object o, string methodName)
{
var infos = o.GetType()
.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(m => m.Name == methodName)
.Where(m => m.GetParameters().Length == 1);
foreach (var methodInfo in infos)
{
var type = methodInfo.GetParameters().First().ParameterType;
var info = methodInfo;
Dict.Add(type, message => info.Invoke(o, new[] { message }));
}
}
public void WireToLambda<T>(Action<T> handler)
{
Dict.Add(typeof(T), o => handler((T)o));
}
public void InvokeMany(IEnumerable<object> messages, Action<object> onNull = null)
{
foreach (var message in messages)
{
Invoke(message, onNull);
}
}
[DebuggerNonUserCode]
public void Invoke(object message, Action<object> onNull = null)
{
Action<object> handler;
var type = message.GetType();
if (!Dict.TryGetValue(type, out handler))
{
handler = onNull ?? (o => { throw new InvalidOperationException("Failed to locate command handler for " + type); });
//Trace.WriteLine(string.Format("Discarding {0} - failed to locate event handler", type.Name));
}
try
{
handler(message);
}
catch (TargetInvocationException ex)
{
if (null != InternalPreserveStackTraceMethod)
InternalPreserveStackTraceMethod.Invoke(ex.InnerException, new object[0]);
throw ex.InnerException;
}
}
}
/// <summary>
/// Creates convention-based routing rules
/// </summary>
public sealed class RedirectToDynamicEvent
{
public readonly IDictionary<Type, List<Wire>> Dict = new Dictionary<Type, List<Wire>>();
public sealed class Wire
{
public Action<object> Call;
public Type ParameterType;
}
static readonly MethodInfo InternalPreserveStackTraceMethod =
typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
public void WireToWhen(object o)
{
var infos = o.GetType()
.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(m => m.Name == "When")
.Where(m => m.GetParameters().Length == 1);
foreach (var methodInfo in infos)
{
if (null == methodInfo)
throw new InvalidOperationException();
var wires = new HashSet<Type>();
var parameterType = methodInfo.GetParameters().First().ParameterType;
wires.Add(parameterType);
// if this is an interface, then we wire up to all inheritors in loaded assemblies
// TODO: make this explicit
if (parameterType.IsInterface)
{
throw new InvalidOperationException("We don't support wiring to interfaces");
//var inheritors = typeof(StartProjectRun).Assembly.GetExportedTypes().Where(parameterType.IsAssignableFrom);
//foreach (var inheritor in inheritors)
//{
// wires.Add(inheritor);
//}
}
foreach (var type in wires)
{
List<Wire> list;
if (!Dict.TryGetValue(type, out list))
{
list = new List<Wire>();
Dict.Add(type, list);
}
var wire = BuildWire(o, type, methodInfo);
list.Add(wire);
}
}
}
static Wire BuildWire(object o, Type type, MethodInfo methodInfo)
{
var info = methodInfo;
var dm = new DynamicMethod("MethodWrapper", null, new[] { typeof(object), typeof(object) });
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, o.GetType());
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Castclass, type);
il.EmitCall(OpCodes.Call, info, null);
il.Emit(OpCodes.Ret);
var call = (Action<object, object>)dm.CreateDelegate(typeof(Action<object, object>));
var wire = new Wire
{
Call = o1 => call(o, o1),
ParameterType = type
};
return wire;
}
public void WireTo<TMessage>(Action<TMessage> msg)
{
var type = typeof(TMessage);
List<Wire> list;
if (!Dict.TryGetValue(type, out list))
{
list = new List<Wire>();
Dict.Add(type, list);
}
list.Add(new Wire
{
Call = o => msg((TMessage)o)
});
}
[DebuggerNonUserCode]
public void InvokeEvent(object @event)
{
var type = @event.GetType();
List<Wire> info;
if (!Dict.TryGetValue(type, out info))
{
return;
}
try
{
foreach (var wire in info)
{
wire.Call(@event);
}
}
catch (TargetInvocationException ex)
{
if (null != InternalPreserveStackTraceMethod)
InternalPreserveStackTraceMethod.Invoke(ex.InnerException, new object[0]);
throw ex.InnerException;
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace tk2dEditor.SpriteCollectionEditor
{
public class FontView
{
public SpriteCollectionProxy SpriteCollection { get { return host.SpriteCollection; } }
IEditorHost host;
public FontView(IEditorHost host)
{
this.host = host;
}
Vector2 fontTextureScrollBar;
Vector2 fontEditorScrollBar;
public bool Draw(List<SpriteCollectionEditorEntry> selectedEntries)
{
if (selectedEntries.Count == 0 || selectedEntries[0].type != SpriteCollectionEditorEntry.Type.Font)
return false;
var entry = selectedEntries[selectedEntries.Count - 1];
var font = SpriteCollection.fonts[ entry.index ];
bool doDelete = false;
GUILayout.BeginHorizontal();
// Body
GUILayout.BeginVertical(tk2dEditorSkin.SC_BodyBackground, GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true));
fontTextureScrollBar = GUILayout.BeginScrollView(fontTextureScrollBar);
if (font.texture != null)
{
font.texture.filterMode = FilterMode.Point;
int border = 16;
Rect rect = GUILayoutUtility.GetRect(border + font.texture.width, border + font.texture.height, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
tk2dGrid.Draw(rect);
GUI.Label(new Rect(border + rect.x, border + rect.y, font.texture.width, font.texture.height), font.texture);
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
// Inspector
EditorGUIUtility.LookLikeControls(100.0f, 100.0f);
fontEditorScrollBar = GUILayout.BeginScrollView(fontEditorScrollBar, GUILayout.ExpandHeight(true), GUILayout.Width(host.InspectorWidth));
// Header
GUILayout.BeginVertical(tk2dEditorSkin.SC_InspectorHeaderBG, GUILayout.ExpandWidth(true));
Object newBmFont = EditorGUILayout.ObjectField("BM Font", font.bmFont, typeof(Object), false);
if (newBmFont != font.bmFont)
{
font.texture = null;
entry.name = "Empty";
font.bmFont = newBmFont;
if (newBmFont != null)
{
string bmFontPath = AssetDatabase.GetAssetPath(newBmFont);
tk2dEditor.Font.Info fontInfo = tk2dEditor.Font.Builder.ParseBMFont(bmFontPath);
if (fontInfo != null && fontInfo.texturePaths.Length > 0)
{
string path = System.IO.Path.GetDirectoryName(bmFontPath).Replace('\\', '/') + "/" + System.IO.Path.GetFileName(fontInfo.texturePaths[0]);;
font.texture = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D;
}
entry.name = font.Name;
host.OnSpriteCollectionSortChanged();
}
}
GUILayout.BeginHorizontal();
Texture2D newTexture = EditorGUILayout.ObjectField("Font Texture", font.texture, typeof(Texture2D), false) as Texture2D;
if (newTexture != font.texture)
{
font.texture = newTexture;
entry.name = font.Name;
host.OnSpriteCollectionSortChanged();
}
GUILayout.FlexibleSpace();
if (GUILayout.Button("Delete", EditorStyles.miniButton)) doDelete = true;
GUILayout.EndHorizontal();
GUILayout.EndVertical();
// Rest of inspector
GUILayout.BeginVertical(tk2dEditorSkin.SC_InspectorBG, GUILayout.ExpandWidth(true));
if (font.texture != null)
{
string assetPath = AssetDatabase.GetAssetPath(font.texture);
if (assetPath.Length > 0)
{
// make sure the source texture is npot and readable, and uncompressed
if (!tk2dSpriteCollectionBuilder.IsTextureImporterSetUp(assetPath))
{
if (tk2dGuiUtility.InfoBoxWithButtons(
"The texture importer needs to be reconfigured to be used as a font texture source. " +
"Please note that this will globally change this texture importer. ",
tk2dGuiUtility.WarningLevel.Info,
"Set up") != -1)
{
tk2dSpriteCollectionBuilder.ConfigureSpriteTextureImporter(assetPath);
AssetDatabase.ImportAsset(assetPath);
}
}
}
}
if (SpriteCollection.AllowAltMaterials && SpriteCollection.altMaterials.Length > 1)
{
List<int> altMaterialIndices = new List<int>();
List<string> altMaterialNames = new List<string>();
for (int i = 0; i < SpriteCollection.altMaterials.Length; ++i)
{
var mat = SpriteCollection.altMaterials[i];
if (mat == null) continue;
altMaterialIndices.Add(i);
altMaterialNames.Add(mat.name);
}
font.materialId = EditorGUILayout.IntPopup("Material", font.materialId, altMaterialNames.ToArray(), altMaterialIndices.ToArray());
}
if (font.data == null || font.editorData == null)
{
if (tk2dGuiUtility.InfoBoxWithButtons(
"A data object is required to build a font. " +
"Please create one or drag an existing data object into the inspector slot.\n",
tk2dGuiUtility.WarningLevel.Info,
"Create") != -1)
{
// make data folder
string root = SpriteCollection.GetOrCreateDataPath();
string name = font.bmFont?font.bmFont.name:"Unknown Font";
string editorDataPath = tk2dGuiUtility.SaveFileInProject("Save Font Data", root, name, "prefab");
if (editorDataPath.Length > 0)
{
int prefabOffset = editorDataPath.ToLower().IndexOf(".prefab");
string dataObjectPath = editorDataPath.Substring(0, prefabOffset) + " data.prefab";
// Create data object
{
GameObject go = new GameObject();
go.AddComponent<tk2dFontData>();
tk2dEditorUtility.SetGameObjectActive(go, false);
#if (UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4)
Object p = EditorUtility.CreateEmptyPrefab(dataObjectPath);
EditorUtility.ReplacePrefab(go, p);
#else
Object p = PrefabUtility.CreateEmptyPrefab(dataObjectPath);
PrefabUtility.ReplacePrefab(go, p);
#endif
GameObject.DestroyImmediate(go);
AssetDatabase.SaveAssets();
font.data = AssetDatabase.LoadAssetAtPath(dataObjectPath, typeof(tk2dFontData)) as tk2dFontData;
}
// Create editor object
{
GameObject go = new GameObject();
tk2dFont f = go.AddComponent<tk2dFont>();
f.proxyFont = true;
f.data = font.data;
tk2dEditorUtility.SetGameObjectActive(go, false);
#if (UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4)
Object p = EditorUtility.CreateEmptyPrefab(editorDataPath);
EditorUtility.ReplacePrefab(go, p, ReplacePrefabOptions.ConnectToPrefab);
#else
Object p = PrefabUtility.CreateEmptyPrefab(editorDataPath);
PrefabUtility.ReplacePrefab(go, p, ReplacePrefabOptions.ConnectToPrefab);
#endif
GameObject.DestroyImmediate(go);
tk2dFont loadedFont = AssetDatabase.LoadAssetAtPath(editorDataPath, typeof(tk2dFont)) as tk2dFont;
tk2dEditorUtility.GetOrCreateIndex().AddOrUpdateFont(loadedFont);
tk2dEditorUtility.CommitIndex();
font.editorData = AssetDatabase.LoadAssetAtPath(editorDataPath, typeof(tk2dFont)) as tk2dFont;
}
entry.name = font.Name;
host.OnSpriteCollectionSortChanged();
}
}
}
else
{
font.editorData = EditorGUILayout.ObjectField("Editor Data", font.editorData, typeof(tk2dFont), false) as tk2dFont;
font.data = EditorGUILayout.ObjectField("Font Data", font.data, typeof(tk2dFontData), false) as tk2dFontData;
}
if (font.data && font.editorData)
{
font.useGradient = EditorGUILayout.Toggle("Use Gradient", font.useGradient);
if (font.useGradient)
{
EditorGUI.indentLevel++;
Texture2D tex = EditorGUILayout.ObjectField("Gradient Tex", font.gradientTexture, typeof(Texture2D), false) as Texture2D;
if (font.gradientTexture != tex)
{
font.gradientTexture = tex;
List<Material> materials = new List<Material>();
materials.Add( SpriteCollection.altMaterials[font.materialId] );
for (int j = 0; j < SpriteCollection.platforms.Count; ++j)
{
if (!SpriteCollection.platforms[j].Valid) continue;
tk2dSpriteCollection data = SpriteCollection.platforms[j].spriteCollection;
materials.Add( data.altMaterials[font.materialId] );
}
for (int j = 0; j < materials.Count; ++j)
{
if (!materials[j].HasProperty("_GradientTex"))
{
Debug.LogError(string.Format("Cant find parameter '_GradientTex' in material '{0}'", materials[j].name));
}
else if (materials[j].GetTexture("_GradientTex") != tex)
{
materials[j].SetTexture("_GradientTex", font.gradientTexture);
EditorUtility.SetDirty(materials[j]);
}
}
}
font.gradientCount = EditorGUILayout.IntField("Gradient Count", font.gradientCount);
EditorGUI.indentLevel--;
}
}
//font.dupeCaps = EditorGUILayout.Toggle("Dupe caps", font.dupeCaps);
font.flipTextureY = EditorGUILayout.Toggle("Flip Texture Y", font.flipTextureY);
font.charPadX = EditorGUILayout.IntField("Char Pad X", font.charPadX);
GUILayout.EndVertical();
GUILayout.EndScrollView();
// make dragable
tk2dPreferences.inst.spriteCollectionInspectorWidth -= (int)tk2dGuiUtility.DragableHandle(4819284, GUILayoutUtility.GetLastRect(), 0, tk2dGuiUtility.DragDirection.Horizontal);
GUILayout.EndHorizontal();
if (doDelete &&
EditorUtility.DisplayDialog("Delete sprite", "Are you sure you want to delete the selected font?", "Yes", "No"))
{
font.active = false;
font.bmFont = null;
font.data = null;
font.texture = null;
SpriteCollection.Trim();
host.OnSpriteCollectionChanged(false);
}
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipelines.Testing;
using System.Numerics;
using Xunit;
namespace System.IO.Pipelines.Tests
{
public class SeekTests
{
[Theory]
[InlineData("a", "a", 'a', 0)]
[InlineData("ab", "a", 'a', 0)]
[InlineData("aab", "a", 'a', 0)]
[InlineData("acab", "a", 'a', 0)]
[InlineData("acab", "c", 'c', 1)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "lo", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "ol", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "ll", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "rml", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "mlr", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)]
[InlineData("aaaaaaaaaaalmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)]
[InlineData("aaaaaaaaaaacmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'm', 12)]
[InlineData("aaaaaaaaaaarmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'r', 11)]
[InlineData("/localhost:5000/PATH/%2FPATH2/ HTTP/1.1", " %?", '%', 21)]
[InlineData("/localhost:5000/PATH/%2FPATH2/?key=value HTTP/1.1", " %?", '%', 21)]
[InlineData("/localhost:5000/PATH/PATH2/?key=value HTTP/1.1", " %?", '?', 27)]
[InlineData("/localhost:5000/PATH/PATH2/ HTTP/1.1", " %?", ' ', 27)]
public void MemorySeek(string raw, string search, char expectResult, int expectIndex)
{
var cursors = BufferUtilities.CreateBuffer(raw);
ReadCursor start = cursors.Start;
ReadCursor end = cursors.End;
ReadCursor result = default(ReadCursor);
var searchFor = search.ToCharArray();
int found = -1;
if (searchFor.Length == 1)
{
found = ReadCursorOperations.Seek(start, end, out result, (byte)searchFor[0]);
}
else if (searchFor.Length == 2)
{
found = ReadCursorOperations.Seek(start, end, out result, (byte)searchFor[0], (byte)searchFor[1]);
}
else if (searchFor.Length == 3)
{
found = ReadCursorOperations.Seek(start, end, out result, (byte)searchFor[0], (byte)searchFor[1], (byte)searchFor[2]);
}
else
{
Assert.False(true, "Invalid test sample.");
}
Assert.Equal(expectResult, found);
Assert.Equal(expectIndex, result.Index - start.Index);
}
[Theory]
[MemberData(nameof(SeekByteLimitData))]
public void TestSeekByteLimitAcrossBlocks(string input, char seek, int limit, int expectedBytesScanned, int expectedReturnValue)
{
// Arrange
var input1 = input.Substring(0, input.Length / 2);
var input2 = input.Substring(input.Length / 2);
var buffer = BufferUtilities.CreateBuffer(input1, string.Empty, input2);
var block1 = buffer.Start;
var block2 = buffer.End;
// Act
ReadCursor result;
var end = limit > input.Length ? buffer.End : buffer.Slice(0, limit).End;
var returnValue = ReadCursorOperations.Seek(buffer.Start, end, out result, (byte)seek);
var returnValue_1 = ReadCursorOperations.Seek(buffer.Start, end, out result, (byte)seek, (byte)seek);
var returnValue_2 = ReadCursorOperations.Seek(buffer.Start, end, out result, (byte)seek, (byte)seek, (byte)seek);
// Assert
Assert.Equal(expectedReturnValue, returnValue);
Assert.Equal(expectedReturnValue, returnValue_1);
Assert.Equal(expectedReturnValue, returnValue_2);
if (expectedReturnValue != -1)
{
var seekCharIndex = input.IndexOf(seek);
var expectedEndBlock = limit <= input.Length / 2 ?
block1.Segment :
(seekCharIndex != -1 && seekCharIndex < input.Length / 2 ? block1.Segment : block2.Segment);
Assert.Same(expectedEndBlock, result.Segment);
var expectedEndIndex = expectedEndBlock.Start + (expectedEndBlock == block1.Segment ? input1.IndexOf(seek) : input2.IndexOf(seek));
Assert.Equal(expectedEndIndex, result.Index);
}
}
[Theory]
[MemberData(nameof(SeekByteLimitData))]
public void TestSeekByteLimitWithinSameBlock(string input, char seek, int limit, int expectedBytesScanned, int expectedReturnValue)
{
// Arrange
var buffer = BufferUtilities.CreateBuffer(input);
// Act
ReadCursor result;
var end = limit > input.Length ? buffer.End : buffer.Slice(0, limit).End;
var returnValue = ReadCursorOperations.Seek(buffer.Start, end, out result, (byte)seek);
var returnValue_1 = ReadCursorOperations.Seek(buffer.Start, end, out result, (byte)seek, (byte)seek);
var returnValue_2 = ReadCursorOperations.Seek(buffer.Start, end, out result, (byte)seek, (byte)seek, (byte)seek);
// Assert
Assert.Equal(expectedReturnValue, returnValue);
Assert.Equal(expectedReturnValue, returnValue_1);
Assert.Equal(expectedReturnValue, returnValue_2);
if (expectedReturnValue != -1)
{
Assert.Same(buffer.Start.Segment, result.Segment);
Assert.Equal(result.Segment.Start + input.IndexOf(seek), result.Index);
}
}
[Theory]
[MemberData(nameof(SeekIteratorLimitData))]
public void TestSeekIteratorLimitWithinSameBlock(string input, char seek, char limitAfter, int expectedReturnValue)
{
// Arrange
var afterSeek = (byte)'B';
var buffer = BufferUtilities.CreateBuffer(input);
var start = buffer.Start;
var scan1 = buffer.Start;
var veryEnd = buffer.End;
var scan2_1 = scan1;
var scan2_2 = scan1;
var scan3_1 = scan1;
var scan3_2 = scan1;
var scan3_3 = scan1;
var end = buffer.End;
// Act
var endReturnValue = ReadCursorOperations.Seek(start, veryEnd, out end, (byte)limitAfter);
end = buffer.Slice(end, 1).End;
var returnValue1 = ReadCursorOperations.Seek(start, end, out scan1, (byte)seek);
var returnValue2_1 = ReadCursorOperations.Seek(start, end, out scan2_1, (byte)seek, afterSeek);
var returnValue2_2 = ReadCursorOperations.Seek(start, end, out scan2_2, afterSeek, (byte)seek);
var returnValue3_1 = ReadCursorOperations.Seek(start, end, out scan3_1, (byte)seek, afterSeek, afterSeek);
var returnValue3_2 = ReadCursorOperations.Seek(start, end, out scan3_2, afterSeek, (byte)seek, afterSeek);
var returnValue3_3 = ReadCursorOperations.Seek(start, end, out scan3_3, afterSeek, afterSeek, (byte)seek);
// Assert
Assert.Equal(input.Contains(limitAfter) ? limitAfter : -1, endReturnValue);
Assert.Equal(expectedReturnValue, returnValue1);
Assert.Equal(expectedReturnValue, returnValue2_1);
Assert.Equal(expectedReturnValue, returnValue2_2);
Assert.Equal(expectedReturnValue, returnValue3_1);
Assert.Equal(expectedReturnValue, returnValue3_2);
Assert.Equal(expectedReturnValue, returnValue3_3);
if (expectedReturnValue != -1)
{
var block = start.Segment;
Assert.Same(block, scan1.Segment);
Assert.Same(block, scan2_1.Segment);
Assert.Same(block, scan2_2.Segment);
Assert.Same(block, scan3_1.Segment);
Assert.Same(block, scan3_2.Segment);
Assert.Same(block, scan3_3.Segment);
var expectedEndIndex = expectedReturnValue != -1 ? start.Index + input.IndexOf(seek) : end.Index;
Assert.Equal(expectedEndIndex, scan1.Index);
Assert.Equal(expectedEndIndex, scan2_1.Index);
Assert.Equal(expectedEndIndex, scan2_2.Index);
Assert.Equal(expectedEndIndex, scan3_1.Index);
Assert.Equal(expectedEndIndex, scan3_2.Index);
Assert.Equal(expectedEndIndex, scan3_3.Index);
}
}
[Theory]
[MemberData(nameof(SeekIteratorLimitData))]
public void TestSeekIteratorLimitAcrossBlocks(string input, char seek, char limitAt, int expectedReturnValue)
{
// Arrange
var afterSeek = (byte)'B';
var input1 = input.Substring(0, input.Length / 2);
var input2 = input.Substring(input.Length / 2);
var buffer = BufferUtilities.CreateBuffer(input1, string.Empty, input2);
var start = buffer.Start;
var scan1 = buffer.Start;
var veryEnd = buffer.End;
var scan2_1 = scan1;
var scan2_2 = scan1;
var scan3_1 = scan1;
var scan3_2 = scan1;
var scan3_3 = scan1;
var end = buffer.End;
// Act
var endReturnValue = ReadCursorOperations.Seek(start, veryEnd, out end, (byte)limitAt);
end = buffer.Move(end, 1);
var returnValue1 = ReadCursorOperations.Seek(start, end, out scan1, (byte)seek);
var returnValue2_1 = ReadCursorOperations.Seek(start, end, out scan2_1, (byte)seek, afterSeek);
var returnValue2_2 = ReadCursorOperations.Seek(start, end, out scan2_2, afterSeek, (byte)seek);
var returnValue3_1 = ReadCursorOperations.Seek(start, end, out scan3_1, (byte)seek, afterSeek, afterSeek);
var returnValue3_2 = ReadCursorOperations.Seek(start, end, out scan3_2, afterSeek, (byte)seek, afterSeek);
var returnValue3_3 = ReadCursorOperations.Seek(start, end, out scan3_3, afterSeek, afterSeek, (byte)seek);
// Assert
Assert.Equal(input.Contains(limitAt) ? limitAt : -1, endReturnValue);
Assert.Equal(expectedReturnValue, returnValue1);
Assert.Equal(expectedReturnValue, returnValue2_1);
Assert.Equal(expectedReturnValue, returnValue2_2);
Assert.Equal(expectedReturnValue, returnValue3_1);
Assert.Equal(expectedReturnValue, returnValue3_2);
Assert.Equal(expectedReturnValue, returnValue3_3);
if (expectedReturnValue != -1)
{
var seekCharIndex = input.IndexOf(seek);
var limitAtIndex = input.IndexOf(limitAt);
var expectedEndBlock = seekCharIndex != -1 && seekCharIndex < input.Length / 2 ?
start.Segment :
(limitAtIndex != -1 && limitAtIndex < input.Length / 2 ? start.Segment : end.Segment);
Assert.Same(expectedEndBlock, scan1.Segment);
Assert.Same(expectedEndBlock, scan2_1.Segment);
Assert.Same(expectedEndBlock, scan2_2.Segment);
Assert.Same(expectedEndBlock, scan3_1.Segment);
Assert.Same(expectedEndBlock, scan3_2.Segment);
Assert.Same(expectedEndBlock, scan3_3.Segment);
var expectedEndIndex = expectedReturnValue != -1 ?
expectedEndBlock.Start + (expectedEndBlock == start.Segment ? input1.IndexOf(seek) : input2.IndexOf(seek)) :
end.Index;
Assert.Equal(expectedEndIndex, scan1.Index);
Assert.Equal(expectedEndIndex, scan2_1.Index);
Assert.Equal(expectedEndIndex, scan2_2.Index);
Assert.Equal(expectedEndIndex, scan3_1.Index);
Assert.Equal(expectedEndIndex, scan3_2.Index);
Assert.Equal(expectedEndIndex, scan3_3.Index);
}
}
public static IEnumerable<object[]> SeekByteLimitData
{
get
{
var vectorSpan = Vector<byte>.Count;
// string input, char seek, int limit, int expectedBytesScanned, int expectedReturnValue
var data = new List<object[]>();
// Non-vector inputs
data.Add(new object[] { "hello, world", 'h', 12, 1, 'h' });
data.Add(new object[] { "hello, world", ' ', 12, 7, ' ' });
data.Add(new object[] { "hello, world", 'd', 12, 12, 'd' });
data.Add(new object[] { "hello, world", '!', 12, 12, -1 });
data.Add(new object[] { "hello, world", 'h', 13, 1, 'h' });
data.Add(new object[] { "hello, world", ' ', 13, 7, ' ' });
data.Add(new object[] { "hello, world", 'd', 13, 12, 'd' });
data.Add(new object[] { "hello, world", '!', 13, 12, -1 });
data.Add(new object[] { "hello, world", 'h', 5, 1, 'h' });
data.Add(new object[] { "hello, world", 'o', 5, 5, 'o' });
data.Add(new object[] { "hello, world", ',', 5, 5, -1 });
data.Add(new object[] { "hello, world", 'd', 5, 5, -1 });
data.Add(new object[] { "abba", 'a', 4, 1, 'a' });
data.Add(new object[] { "abba", 'b', 4, 2, 'b' });
// Vector inputs
// Single vector, no seek char in input, expect failure
data.Add(new object[] { new string('a', vectorSpan), 'b', vectorSpan, vectorSpan, -1 });
// Two vectors, no seek char in input, expect failure
data.Add(new object[] { new string('a', vectorSpan * 2), 'b', vectorSpan * 2, vectorSpan * 2, -1 });
// Two vectors plus non vector length (thus hitting slow path too), no seek char in input, expect failure
data.Add(new object[] { new string('a', vectorSpan * 2 + vectorSpan / 2), 'b', vectorSpan * 2 + vectorSpan / 2, vectorSpan * 2 + vectorSpan / 2, -1 });
// For each input length from 1/2 to 3 1/2 vector spans in 1/2 vector span increments...
for (var length = vectorSpan / 2; length <= vectorSpan * 3 + vectorSpan / 2; length += vectorSpan / 2)
{
// ...place the seek char at vector and input boundaries...
for (var i = Math.Min(vectorSpan - 1, length - 1); i < length; i += ((i + 1) % vectorSpan == 0) ? 1 : Math.Min(i + (vectorSpan - 1), length - 1))
{
var input = new StringBuilder(new string('a', length));
input[i] = 'b';
// ...and check with a seek byte limit before, at, and past the seek char position...
for (var limitOffset = -1; limitOffset <= 1; limitOffset++)
{
var limit = (i + 1) + limitOffset;
if (limit >= i + 1)
{
// ...that Seek() succeeds when the seek char is within that limit...
data.Add(new object[] { input.ToString(), 'b', limit, i + 1, 'b' });
}
else
{
// ...and fails when it's not.
data.Add(new object[] { input.ToString(), 'b', limit, Math.Min(length, limit), -1 });
}
}
}
}
return data;
}
}
public static IEnumerable<object[]> SeekIteratorLimitData
{
get
{
var vectorSpan = Vector<byte>.Count;
// string input, char seek, char limitAt, int expectedReturnValue
var data = new List<object[]>();
// Non-vector inputs
data.Add(new object[] { "hello, world", 'h', 'd', 'h' });
data.Add(new object[] { "hello, world", ' ', 'd', ' ' });
data.Add(new object[] { "hello, world", 'd', 'd', 'd' });
data.Add(new object[] { "hello, world", '!', 'd', -1 });
data.Add(new object[] { "hello, world", 'h', 'w', 'h' });
data.Add(new object[] { "hello, world", 'o', 'w', 'o' });
data.Add(new object[] { "hello, world", 'r', 'w', -1 });
data.Add(new object[] { "hello, world", 'd', 'w', -1 });
// Vector inputs
// Single vector, no seek char in input, expect failure
data.Add(new object[] { new string('a', vectorSpan), 'b', 'b', -1 });
// Two vectors, no seek char in input, expect failure
data.Add(new object[] { new string('a', vectorSpan * 2), 'b', 'b', -1 });
// Two vectors plus non vector length (thus hitting slow path too), no seek char in input, expect failure
data.Add(new object[] { new string('a', vectorSpan * 2 + vectorSpan / 2), 'b', 'b', -1 });
// For each input length from 1/2 to 3 1/2 vector spans in 1/2 vector span increments...
for (var length = vectorSpan / 2; length <= vectorSpan * 3 + vectorSpan / 2; length += vectorSpan / 2)
{
// ...place the seek char at vector and input boundaries...
for (var i = Math.Min(vectorSpan - 1, length - 1); i < length; i += ((i + 1) % vectorSpan == 0) ? 1 : Math.Min(i + (vectorSpan - 1), length - 1))
{
var input = new StringBuilder(new string('a', length));
input[i] = 'b';
// ...along with sentinel characters to seek the limit iterator to...
input[i - 1] = 'A';
if (i < length - 1) input[i + 1] = 'B';
// ...and check that Seek() succeeds with a limit iterator at or past the seek char position...
data.Add(new object[] { input.ToString(), 'b', 'b', 'b' });
if (i < length - 1) data.Add(new object[] { input.ToString(), 'b', 'B', 'b' });
// ...and fails with a limit iterator before the seek char position.
data.Add(new object[] { input.ToString(), 'b', 'A', -1 });
}
}
return data;
}
}
}
}
| |
/*
* 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.Globalization;
using System.Linq;
using QuantConnect.Brokerages.Zerodha.Messages;
using QuantConnect.Util;
namespace QuantConnect.Brokerages.Zerodha
{
/// <summary>
/// Provides the mapping between Lean symbols and Zerodha symbols.
/// </summary>
public class ZerodhaSymbolMapper : ISymbolMapper
{
/// <summary>
/// Symbols that are Tradable
/// </summary>
public List<Symbol> KnownSymbols
{
get
{
return KnownSymbolsList;
}
}
/// <summary>
/// Custom class to store information about symbols
/// </summary>
private class SymbolData
{
/// <summary>
/// Stores exchange name for the tradingSymbol
/// </summary>
public string Exchange { get; set;}
/// <summary>
/// Stores instrumentToken name for the tradingSymbol
/// </summary>
public uint InstrumentToken {get; set;}
/// <summary>
/// Initalize values to the class attributes
/// </summary>
public SymbolData(uint token, string exchangeName)
{
Exchange = exchangeName;
InstrumentToken = token;
}
}
/// <summary>
/// The list of known Zerodha symbols.
/// </summary>
private List<Symbol> KnownSymbolsList = new List<Symbol>();
/// <summary>
/// Mapping between brokerageSymbol and a list of all available SymbolData objects for the brokerageSymbol.
/// </summary>
private Dictionary<string, List<SymbolData>> ZerodhaInstrumentsList = new Dictionary<string, List<SymbolData>>();
/// <summary>
/// Mapping between instrumentToken and it's market segment ( E.g: 408065-> nse)
/// </summary>
private Dictionary<uint,string> ZerodhaInstrumentsExchangeMapping = new Dictionary<uint,string>();
/// <summary>
/// Constructs default instance of the Zerodha Sybol Mapper
/// </summary>
public ZerodhaSymbolMapper(Kite kite, string exchange = "")
{
KnownSymbolsList = GetTradableInstrumentsList(kite, exchange);
}
/// <summary>
/// Get list of tradable symbol
/// </summary>
/// <param name="kite">Kite</param>
/// <param name="exchange">Exchange</param>
/// <returns></returns>
private List<Symbol> GetTradableInstrumentsList(Kite kite, string exchange = "")
{
var tradableInstruments = kite.GetInstruments(exchange);
var symbols = new List<Symbol>();
var zerodhaInstrumentsMapping = new Dictionary<string, List<SymbolData>>();
var zerodhaTokenExchangeDict = new Dictionary<uint,string>();
foreach (var tp in tradableInstruments)
{
var securityType = SecurityType.Equity;
var market = Market.India;
zerodhaTokenExchangeDict[tp.InstrumentToken] = tp.Exchange.ToLowerInvariant();
OptionRight optionRight = 0;
switch (tp.InstrumentType)
{
//Equities
case "EQ":
securityType = SecurityType.Equity;
break;
//Call Options
case "CE":
securityType = SecurityType.Option;
optionRight = OptionRight.Call;
break;
//Put Options
case "PE":
securityType = SecurityType.Option;
optionRight = OptionRight.Put;
break;
//Stock Futures
case "FUT":
securityType = SecurityType.Future;
break;
default:
securityType = SecurityType.Base;
break;
}
if (securityType == SecurityType.Option)
{
var strikePrice = tp.Strike;
var expiryDate = tp.Expiry;
//TODO: Handle parsing of BCDOPT strike price
if(tp.Segment!= "BCD-OPT")
{
var symbol = GetLeanSymbol(tp.Name.Trim().Replace(" ", ""), securityType, market, (DateTime)expiryDate, GetStrikePrice(tp), optionRight);
symbols.Add(symbol);
var cleanSymbol = tp.TradingSymbol.Trim().Replace(" ", "");
if (!zerodhaInstrumentsMapping.ContainsKey(cleanSymbol))
{
zerodhaInstrumentsMapping[cleanSymbol] = new List<SymbolData>();
}
zerodhaInstrumentsMapping[cleanSymbol].Add(new SymbolData(tp.InstrumentToken,market));
}
}
if (securityType == SecurityType.Future)
{
var expiryDate = tp.Expiry;
var cleanSymbol = tp.TradingSymbol.Trim().Replace(" ", "");
var symbol = GetLeanSymbol(cleanSymbol, securityType, market, (DateTime)expiryDate);
symbols.Add(symbol);
if (!zerodhaInstrumentsMapping.ContainsKey(cleanSymbol))
{
zerodhaInstrumentsMapping[cleanSymbol] = new List<SymbolData>();
}
zerodhaInstrumentsMapping[cleanSymbol].Add(new SymbolData(tp.InstrumentToken,market));
}
if (securityType == SecurityType.Equity)
{
var cleanSymbol = tp.TradingSymbol.Trim().Replace(" ", "");
var symbol = GetLeanSymbol(cleanSymbol, securityType, market);
symbols.Add(symbol);
if (!zerodhaInstrumentsMapping.ContainsKey(cleanSymbol))
{
zerodhaInstrumentsMapping[cleanSymbol] = new List<SymbolData>();
}
zerodhaInstrumentsMapping[cleanSymbol].Add(new SymbolData(tp.InstrumentToken,market));
}
}
ZerodhaInstrumentsList = zerodhaInstrumentsMapping;
ZerodhaInstrumentsExchangeMapping = zerodhaTokenExchangeDict;
return symbols;
}
private decimal GetStrikePrice(CsvInstrument scrip)
{
var strikePrice = scrip.TradingSymbol.Trim().Replace(" ", "").Replace(scrip.Name, "");
var strikePriceTemp = strikePrice.Substring(5, strikePrice.Length - 5);
var strikePriceResult = strikePriceTemp.Substring(0, strikePriceTemp.Length - 2);
return Convert.ToDecimal(strikePriceResult, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts a Lean symbol instance to an Zerodha symbol
/// </summary>
/// <param name="symbol">A Lean symbol instance</param>
/// <returns>The Zerodha symbol</returns>
public string GetBrokerageSymbol(Symbol symbol)
{
if (symbol == null || string.IsNullOrWhiteSpace(symbol.Value))
{
throw new ArgumentException("Invalid symbol: " + (symbol == null ? "null" : symbol.ToString()));
}
if (symbol.ID.SecurityType != SecurityType.Equity && symbol.ID.SecurityType != SecurityType.Future && symbol.ID.SecurityType != SecurityType.Option)
{
throw new ArgumentException("Invalid security type: " + symbol.ID.SecurityType);
}
var brokerageSymbol = ConvertLeanSymbolToZerodhaSymbol(symbol.Value);
return brokerageSymbol;
}
/// <summary>
/// Converts an Zerodha symbol to a Lean symbol instance
/// </summary>
/// <param name="brokerageSymbol">The Zerodha symbol</param>
/// <param name="securityType">The security type</param>
/// <param name="market">The market</param>
/// <param name="expirationDate">Expiration date of the security(if applicable)</param>
/// <param name="strike">The strike of the security (if applicable)</param>
/// <param name="optionRight">The option right of the security (if applicable)</param>
/// <returns>A new Lean Symbol instance</returns>
public Symbol GetLeanSymbol(string brokerageSymbol, SecurityType securityType, string market, DateTime expirationDate = default(DateTime), decimal strike = 0, OptionRight optionRight = OptionRight.Call)
{
if (string.IsNullOrWhiteSpace(brokerageSymbol))
{
throw new ArgumentException($"Invalid Zerodha symbol: {brokerageSymbol}");
}
if (securityType == SecurityType.Forex || securityType == SecurityType.Cfd || securityType == SecurityType.Commodity || securityType == SecurityType.Crypto)
{
throw new ArgumentException($"Invalid security type: {securityType}");
}
if (!Market.Encode(market).HasValue)
{
throw new ArgumentException($"Invalid market: {market}");
}
var cleanSymbol = brokerageSymbol.Replace(" ", "").Trim();
switch (securityType)
{
case SecurityType.Option:
OptionStyle optionStyle = OptionStyle.European;
return Symbol.CreateOption(cleanSymbol, market, optionStyle, optionRight, strike, expirationDate);
case SecurityType.Future:
return Symbol.CreateFuture(cleanSymbol, market, expirationDate);
default:
return Symbol.Create(cleanSymbol, securityType, market);
}
}
/// <summary>
/// Converts an Zerodha symbol to a Lean symbol instance
/// </summary>
/// <param name="brokerageSymbol">The Zerodha symbol</param>
/// <returns>A new Lean Symbol instance</returns>
public Symbol GetLeanSymbol(string brokerageSymbol)
{
if (string.IsNullOrWhiteSpace(brokerageSymbol))
{
throw new ArgumentException($"Invalid Zerodha symbol: {brokerageSymbol}");
}
var cleanSymbol = brokerageSymbol.Replace(" ", "").Trim();
if (IsKnownBrokerageSymbol(cleanSymbol))
{
throw new ArgumentException($"Symbol not present : {cleanSymbol}");
}
var symbol = KnownSymbols.FirstOrDefault(s => s.Value == cleanSymbol);
var exchange = GetZerodhaDefaultExchange(cleanSymbol);
return GetLeanSymbol(cleanSymbol, symbol.SecurityType, exchange);
}
/// <summary>
/// Fetches the trading segment inside India Market, E.g: NSE, BSE for the given Instrument Token
/// </summary>
/// <param name="Token">The Zerodha Instrument Token</param>
/// <returns>An exchange value for the given token</returns>
public string GetZerodhaExchangeFromToken(uint Token)
{
string exchange = string.Empty;
if (ZerodhaInstrumentsExchangeMapping.ContainsKey(Token))
{
ZerodhaInstrumentsExchangeMapping.TryGetValue(Token, out exchange);
}
return exchange;
}
/// <summary>
/// Fetches the first available Exchage value for the given symbol from list of possible exchanges
/// </summary>
/// <param name="brokerageSymbol">The Zerodha symbol</param>
/// <returns>A default exchange value for the given ticker</returns>
private string GetZerodhaDefaultExchange(string brokerageSymbol)
{
if (string.IsNullOrWhiteSpace(brokerageSymbol))
{
throw new ArgumentException($"Invalid Zerodha symbol: {brokerageSymbol}");
}
var cleanSymbol = brokerageSymbol.Replace(" ", "").Trim();
List<SymbolData> tempSymbolDataList;
if (ZerodhaInstrumentsList.TryGetValue(cleanSymbol, out tempSymbolDataList))
{
return tempSymbolDataList[0].Exchange;
}
return string.Empty;
}
/// <summary>
/// Converts Lean symbol to a List of Zerodha Instrument Tokens available from various exchange
/// </summary>
/// <param name="brokerageSymbol">The Zerodha symbol</param>
/// <returns>A list of Zerodha Instrument Tokens</returns>
public List<uint> GetZerodhaInstrumentTokenList(string brokerageSymbol)
{
if (string.IsNullOrWhiteSpace(brokerageSymbol))
{
throw new ArgumentException($"Invalid Zerodha symbol: {brokerageSymbol}");
}
var cleanSymbol = brokerageSymbol.Replace(" ", "").Trim();
List<uint> tokenList = new List<uint>();
List<SymbolData> tempSymbolDataList;
if (ZerodhaInstrumentsList.TryGetValue(cleanSymbol, out tempSymbolDataList))
{
foreach (var sd in tempSymbolDataList)
{
tokenList.Add(sd.InstrumentToken);
}
}
return tokenList;
}
/// <summary>
/// Checks if the symbol is supported by Zerodha
/// </summary>
/// <param name="brokerageSymbol">The Zerodha symbol</param>
/// <returns>True if Zerodha supports the symbol</returns>
private bool IsKnownBrokerageSymbol(string brokerageSymbol)
{
if (string.IsNullOrWhiteSpace(brokerageSymbol))
{
return false;
}
return KnownSymbolsList.Where(x => x.Value.Contains(brokerageSymbol)).IsNullOrEmpty();
}
/// <summary>
/// Converts an Zerodha symbol to a Lean symbol string
/// </summary>
public Symbol ConvertZerodhaSymbolToLeanSymbol(uint ZerodhaSymbol)
{
var _symbol = string.Empty;
foreach (var item in ZerodhaInstrumentsList)
{
foreach( var sd in item.Value)
{
if (sd.InstrumentToken == ZerodhaSymbol)
{
_symbol = item.Key;
break;
}
}
}
// return as it is due to Zerodha has similar Symbol format
return KnownSymbolsList.Where(s => s.Value == _symbol).FirstOrDefault();
}
/// <summary>
/// Converts a Lean symbol string to an Zerodha symbol
/// </summary>
private static string ConvertLeanSymbolToZerodhaSymbol(string leanSymbol)
{
if (string.IsNullOrWhiteSpace(leanSymbol))
{
throw new ArgumentException($"Invalid Lean symbol: {leanSymbol}");
}
// return as it is due to Zerodha has similar Symbol format
return leanSymbol.ToUpperInvariant();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Baseline;
using Marten.Linq;
using Marten.Schema;
using Marten.Services;
using Marten.Services.Events;
namespace Marten.Events
{
public class EventStore : IEventStore
{
private readonly IDocumentSession _session;
private readonly IDocumentSchema _schema;
private readonly IManagedConnection _connection;
private readonly UnitOfWork _unitOfWork;
private readonly EventSelector _selector;
private readonly ISerializer _serializer;
public EventStore(IDocumentSession session, IDocumentSchema schema, ISerializer serializer, IManagedConnection connection, UnitOfWork unitOfWork)
{
_session = session;
_schema = schema;
_serializer = serializer;
_connection = connection;
_unitOfWork = unitOfWork;
_selector = new EventSelector(_schema.Events, serializer);
}
public void Append(Guid stream, params object[] events)
{
_schema.EnsureStorageExists(typeof(EventStream));
if (_unitOfWork.HasStream(stream))
{
_unitOfWork.StreamFor(stream).AddEvents(events.Select(EventStream.ToEvent));
}
else
{
var eventStream = new EventStream(stream, events.Select(EventStream.ToEvent).ToArray(), false);
_unitOfWork.StoreStream(eventStream);
}
}
public void Append(Guid stream, int expectedVersion, params object[] events)
{
Append(stream, events);
var assertion =
_unitOfWork.NonDocumentOperationsOf<AssertEventStreamMaxEventId>()
.FirstOrDefault(x => x.Stream == stream);
if (assertion == null)
{
_unitOfWork.Add(new AssertEventStreamMaxEventId(stream, expectedVersion, _schema.Events.Table.QualifiedName));
}
else
{
assertion.ExpectedVersion = expectedVersion;
}
}
public Guid StartStream<T>(Guid id, params object[] events) where T : class, new()
{
_schema.EnsureStorageExists(typeof(EventStream));
var stream = new EventStream(id, events.Select(EventStream.ToEvent).ToArray(), true)
{
AggregateType = typeof (T)
};
_unitOfWork.StoreStream(stream);
return id;
}
public Guid StartStream<TAggregate>(params object[] events) where TAggregate : class, new()
{
return StartStream<TAggregate>(Guid.NewGuid(), events);
}
public IList<IEvent> FetchStream(Guid streamId, int version = 0, DateTime? timestamp = null)
{
_schema.EnsureStorageExists(typeof(EventStream));
var handler = new EventQueryHandler(_selector, streamId, version, timestamp);
return _connection.Fetch(handler, null, null);
}
public Task<IList<IEvent>> FetchStreamAsync(Guid streamId, int version = 0, DateTime? timestamp = null,
CancellationToken token = new CancellationToken())
{
_schema.EnsureStorageExists(typeof(EventStream));
var handler = new EventQueryHandler(_selector, streamId, version, timestamp);
return _connection.FetchAsync(handler, null, null, token);
}
public T AggregateStream<T>(Guid streamId, int version = 0, DateTime? timestamp = null) where T : class, new()
{
_schema.EnsureStorageExists(typeof(EventStream));
var inner = new EventQueryHandler(_selector, streamId, version, timestamp);
var aggregator = _schema.Events.AggregateFor<T>();
var handler = new AggregationQueryHandler<T>(aggregator, inner, _session);
var aggregate = _connection.Fetch(handler, null, null);
var assignment = _schema.IdAssignmentFor<T>();
assignment.Assign(aggregate, streamId);
return aggregate;
}
public async Task<T> AggregateStreamAsync<T>(Guid streamId, int version = 0, DateTime? timestamp = null,
CancellationToken token = new CancellationToken()) where T : class, new()
{
_schema.EnsureStorageExists(typeof(EventStream));
var inner = new EventQueryHandler(_selector, streamId, version, timestamp);
var aggregator = _schema.Events.AggregateFor<T>();
var handler = new AggregationQueryHandler<T>(aggregator, inner, _session);
var aggregate = await _connection.FetchAsync(handler, null, null, token).ConfigureAwait(false);
var assignment = _schema.IdAssignmentFor<T>();
assignment.Assign(aggregate, streamId);
return aggregate;
}
public IMartenQueryable<T> QueryRawEventDataOnly<T>()
{
_schema.EnsureStorageExists(typeof(EventStream));
if (_schema.Events.AllAggregates().Any(x => x.AggregateType == typeof(T)))
{
return _session.Query<T>();
}
if (_schema.AllMappings.All(x => x.DocumentType != typeof(T)))
{
_schema.Events.AddEventType(typeof(T));
}
return _session.Query<T>();
}
public IMartenQueryable<IEvent> QueryAllRawEvents()
{
_schema.EnsureStorageExists(typeof(EventStream));
return _session.Query<IEvent>();
}
public Event<T> Load<T>(Guid id) where T : class
{
_schema.EnsureStorageExists(typeof(EventStream));
_schema.Events.AddEventType(typeof (T));
return Load(id).As<Event<T>>();
}
public async Task<Event<T>> LoadAsync<T>(Guid id, CancellationToken token = default(CancellationToken)) where T : class
{
_schema.EnsureStorageExists(typeof(EventStream));
_schema.Events.AddEventType(typeof (T));
return (await LoadAsync(id, token).ConfigureAwait(false)).As<Event<T>>();
}
public IEvent Load(Guid id)
{
_schema.EnsureStorageExists(typeof(EventStream));
var handler = new SingleEventQueryHandler(id, _schema.Events, _serializer);
return _connection.Fetch(handler, new NulloIdentityMap(_serializer), null);
}
public Task<IEvent> LoadAsync(Guid id, CancellationToken token = default(CancellationToken))
{
_schema.EnsureStorageExists(typeof(EventStream));
var handler = new SingleEventQueryHandler(id, _schema.Events, _serializer);
return _connection.FetchAsync(handler, new NulloIdentityMap(_serializer), null, token);
}
public StreamState FetchStreamState(Guid streamId)
{
_schema.EnsureStorageExists(typeof(EventStream));
var handler = new StreamStateHandler(_schema.Events, streamId);
return _connection.Fetch(handler, null, null);
}
public Task<StreamState> FetchStreamStateAsync(Guid streamId, CancellationToken token = new CancellationToken())
{
_schema.EnsureStorageExists(typeof(EventStream));
var handler = new StreamStateHandler(_schema.Events, streamId);
return _connection.FetchAsync(handler, null, null, token);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Mapsui.Fetcher;
namespace Mapsui.Layers
{
public class LayerCollection : IEnumerable<ILayer>
{
private ConcurrentQueue<ILayer> _layers = new();
public delegate void LayerRemovedEventHandler(ILayer layer);
public delegate void LayerAddedEventHandler(ILayer layer);
public delegate void LayerMovedEventHandler(ILayer layer);
public delegate void LayerCollectionChangedEventHandler(object sender, LayerCollectionChangedEventArgs args);
public event LayerRemovedEventHandler? LayerRemoved;
public event LayerAddedEventHandler? LayerAdded;
public event LayerMovedEventHandler? LayerMoved;
public event LayerCollectionChangedEventHandler? Changed;
public int Count => _layers.Count;
public bool IsReadOnly => false;
public IEnumerator<ILayer> GetEnumerator()
{
return _layers.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _layers.GetEnumerator();
}
public void Clear()
{
var copy = _layers.ToArray().ToList();
_layers = new ConcurrentQueue<ILayer>();
foreach (var layer in copy)
{
if (layer is IAsyncDataFetcher asyncLayer)
{
asyncLayer.AbortFetch();
asyncLayer.ClearCache();
}
OnLayerRemoved(layer);
}
}
public bool Contains(ILayer item)
{
return _layers.Contains(item);
}
public void CopyTo(ILayer[] array, int arrayIndex)
{
var copy = _layers.ToArray().ToList();
var maxCount = Math.Min(array.Length, copy.Count);
var count = maxCount - arrayIndex;
copy.CopyTo(0, array, arrayIndex, count);
_layers = new ConcurrentQueue<ILayer>(copy);
}
public ILayer this[int index] => _layers.ToArray()[index];
public void Add(params ILayer[] layers)
{
AddLayers(layers);
OnChanged(layers, null);
}
public void Move(int index, ILayer layer)
{
var copy = _layers.ToArray().ToList();
copy.Remove(layer);
if (copy.Count > index)
copy.Insert(index, layer);
else
copy.Add(layer);
_layers = new ConcurrentQueue<ILayer>(copy);
OnLayerMoved(layer);
OnChanged(null, null, new[] { layer });
}
public void Insert(int index, params ILayer[] layers)
{
if (layers == null || !layers.Any())
throw new ArgumentException("Layers cannot be null or empty");
var copy = _layers.ToArray().ToList();
if (copy.Count > index)
copy.InsertRange(index, layers);
else
copy.AddRange(layers);
_layers = new ConcurrentQueue<ILayer>(copy);
foreach (var layer in layers)
OnLayerAdded(layer);
OnChanged(layers, null);
}
public bool Remove(params ILayer[] layers)
{
var success = RemoveLayers(layers);
OnChanged(null, layers);
return success;
}
public bool Remove(Func<ILayer, bool> predicate)
{
var copyLayers = _layers.ToArray().Where(predicate).ToArray();
var success = RemoveLayers(copyLayers);
OnChanged(null, copyLayers);
return success;
}
public void Modify(IEnumerable<ILayer> layersToRemove, IEnumerable<ILayer> layersToAdd)
{
var copyLayersToRemove = layersToRemove.ToArray();
var copyLayersToAdd = layersToAdd.ToArray();
RemoveLayers(copyLayersToRemove);
AddLayers(copyLayersToAdd);
OnChanged(copyLayersToAdd, copyLayersToRemove);
}
public void Modify(Func<ILayer, bool> removePredicate, IEnumerable<ILayer> layersToAdd)
{
var copyLayersToRemove = _layers.ToArray().Where(removePredicate).ToArray();
var copyLayersToAdd = layersToAdd.ToArray();
RemoveLayers(copyLayersToRemove);
AddLayers(copyLayersToAdd);
OnChanged(copyLayersToAdd, copyLayersToRemove);
}
private void AddLayers(ILayer[] layers)
{
if (layers == null || !layers.Any())
throw new ArgumentException("Layers cannot be null or empty");
foreach (var layer in layers)
{
_layers.Enqueue(layer);
OnLayerAdded(layer);
}
}
private bool RemoveLayers(ILayer[] layers)
{
var copy = _layers.ToArray().ToList();
var success = true;
foreach (var layer in layers)
{
if (!copy.Remove(layer))
success = false;
if (layer is IAsyncDataFetcher asyncLayer)
{
asyncLayer.AbortFetch();
asyncLayer.ClearCache();
}
}
_layers = new ConcurrentQueue<ILayer>(copy);
foreach (var layer in layers)
OnLayerRemoved(layer);
return success;
}
private void OnLayerRemoved(ILayer layer)
{
LayerRemoved?.Invoke(layer);
}
private void OnLayerAdded(ILayer layer)
{
LayerAdded?.Invoke(layer);
}
private void OnLayerMoved(ILayer layer)
{
LayerMoved?.Invoke(layer);
}
private void OnChanged(IEnumerable<ILayer>? added, IEnumerable<ILayer>? removed, IEnumerable<ILayer>? moved = null)
{
Changed?.Invoke(this, new LayerCollectionChangedEventArgs(added, removed, moved));
}
public IEnumerable<ILayer> FindLayer(string layername)
{
return _layers.Where(layer => layer.Name.Contains(layername));
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* 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.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Represents a group of time zone period transitions.
/// </summary>
internal class TimeZoneTransitionGroup : ComplexProperty
{
private TimeZoneDefinition timeZoneDefinition;
private string id;
private List<TimeZoneTransition> transitions = new List<TimeZoneTransition>();
private TimeZoneTransition transitionToStandard;
private TimeZoneTransition transitionToDaylight;
/// <summary>
/// Loads from XML.
/// </summary>
/// <param name="reader">The reader.</param>
internal void LoadFromXml(EwsServiceXmlReader reader)
{
this.LoadFromXml(reader, XmlElementNames.TransitionsGroup);
}
/// <summary>
/// Writes to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal void WriteToXml(EwsServiceXmlWriter writer)
{
this.WriteToXml(writer, XmlElementNames.TransitionsGroup);
}
/// <summary>
/// Reads the attributes from XML.
/// </summary>
/// <param name="reader">The reader.</param>
internal override void ReadAttributesFromXml(EwsServiceXmlReader reader)
{
this.id = reader.ReadAttributeValue(XmlAttributeNames.Id);
}
/// <summary>
/// Writes the attributes to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteAttributesToXml(EwsServiceXmlWriter writer)
{
writer.WriteAttributeValue(XmlAttributeNames.Id, this.id);
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>True if element was read.</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
reader.EnsureCurrentNodeIsStartElement();
TimeZoneTransition transition = TimeZoneTransition.Create(this.timeZoneDefinition, reader.LocalName);
transition.LoadFromXml(reader);
EwsUtilities.Assert(
transition.TargetPeriod != null,
"TimeZoneTransitionGroup.TryReadElementFromXml",
"The transition's target period is null.");
this.transitions.Add(transition);
return true;
}
/// <summary>
/// Writes elements to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
foreach (TimeZoneTransition transition in this.transitions)
{
transition.WriteToXml(writer);
}
}
/// <summary>
/// Initializes this transition group based on the specified asjustment rule.
/// </summary>
/// <param name="adjustmentRule">The adjustment rule to initialize from.</param>
/// <param name="standardPeriod">A reference to the pre-created standard period.</param>
internal virtual void InitializeFromAdjustmentRule(TimeZoneInfo.AdjustmentRule adjustmentRule, TimeZonePeriod standardPeriod)
{
TimeZonePeriod daylightPeriod = new TimeZonePeriod();
// Generate an Id of the form "Daylight/2008"
daylightPeriod.Id = string.Format(
"{0}/{1}",
TimeZonePeriod.DaylightPeriodId,
adjustmentRule.DateStart.Year);
daylightPeriod.Name = TimeZonePeriod.DaylightPeriodName;
daylightPeriod.Bias = standardPeriod.Bias - adjustmentRule.DaylightDelta;
this.timeZoneDefinition.Periods.Add(daylightPeriod.Id, daylightPeriod);
this.transitionToDaylight = TimeZoneTransition.CreateTimeZoneTransition(
this.timeZoneDefinition,
daylightPeriod,
adjustmentRule.DaylightTransitionStart);
TimeZonePeriod standardPeriodToSet = new TimeZonePeriod();
standardPeriodToSet.Id = string.Format(
"{0}/{1}",
standardPeriod.Id,
adjustmentRule.DateStart.Year);
standardPeriodToSet.Name = standardPeriod.Name;
standardPeriodToSet.Bias = standardPeriod.Bias;
this.timeZoneDefinition.Periods.Add(standardPeriodToSet.Id, standardPeriodToSet);
this.transitionToStandard = TimeZoneTransition.CreateTimeZoneTransition(
this.timeZoneDefinition,
standardPeriodToSet,
adjustmentRule.DaylightTransitionEnd);
this.transitions.Add(this.transitionToDaylight);
this.transitions.Add(this.transitionToStandard);
}
/// <summary>
/// Validates this transition group.
/// </summary>
internal void Validate()
{
// There must be exactly one or two transitions in the group.
if (this.transitions.Count < 1 || this.transitions.Count > 2)
{
throw new ServiceLocalException(Strings.InvalidOrUnsupportedTimeZoneDefinition);
}
// If there is only one transition, it must be of type TimeZoneTransition
if (this.transitions.Count == 1 && !(this.transitions[0].GetType() == typeof(TimeZoneTransition)))
{
throw new ServiceLocalException(Strings.InvalidOrUnsupportedTimeZoneDefinition);
}
// If there are two transitions, none of them should be of type TimeZoneTransition
if (this.transitions.Count == 2)
{
foreach (TimeZoneTransition transition in this.transitions)
{
if (transition.GetType() == typeof(TimeZoneTransition))
{
throw new ServiceLocalException(Strings.InvalidOrUnsupportedTimeZoneDefinition);
}
}
}
// All the transitions in the group must be to a period.
foreach (TimeZoneTransition transition in this.transitions)
{
if (transition.TargetPeriod == null)
{
throw new ServiceLocalException(Strings.InvalidOrUnsupportedTimeZoneDefinition);
}
}
}
/// <summary>
/// Represents custom time zone creation parameters.
/// </summary>
internal class CustomTimeZoneCreateParams
{
private TimeSpan baseOffsetToUtc;
private string standardDisplayName;
private string daylightDisplayName;
/// <summary>
/// Initializes a new instance of the <see cref="CustomTimeZoneCreateParams"/> class.
/// </summary>
internal CustomTimeZoneCreateParams()
{
}
/// <summary>
/// Gets or sets the base offset to UTC.
/// </summary>
internal TimeSpan BaseOffsetToUtc
{
get { return this.baseOffsetToUtc; }
set { this.baseOffsetToUtc = value; }
}
/// <summary>
/// Gets or sets the display name of the standard period.
/// </summary>
internal string StandardDisplayName
{
get { return this.standardDisplayName; }
set { this.standardDisplayName = value; }
}
/// <summary>
/// Gets or sets the display name of the daylight period.
/// </summary>
internal string DaylightDisplayName
{
get { return this.daylightDisplayName; }
set { this.daylightDisplayName = value; }
}
/// <summary>
/// Gets a value indicating whether the custom time zone should have a daylight period.
/// </summary>
/// <value>
/// <c>true</c> if the custom time zone should have a daylight period; otherwise, <c>false</c>.
/// </value>
internal bool HasDaylightPeriod
{
get { return !string.IsNullOrEmpty(this.daylightDisplayName); }
}
}
/// <summary>
/// Gets a value indicating whether this group contains a transition to the Daylight period.
/// </summary>
/// <value><c>true</c> if this group contains a transition to daylight; otherwise, <c>false</c>.</value>
internal bool SupportsDaylight
{
get { return this.transitions.Count == 2; }
}
/// <summary>
/// Initializes the private members holding references to the transitions to the Daylight
/// and Standard periods.
/// </summary>
private void InitializeTransitions()
{
if (this.transitionToStandard == null)
{
foreach (TimeZoneTransition transition in this.transitions)
{
if (transition.TargetPeriod.IsStandardPeriod || (this.transitions.Count == 1))
{
this.transitionToStandard = transition;
}
else
{
this.transitionToDaylight = transition;
}
}
}
// If we didn't find a Standard period, this is an invalid time zone group.
if (this.transitionToStandard == null)
{
throw new ServiceLocalException(Strings.InvalidOrUnsupportedTimeZoneDefinition);
}
}
/// <summary>
/// Gets the transition to the Daylight period.
/// </summary>
private TimeZoneTransition TransitionToDaylight
{
get
{
this.InitializeTransitions();
return this.transitionToDaylight;
}
}
/// <summary>
/// Gets the transition to the Standard period.
/// </summary>
private TimeZoneTransition TransitionToStandard
{
get
{
this.InitializeTransitions();
return this.transitionToStandard;
}
}
/// <summary>
/// Gets the offset to UTC based on this group's transitions.
/// </summary>
internal CustomTimeZoneCreateParams GetCustomTimeZoneCreationParams()
{
CustomTimeZoneCreateParams result = new CustomTimeZoneCreateParams();
if (this.TransitionToDaylight != null)
{
result.DaylightDisplayName = this.TransitionToDaylight.TargetPeriod.Name;
}
result.StandardDisplayName = this.TransitionToStandard.TargetPeriod.Name;
// Assume that the standard period's offset is the base offset to UTC.
// EWS returns a positive offset for time zones that are behind UTC, and
// a negative one for time zones ahead of UTC. TimeZoneInfo does it the other
// way around.
result.BaseOffsetToUtc = -this.TransitionToStandard.TargetPeriod.Bias;
return result;
}
/// <summary>
/// Gets the delta offset for the daylight.
/// </summary>
/// <returns></returns>
internal TimeSpan GetDaylightDelta()
{
if (this.SupportsDaylight)
{
// EWS returns a positive offset for time zones that are behind UTC, and
// a negative one for time zones ahead of UTC. TimeZoneInfo does it the other
// way around.
return this.TransitionToStandard.TargetPeriod.Bias - this.TransitionToDaylight.TargetPeriod.Bias;
}
else
{
return TimeSpan.Zero;
}
}
/// <summary>
/// Creates a time zone adjustment rule.
/// </summary>
/// <param name="startDate">The start date of the adjustment rule.</param>
/// <param name="endDate">The end date of the adjustment rule.</param>
/// <returns>An TimeZoneInfo.AdjustmentRule.</returns>
internal TimeZoneInfo.AdjustmentRule CreateAdjustmentRule(DateTime startDate, DateTime endDate)
{
// If there is only one transition, we can't create an adjustment rule. We have to assume
// that the base offset to UTC is unchanged.
if (this.transitions.Count == 1)
{
return null;
}
return TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(
startDate.Date,
endDate.Date,
this.GetDaylightDelta(),
this.TransitionToDaylight.CreateTransitionTime(),
this.TransitionToStandard.CreateTransitionTime());
}
/// <summary>
/// Initializes a new instance of the <see cref="TimeZoneTransitionGroup"/> class.
/// </summary>
/// <param name="timeZoneDefinition">The time zone definition.</param>
internal TimeZoneTransitionGroup(TimeZoneDefinition timeZoneDefinition)
: base()
{
this.timeZoneDefinition = timeZoneDefinition;
}
/// <summary>
/// Initializes a new instance of the <see cref="TimeZoneTransitionGroup"/> class.
/// </summary>
/// <param name="timeZoneDefinition">The time zone definition.</param>
/// <param name="id">The Id of the new transition group.</param>
internal TimeZoneTransitionGroup(TimeZoneDefinition timeZoneDefinition, string id)
: this(timeZoneDefinition)
{
this.id = id;
}
/// <summary>
/// Gets or sets the id of this group.
/// </summary>
internal string Id
{
get { return this.id; }
set { this.id = value; }
}
/// <summary>
/// Gets the transitions in this group.
/// </summary>
internal List<TimeZoneTransition> Transitions
{
get { return this.transitions; }
}
}
}
| |
// ----------------------------------------------------------------------
//
// Microsoft Windows NT
// Copyright (C) Microsoft Corporation, 2007.
//
// Contents: Entry points for managed PowerShell plugin worker used to
// host powershell in a WSMan service.
// ----------------------------------------------------------------------
using System.Threading;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Collections.Generic;
using Microsoft.Win32.SafeHandles;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting.Client;
using System.Management.Automation.Remoting.Server;
using System.Management.Automation.Remoting.WSMan;
using System.Management.Automation.Tracing;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// Consolidation of constants for uniformity.
/// </summary>
internal static class WSManPluginConstants
{
internal const int ExitCodeSuccess = 0x00000000;
internal const int ExitCodeFailure = 0x00000001;
internal const string CtrlCSignal = "powershell/signal/crtl_c";
// The following are the only supported streams in PowerShell remoting.
// see WSManNativeApi.cs. These are duplicated here to save on
// Marshalling time.
internal const string SupportedInputStream = "stdin";
internal const string SupportedOutputStream = "stdout";
internal const string SupportedPromptResponseStream = "pr";
internal const string PowerShellStartupProtocolVersionName = "protocolversion";
internal const string PowerShellStartupProtocolVersionValue = "2.0";
internal const string PowerShellOptionPrefix = "PS_";
internal const int WSManPluginParamsGetRequestedLocale = 5;
internal const int WSManPluginParamsGetRequestedDataLocale = 6;
}
/// <summary>
/// Definitions of HRESULT error codes that are passed to the client.
/// 0x8054.... means that it is a PowerShell HRESULT. The PowerShell facility
/// is 84 (0x54).
/// </summary>
internal enum WSManPluginErrorCodes : int
{
NullPluginContext = -2141976624, // 0x805407D0
PluginContextNotFound = -2141976623, // 0x805407D1
NullInvalidInput = -2141975624, // 0x80540BB8
NullInvalidStreamSets = -2141975623, // 0x80540BB9
SessionCreationFailed = -2141975622, // 0x80540BBA
NullShellContext = -2141975621, // 0x80540BBB
InvalidShellContext = -2141975620, // 0x80540BBC
InvalidCommandContext = -2141975619, // 0x80540BBD
InvalidInputStream = -2141975618, // 0x80540BBE
InvalidInputDatatype = -2141975617, // 0x80540BBF
InvalidOutputStream = -2141975616, // 0x80540BC0
InvalidSenderDetails = -2141975615, // 0x80540BC1
ShutdownRegistrationFailed = -2141975614, // 0x80540BC2
ReportContextFailed = -2141975613, // 0x80540BC3
InvalidArgSet = -2141975612, // 0x80540BC4
ProtocolVersionNotMatch = -2141975611, // 0x80540BC5
OptionNotUnderstood = -2141975610, // 0x80540BC6
ProtocolVersionNotFound = -2141975609, // 0x80540BC7
ManagedException = -2141974624, // 0x80540FA0
PluginOperationClose = -2141974623, // 0x80540FA1
PluginConnectNoNegotiationData = -2141974622, // 0x80540FA2
PluginConnectOperationFailed = -2141974621, // 0x80540FA3
NoError = 0,
OutOfMemory = -2147024882 // 0x8007000E
}
/// <summary>
/// class that holds plugin + shell context information used to handle
/// shutdown notifications.
///
/// Explicit destruction and release of the IntPtrs is not required because
/// their lifetime is managed by WinRM.
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal class WSManPluginOperationShutdownContext // TODO: Rename to OperationShutdownContext when removing the MC++ module.
{
#region Internal Members
internal IntPtr pluginContext;
internal IntPtr shellContext;
internal IntPtr commandContext;
internal bool isReceiveOperation;
internal bool isShuttingDown;
#endregion
#region Constructors
internal WSManPluginOperationShutdownContext(
IntPtr plgContext,
IntPtr shContext,
IntPtr cmdContext,
bool isRcvOp)
{
pluginContext = plgContext;
shellContext = shContext;
commandContext = cmdContext;
isReceiveOperation = isRcvOp;
isShuttingDown = false;
}
#endregion
}
/// <summary>
/// Represents the logical grouping of all actions required to handle the
/// lifecycle of shell sessions through the WinRM plugin.
/// </summary>
internal class WSManPluginInstance
{
#region Private Members
private Dictionary<IntPtr, WSManPluginShellSession> _activeShellSessions;
private object _syncObject;
private static Dictionary<IntPtr, WSManPluginInstance> s_activePlugins = new Dictionary<IntPtr, WSManPluginInstance>();
/// <summary>
/// Enables dependency injection after the static constructor is called.
/// This may be overridden in unit tests to enable different behavoir.
/// It is static because static instances of this class use the facade. Otherwise,
/// it would be passed in via a parameterized constructor.
/// </summary>
internal static IWSManNativeApiFacade wsmanPinvokeStatic = new WSManNativeApiFacade();
#endregion
#region Constructor and Destructor
internal WSManPluginInstance()
{
_activeShellSessions = new Dictionary<IntPtr, WSManPluginShellSession>();
_syncObject = new System.Object();
}
/// <summary>
/// static constructor to listen to unhandled exceptions
/// from the AppDomain and log the errors
/// Note: It is not necessary to instantiate IWSManNativeApi here because it is not used.
/// </summary>
static WSManPluginInstance()
{
// NOTE - the order is important here:
// because handler from WindowsErrorReporting is going to terminate the proces
// we want it to fire last
#if !CORECLR
// Register our remoting handler for crashes
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(WSManPluginInstance.UnhandledExceptionHandler);
// Register our Watson handler for crash reports in server mode
System.Management.Automation.WindowsErrorReporting.RegisterWindowsErrorReporting(true);
#endif
}
#endregion
/// <summary>
/// Create a new shell in the plugin context.
/// </summary>
/// <param name="pluginContext"></param>
/// <param name="requestDetails"></param>
/// <param name="flags"></param>
/// <param name="extraInfo"></param>
/// <param name="startupInfo"></param>
/// <param name="inboundShellInformation"></param>
internal void CreateShell(
IntPtr pluginContext,
WSManNativeApi.WSManPluginRequest requestDetails,
int flags,
string extraInfo,
WSManNativeApi.WSManShellStartupInfo_UnToMan startupInfo,
WSManNativeApi.WSManData_UnToMan inboundShellInformation)
{
if (null == requestDetails)
{
// Nothing can be done because requestDetails are required to report operation complete
PSEtwLog.LogAnalyticInformational(PSEventId.ReportOperationComplete,
PSOpcode.Close, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
"null",
Convert.ToString(WSManPluginErrorCodes.NullInvalidInput, CultureInfo.InvariantCulture),
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullInvalidInput,
"requestDetails",
"WSManPluginShell"),
String.Empty);
return;
}
if ((null == requestDetails.senderDetails) ||
(null == requestDetails.operationInfo))
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullInvalidInput,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullInvalidInput,
"requestDetails",
"WSManPluginShell"));
return;
}
if (null == startupInfo)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullInvalidInput,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullInvalidInput,
"startupInfo",
"WSManPluginShell"));
return;
}
if ((0 == startupInfo.inputStreamSet.streamIDsCount) || (0 == startupInfo.outputStreamSet.streamIDsCount))
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullInvalidStreamSets,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullInvalidStreamSet,
WSManPluginConstants.SupportedInputStream,
WSManPluginConstants.SupportedOutputStream));
return;
}
if (String.IsNullOrEmpty(extraInfo))
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullInvalidInput,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullInvalidInput,
"extraInfo",
"WSManPluginShell"));
return;
}
WSManPluginInstance.SetThreadProperties(requestDetails);
// check if protocolversion option is honored
if (!EnsureOptionsComply(requestDetails))
{
return;
}
int result = WSManPluginConstants.ExitCodeSuccess;
WSManPluginShellSession mgdShellSession;
WSManPluginOperationShutdownContext context;
System.Byte[] convertedBase64 = null;
try
{
PSSenderInfo senderInfo = GetPSSenderInfo(requestDetails.senderDetails);
// inbound shell information is already verified by pwrshplugin.dll.. so no need
// to verify here.
WSManPluginServerTransportManager serverTransportMgr;
if (Platform.IsWindows)
{
serverTransportMgr = new WSManPluginServerTransportManager(BaseTransportManager.DefaultFragmentSize, new PSRemotingCryptoHelperServer());
}
else
{
serverTransportMgr = new WSManPluginServerTransportManager(BaseTransportManager.DefaultFragmentSize, null);
}
PSEtwLog.LogAnalyticInformational(PSEventId.ServerCreateRemoteSession,
PSOpcode.Connect, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
requestDetails.ToString(), senderInfo.UserInfo.Identity.Name, requestDetails.resourceUri);
ServerRemoteSession remoteShellSession = ServerRemoteSession.CreateServerRemoteSession(senderInfo,
requestDetails.resourceUri,
extraInfo,
serverTransportMgr);
if (null == remoteShellSession)
{
WSManPluginInstance.ReportWSManOperationComplete(
requestDetails,
WSManPluginErrorCodes.SessionCreationFailed);
return;
}
context = new WSManPluginOperationShutdownContext(pluginContext, requestDetails.unmanagedHandle, IntPtr.Zero, false);
if (null == context)
{
ReportOperationComplete(requestDetails, WSManPluginErrorCodes.OutOfMemory);
return;
}
// Create a shell session wrapper to track and service future interacations.
mgdShellSession = new WSManPluginShellSession(requestDetails, serverTransportMgr, remoteShellSession, context);
AddToActiveShellSessions(mgdShellSession);
mgdShellSession.SessionClosed += new EventHandler<EventArgs>(HandleShellSessionClosed);
if (null != inboundShellInformation)
{
if ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT != inboundShellInformation.Type)
{
// only text data is supported
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidInputDatatype,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidInputDataType,
"WSMAN_DATA_TYPE_TEXT"));
DeleteFromActiveShellSessions(requestDetails.unmanagedHandle);
return;
}
else
{
convertedBase64 = ServerOperationHelpers.ExtractEncodedXmlElement(
inboundShellInformation.Text,
WSManNativeApi.PS_CREATION_XML_TAG);
}
}
// now report the shell context to WSMan.
PSEtwLog.LogAnalyticInformational(PSEventId.ReportContext,
PSOpcode.Connect, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
requestDetails.ToString(), requestDetails.ToString());
result = wsmanPinvokeStatic.WSManPluginReportContext(requestDetails.unmanagedHandle, 0, requestDetails.unmanagedHandle);
if (WSManPluginConstants.ExitCodeSuccess != result)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.ReportContextFailed,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginReportContextFailed));
DeleteFromActiveShellSessions(requestDetails.unmanagedHandle);
return;
}
}
catch (System.Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
PSEtwLog.LogOperationalError(PSEventId.TransportError,
PSOpcode.Connect, PSTask.None, PSKeyword.UseAlwaysOperational, "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000",
Convert.ToString(WSManPluginErrorCodes.ManagedException, CultureInfo.InvariantCulture), e.Message, e.StackTrace);
DeleteFromActiveShellSessions(requestDetails.unmanagedHandle);
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.ManagedException,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginManagedException,
e.Message));
return;
}
bool isRegisterWaitForSingleObjectSucceeded = true;
//always synchronize calls to OperationComplete once notification handle is registered.. else duplicate OperationComplete calls are bound to happen
lock (mgdShellSession.shellSyncObject)
{
mgdShellSession.registeredShutdownNotification = 1;
// Wrap the provided handle so it can be passed to the registration function
EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
if (Platform.IsWindows)
{
SafeWaitHandle safeWaitHandle = new SafeWaitHandle(requestDetails.shutdownNotificationHandle, false); // Owned by WinRM
ClrFacade.SetSafeWaitHandle(eventWaitHandle, safeWaitHandle);
}
else
{
//On non-windows platforms the shutdown notification is done through a callback instead of a windows event handle.
//Register the callback and this will then signal the event. Note, the gch object is deleted in the shell shutdown
//notification that will always come in to shut down the operation.
GCHandle gch = GCHandle.Alloc(eventWaitHandle);
IntPtr p = GCHandle.ToIntPtr(gch);
wsmanPinvokeStatic.WSManPluginRegisterShutdownCallback(
requestDetails.unmanagedHandle,
WSManPluginManagedEntryWrapper.workerPtrs.UnmanagedStruct.wsManPluginShutdownCallbackNative,
p);
}
mgdShellSession.registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject(
eventWaitHandle,
new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback),
context,
-1, // INFINITE
true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION?
if (null == mgdShellSession.registeredShutDownWaitHandle)
{
isRegisterWaitForSingleObjectSucceeded = false;
}
}
if (!isRegisterWaitForSingleObjectSucceeded)
{
mgdShellSession.registeredShutdownNotification = 0;
WSManPluginInstance.ReportWSManOperationComplete(
requestDetails,
WSManPluginErrorCodes.ShutdownRegistrationFailed);
DeleteFromActiveShellSessions(requestDetails.unmanagedHandle);
return;
}
try
{
if (convertedBase64 != null)
{
mgdShellSession.SendOneItemToSessionHelper(convertedBase64, WSManPluginConstants.SupportedInputStream);
}
}
catch (System.Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
PSEtwLog.LogOperationalError(PSEventId.TransportError,
PSOpcode.Connect, PSTask.None, PSKeyword.UseAlwaysOperational, "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000",
Convert.ToString(WSManPluginErrorCodes.ManagedException, CultureInfo.InvariantCulture), e.Message, e.StackTrace);
if (Interlocked.Exchange(ref mgdShellSession.registeredShutdownNotification, 0) == 1)
{
// unregister callback.. wait for any ongoing callbacks to complete.. nothing much we could do if this fails
bool ignore = mgdShellSession.registeredShutDownWaitHandle.Unregister(null);
mgdShellSession.registeredShutDownWaitHandle = null;
//this will called OperationComplete
PerformCloseOperation(context);
}
return;
}
return;
}
/// <summary>
/// This gets called on a thread pool thread once Shutdown wait handle is notified.
/// </summary>
/// <param name="context"></param>
internal void CloseShellOperation(
WSManPluginOperationShutdownContext context)
{
PSEtwLog.LogAnalyticInformational(PSEventId.ServerCloseOperation,
PSOpcode.Disconnect, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
((IntPtr)context.shellContext).ToString(),
((IntPtr)context.commandContext).ToString(),
context.isReceiveOperation.ToString());
WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(context.shellContext);
if (null == mgdShellSession)
{
// this should never be the case. this will protect the service.
//Dbg.Assert(false, "context.shellContext not matched");
return;
}
SetThreadProperties(mgdShellSession.creationRequestDetails);
// update the internal data store only if this is not receive operation.
if (!context.isReceiveOperation)
{
DeleteFromActiveShellSessions(context.shellContext);
}
string errorMsg = StringUtil.Format(RemotingErrorIdStrings.WSManPluginOperationClose);
System.Exception reasonForClose = new System.Exception(errorMsg);
mgdShellSession.CloseOperation(context, reasonForClose);
}
internal void CloseCommandOperation(
WSManPluginOperationShutdownContext context)
{
PSEtwLog.LogAnalyticInformational(PSEventId.ServerCloseOperation,
PSOpcode.Disconnect, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
context.shellContext.ToString(),
context.commandContext.ToString(),
context.isReceiveOperation.ToString());
WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(context.shellContext);
if (null == mgdShellSession)
{
// this should never be the case. this will protect the service.
//Dbg.Assert(false, "context.shellContext not matched");
return;
}
SetThreadProperties(mgdShellSession.creationRequestDetails);
mgdShellSession.CloseCommandOperation(context);
}
/// <summary>
/// adds shell session to activeShellSessions store and returns the id
/// at which the session is added.
/// </summary>
/// <param name="newShellSession"></param>
private void AddToActiveShellSessions(
WSManPluginShellSession newShellSession)
{
int count = -1;
lock (_syncObject)
{
IntPtr key = newShellSession.creationRequestDetails.unmanagedHandle;
Dbg.Assert(IntPtr.Zero != key, "NULL handles should not be provided");
if (!_activeShellSessions.ContainsKey(key))
{
_activeShellSessions.Add(key, newShellSession);
// trigger an event outside the lock
count = _activeShellSessions.Count;
}
}
if (-1 != count)
{
// Raise session count changed event
WSManServerChannelEvents.RaiseActiveSessionsChangedEvent(new ActiveSessionsChangedEventArgs(count));
}
}
/// <summary>
/// Retrieves a WSManPluginShellSession if matched.
/// </summary>
/// <param name="key">Shell context (WSManPluginRequest.unmanagedHandle)</param>
/// <returns>null WSManPluginShellSession if not matched. The object if matched.</returns>
private WSManPluginShellSession GetFromActiveShellSessions(
IntPtr key)
{
lock (_syncObject)
{
WSManPluginShellSession result;
_activeShellSessions.TryGetValue(key, out result);
return result;
}
}
/// <summary>
/// Removes a WSManPluginShellSession from tracking.
/// </summary>
/// <param name="keyToDelete">IntPtr of a WSManPluginRequest structure.</param>
private void DeleteFromActiveShellSessions(
IntPtr keyToDelete)
{
int count = -1;
lock (_syncObject)
{
if (_activeShellSessions.Remove(keyToDelete))
{
// trigger an event outside the lock
count = _activeShellSessions.Count;
}
}
if (-1 != count)
{
// Raise session count changed event
WSManServerChannelEvents.RaiseActiveSessionsChangedEvent(new ActiveSessionsChangedEventArgs(count));
}
}
/// <summary>
/// Triggers a shell close from an event handler.
/// </summary>
/// <param name="source">Shell context</param>
/// <param name="e"></param>
private void HandleShellSessionClosed(
Object source,
EventArgs e)
{
DeleteFromActiveShellSessions((IntPtr)source);
}
/// <summary>
/// Helper function to validate incoming values
/// </summary>
/// <param name="requestDetails"></param>
/// <param name="shellContext"></param>
/// <param name="inputFunctionName"></param>
/// <returns></returns>
private bool validateIncomingContexts(
WSManNativeApi.WSManPluginRequest requestDetails,
IntPtr shellContext,
string inputFunctionName)
{
if (null == requestDetails)
{
// Nothing can be done because requestDetails are required to report operation complete
PSEtwLog.LogAnalyticInformational(PSEventId.ReportOperationComplete,
PSOpcode.Close, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
"null",
Convert.ToString(WSManPluginErrorCodes.NullInvalidInput, CultureInfo.InvariantCulture),
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullInvalidInput,
"requestDetails",
inputFunctionName),
String.Empty);
return false;
}
if (IntPtr.Zero == shellContext)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullShellContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullShellContext,
"ShellContext",
inputFunctionName));
return false;
}
return true;
}
/// <summary>
/// Create a new command in the shell context.
/// </summary>
/// <param name="pluginContext"></param>
/// <param name="requestDetails"></param>
/// <param name="flags"></param>
/// <param name="shellContext"></param>
/// <param name="commandLine"></param>
/// <param name="arguments"></param>
internal void CreateCommand(
IntPtr pluginContext,
WSManNativeApi.WSManPluginRequest requestDetails,
int flags,
IntPtr shellContext,
string commandLine,
WSManNativeApi.WSManCommandArgSet arguments)
{
if (!validateIncomingContexts(requestDetails, shellContext, "WSManRunShellCommandEx"))
{
return;
}
SetThreadProperties(requestDetails);
PSEtwLog.LogAnalyticInformational(PSEventId.ServerCreateCommandSession,
PSOpcode.Connect, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
((IntPtr)shellContext).ToString(), requestDetails.ToString());
WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext);
if (null == mgdShellSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidShellContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidShellContext));
return;
}
mgdShellSession.CreateCommand(pluginContext, requestDetails, flags, commandLine, arguments);
}
internal void StopCommand(
WSManNativeApi.WSManPluginRequest requestDetails,
IntPtr shellContext,
IntPtr commandContext)
{
if (null == requestDetails)
{
// Nothing can be done because requestDetails are required to report operation complete
PSEtwLog.LogAnalyticInformational(PSEventId.ReportOperationComplete,
PSOpcode.Close, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
"null",
Convert.ToString(WSManPluginErrorCodes.NullInvalidInput, CultureInfo.InvariantCulture),
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullInvalidInput,
"requestDetails",
"StopCommand"),
String.Empty);
return;
}
SetThreadProperties(requestDetails);
PSEtwLog.LogAnalyticInformational(PSEventId.ServerStopCommand,
PSOpcode.Disconnect, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
((IntPtr)shellContext).ToString(),
((IntPtr)commandContext).ToString(),
requestDetails.ToString());
WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext);
if (null == mgdShellSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidShellContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidShellContext));
return;
}
WSManPluginCommandSession mgdCommandSession = mgdShellSession.GetCommandSession(commandContext);
if (null == mgdCommandSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidCommandContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidCommandContext));
return;
}
mgdCommandSession.Stop(requestDetails);
}
internal void Shutdown()
{
PSEtwLog.LogAnalyticInformational(PSEventId.WSManPluginShutdown,
PSOpcode.ShuttingDown, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic);
// all active shells should be closed at this point
Dbg.Assert(_activeShellSessions.Count == 0, "All active shells should be closed");
// raise shutting down notification
WSManServerChannelEvents.RaiseShuttingDownEvent();
}
/// <summary>
/// Connect
/// </summary>
/// <param name="requestDetails"></param>
/// <param name="flags"></param>
/// <param name="shellContext"></param>
/// <param name="commandContext"></param>
/// <param name="inboundConnectInformation"></param>
internal void ConnectShellOrCommand(
WSManNativeApi.WSManPluginRequest requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
WSManNativeApi.WSManData_UnToMan inboundConnectInformation)
{
if (!validateIncomingContexts(requestDetails, shellContext, "ConnectShellOrCommand"))
{
return;
}
//TODO... What does this mean from a new client that has specified diff locale from original client?
SetThreadProperties(requestDetails);
//TODO.. Add new ETW events and log
/*etwTracer.AnalyticChannel.WriteInformation(PSEventId.ServerReceivedData,
PSOpcode.Open, PSTask.None,
((IntPtr)shellContext).ToString(), ((IntPtr)commandContext).ToString(), ((IntPtr)requestDetails).ToString());*/
WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext);
if (null == mgdShellSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidShellContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidShellContext));
return;
}
if (IntPtr.Zero == commandContext)
{
mgdShellSession.ExecuteConnect(requestDetails, flags, inboundConnectInformation);
return;
}
// this connect is on a commad
WSManPluginCommandSession mgdCmdSession = mgdShellSession.GetCommandSession(commandContext);
if (null == mgdCmdSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidCommandContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidCommandContext));
return;
}
mgdCmdSession.ExecuteConnect(requestDetails, flags, inboundConnectInformation);
}
/// <summary>
/// Send data to the shell / command specified.
/// </summary>
/// <param name="requestDetails"></param>
/// <param name="flags"></param>
/// <param name="shellContext"></param>
/// <param name="commandContext"></param>
/// <param name="stream"></param>
/// <param name="inboundData"></param>
internal void SendOneItemToShellOrCommand(
WSManNativeApi.WSManPluginRequest requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
string stream,
WSManNativeApi.WSManData_UnToMan inboundData)
{
if (!validateIncomingContexts(requestDetails, shellContext, "SendOneItemToShellOrCommand"))
{
return;
}
SetThreadProperties(requestDetails);
PSEtwLog.LogAnalyticInformational(PSEventId.ServerReceivedData,
PSOpcode.Open, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
((IntPtr)shellContext).ToString(), ((IntPtr)commandContext).ToString(), requestDetails.ToString());
WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext);
if (null == mgdShellSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidShellContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidShellContext)
);
return;
}
if (IntPtr.Zero == commandContext)
{
// the data is destined for shell (runspace) session. so let shell handle it
mgdShellSession.SendOneItemToSession(requestDetails, flags, stream, inboundData);
return;
}
// the data is destined for command.
WSManPluginCommandSession mgdCmdSession = mgdShellSession.GetCommandSession(commandContext);
if (null == mgdCmdSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidCommandContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidCommandContext));
return;
}
mgdCmdSession.SendOneItemToSession(requestDetails, flags, stream, inboundData);
}
/// <summary>
/// unlock the shell / command specified so that the shell / command
/// starts sending data to the client.
/// </summary>
/// <param name="pluginContext"></param>
/// <param name="requestDetails"></param>
/// <param name="flags"></param>
/// <param name="shellContext"></param>
/// <param name="commandContext"></param>
/// <param name="streamSet"></param>
internal void EnableShellOrCommandToSendDataToClient(
IntPtr pluginContext,
WSManNativeApi.WSManPluginRequest requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
WSManNativeApi.WSManStreamIDSet_UnToMan streamSet)
{
if (!validateIncomingContexts(requestDetails, shellContext, "EnableShellOrCommandToSendDataToClient"))
{
return;
}
SetThreadProperties(requestDetails);
PSEtwLog.LogAnalyticInformational(PSEventId.ServerClientReceiveRequest,
PSOpcode.Open, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
((IntPtr)shellContext).ToString(),
((IntPtr)commandContext).ToString(),
requestDetails.ToString());
WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext);
if (null == mgdShellSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidShellContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidShellContext)
);
return;
}
WSManPluginOperationShutdownContext ctxtToReport = new WSManPluginOperationShutdownContext(pluginContext, shellContext, IntPtr.Zero, true);
if (null == ctxtToReport)
{
ReportOperationComplete(requestDetails, WSManPluginErrorCodes.OutOfMemory);
return;
}
if (IntPtr.Zero == commandContext)
{
// the instruction is destined for shell (runspace) session. so let shell handle it
if (mgdShellSession.EnableSessionToSendDataToClient(requestDetails, flags, streamSet, ctxtToReport))
{
return;
}
}
else
{
// the instruction is destined for command
ctxtToReport.commandContext = commandContext;
WSManPluginCommandSession mgdCmdSession = mgdShellSession.GetCommandSession(commandContext);
if (null == mgdCmdSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidCommandContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidCommandContext));
return;
}
if (mgdCmdSession.EnableSessionToSendDataToClient(requestDetails, flags, streamSet, ctxtToReport))
{
return;
}
}
}
/// <summary>
/// used to create PSPrincipal object from senderDetails struct.
/// </summary>
/// <param name="senderDetails"></param>
/// <returns></returns>
private PSSenderInfo GetPSSenderInfo(
WSManNativeApi.WSManSenderDetails senderDetails)
{
// senderDetails will not be null.
Dbg.Assert(null != senderDetails, "senderDetails cannot be null");
// Construct PSIdentity
PSCertificateDetails psCertDetails = null;
// Construct Certificate Details
if (null != senderDetails.certificateDetails)
{
psCertDetails = new PSCertificateDetails(
senderDetails.certificateDetails.subject,
senderDetails.certificateDetails.issuerName,
senderDetails.certificateDetails.issuerThumbprint);
}
// Construct PSPrincipal
PSIdentity psIdentity = new PSIdentity(senderDetails.authenticationMechanism, true, senderDetails.senderName, psCertDetails);
// For Virtual and RunAs accounts WSMan specifies the client token via an environment variable and
// senderDetails.clientToken should not be used.
IntPtr clientToken = GetRunAsClientToken();
clientToken = (clientToken != IntPtr.Zero) ? clientToken : senderDetails.clientToken;
WindowsIdentity windowsIdentity = null;
if (clientToken != IntPtr.Zero)
{
try
{
windowsIdentity = new WindowsIdentity(clientToken, senderDetails.authenticationMechanism);
}
// Suppress exceptions..So windowsIdentity = null in these cases
catch (ArgumentException)
{
// userToken is 0.
// -or-
// userToken is duplicated and invalid for impersonation.
}
catch (System.Security.SecurityException)
{
// The caller does not have the correct permissions.
// -or-
// A Win32 error occurred.
}
}
PSPrincipal userPrincipal = new PSPrincipal(psIdentity, windowsIdentity);
PSSenderInfo result = new PSSenderInfo(userPrincipal, senderDetails.httpUrl);
return result;
}
private const string WSManRunAsClientTokenName = "__WINRM_RUNAS_CLIENT_TOKEN__";
/// <summary>
/// Helper method to retrieve the WSMan client token from the __WINRM_RUNAS_CLIENT_TOKEN__
/// environment variable, which is set in the WSMan layer for Virtual or RunAs accounts.
/// </summary>
/// <returns>ClientToken IntPtr</returns>
private IntPtr GetRunAsClientToken()
{
string clientTokenStr = System.Environment.GetEnvironmentVariable(WSManRunAsClientTokenName);
if (clientTokenStr != null)
{
// Remove the token value from the environment variable
System.Environment.SetEnvironmentVariable(WSManRunAsClientTokenName, null);
int clientTokenInt;
if (int.TryParse(clientTokenStr, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out clientTokenInt))
{
return new IntPtr(clientTokenInt);
}
}
return IntPtr.Zero;
}
/// <summary>
/// Was private. Made protected internal for easier testing
/// </summary>
/// <param name="requestDetails"></param>
/// <returns></returns>
protected internal bool EnsureOptionsComply(
WSManNativeApi.WSManPluginRequest requestDetails)
{
WSManNativeApi.WSManOption[] options = requestDetails.operationInfo.optionSet.options;
bool isProtocolVersionDeclared = false;
for (int i = 0; i < options.Length; i++) // What about requestDetails.operationInfo.optionSet.optionsCount? It is a hold over from the C++ API. Safer is Length.
{
WSManNativeApi.WSManOption option = options[i];
if (String.Equals(option.name, WSManPluginConstants.PowerShellStartupProtocolVersionName, StringComparison.Ordinal))
{
if (!EnsureProtocolVersionComplies(requestDetails, option.value))
{
return false;
}
isProtocolVersionDeclared = true;
}
if (0 == String.Compare(option.name, 0, WSManPluginConstants.PowerShellOptionPrefix, 0, WSManPluginConstants.PowerShellOptionPrefix.Length, StringComparison.Ordinal))
{
if (option.mustComply)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.OptionNotUnderstood,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginOptionNotUnderstood,
option.name,
System.Management.Automation.PSVersionInfo.BuildVersion,
WSManPluginConstants.PowerShellStartupProtocolVersionValue));
return false;
}
}
}
if (!isProtocolVersionDeclared)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.ProtocolVersionNotFound,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginProtocolVersionNotFound,
WSManPluginConstants.PowerShellStartupProtocolVersionName,
System.Management.Automation.PSVersionInfo.BuildVersion,
WSManPluginConstants.PowerShellStartupProtocolVersionValue));
return false;
}
return true;
}
/// <summary>
/// Verifies that the protocol version is in the correct syntax and supported.
/// </summary>
/// <param name="requestDetails"></param>
/// <param name="clientVersionString"></param>
/// <returns></returns>
protected internal bool EnsureProtocolVersionComplies(
WSManNativeApi.WSManPluginRequest requestDetails,
string clientVersionString)
{
if (String.Equals(clientVersionString, WSManPluginConstants.PowerShellStartupProtocolVersionValue, StringComparison.Ordinal))
{
return true;
}
// Check if major versions are equal and server's minor version is smaller..
// if so client's version is supported by the server. The understanding is
// that minor version changes do not break the protocol.
System.Version clientVersion = Utils.StringToVersion(clientVersionString);
System.Version serverVersion = Utils.StringToVersion(WSManPluginConstants.PowerShellStartupProtocolVersionValue);
if ((null != clientVersion) && (null != serverVersion) &&
(clientVersion.Major == serverVersion.Major) &&
(clientVersion.Minor >= serverVersion.Minor))
{
return true;
}
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.ProtocolVersionNotMatch,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginProtocolVersionNotMatch,
WSManPluginConstants.PowerShellStartupProtocolVersionValue,
System.Management.Automation.PSVersionInfo.BuildVersion,
clientVersionString));
return false;
}
/// <summary>
/// static func to take care of unmanaged to managed transitions.
/// </summary>
/// <param name="pluginContext"></param>
/// <param name="requestDetails"></param>
/// <param name="flags"></param>
/// <param name="extraInfo"></param>
/// <param name="startupInfo"></param>
/// <param name="inboundShellInformation"></param>
internal static void PerformWSManPluginShell(
IntPtr pluginContext, // PVOID
IntPtr requestDetails, // WSMAN_PLUGIN_REQUEST*
int flags,
string extraInfo,
IntPtr startupInfo, // WSMAN_SHELL_STARTUP_INFO*
IntPtr inboundShellInformation) // WSMAN_DATA*
{
WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext);
if (null == pluginToUse)
{
lock (s_activePlugins)
{
pluginToUse = GetFromActivePlugins(pluginContext);
if (null == pluginToUse)
{
// create a new plugin
WSManPluginInstance mgdPlugin = new WSManPluginInstance();
AddToActivePlugins(pluginContext, mgdPlugin);
pluginToUse = mgdPlugin;
}
}
}
// Marshal the incoming pointers into managed types prior to the call
WSManNativeApi.WSManPluginRequest requestDetailsInstance = WSManNativeApi.WSManPluginRequest.UnMarshal(requestDetails);
WSManNativeApi.WSManShellStartupInfo_UnToMan startupInfoInstance = WSManNativeApi.WSManShellStartupInfo_UnToMan.UnMarshal(startupInfo);
WSManNativeApi.WSManData_UnToMan inboundShellInfo = WSManNativeApi.WSManData_UnToMan.UnMarshal(inboundShellInformation);
pluginToUse.CreateShell(pluginContext, requestDetailsInstance, flags, extraInfo, startupInfoInstance, inboundShellInfo);
}
internal static void PerformWSManPluginCommand(
IntPtr pluginContext,
IntPtr requestDetails, // WSMAN_PLUGIN_REQUEST*
int flags,
IntPtr shellContext, // PVOID
[MarshalAs(UnmanagedType.LPWStr)] string commandLine,
IntPtr arguments) // WSMAN_COMMAND_ARG_SET*
{
WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext);
if (null == pluginToUse)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.PluginContextNotFound,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginContextNotFound));
return;
}
// Marshal the incoming pointers into managed types prior to the call
WSManNativeApi.WSManPluginRequest request = WSManNativeApi.WSManPluginRequest.UnMarshal(requestDetails);
WSManNativeApi.WSManCommandArgSet argSet = WSManNativeApi.WSManCommandArgSet.UnMarshal(arguments);
pluginToUse.CreateCommand(pluginContext, request, flags, shellContext, commandLine, argSet);
}
internal static void PerformWSManPluginConnect(
IntPtr pluginContext,
IntPtr requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
IntPtr inboundConnectInformation)
{
WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext);
if (null == pluginToUse)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.PluginContextNotFound,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginContextNotFound));
return;
}
// Marshal the incoming pointers into managed types prior to the call
WSManNativeApi.WSManPluginRequest request = WSManNativeApi.WSManPluginRequest.UnMarshal(requestDetails);
WSManNativeApi.WSManData_UnToMan connectInformation = WSManNativeApi.WSManData_UnToMan.UnMarshal(inboundConnectInformation);
pluginToUse.ConnectShellOrCommand(request, flags, shellContext, commandContext, connectInformation);
}
internal static void PerformWSManPluginSend(
IntPtr pluginContext,
IntPtr requestDetails, // WSMAN_PLUGIN_REQUEST*
int flags,
IntPtr shellContext, // PVOID
IntPtr commandContext, // PVOID
string stream,
IntPtr inboundData) // WSMAN_DATA*
{
WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext);
if (null == pluginToUse)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.PluginContextNotFound,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginContextNotFound));
return;
}
// Marshal the incoming pointers into managed types prior to the call
WSManNativeApi.WSManPluginRequest request = WSManNativeApi.WSManPluginRequest.UnMarshal(requestDetails);
WSManNativeApi.WSManData_UnToMan data = WSManNativeApi.WSManData_UnToMan.UnMarshal(inboundData);
pluginToUse.SendOneItemToShellOrCommand(request, flags, shellContext, commandContext, stream, data);
}
internal static void PerformWSManPluginReceive(
IntPtr pluginContext, // PVOID
IntPtr requestDetails, // WSMAN_PLUGIN_REQUEST*
int flags,
IntPtr shellContext,
IntPtr commandContext,
IntPtr streamSet) // WSMAN_STREAM_ID_SET*
{
WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext);
if (null == pluginToUse)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.PluginContextNotFound,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginContextNotFound));
return;
}
// Marshal the incoming pointers into managed types prior to the call
WSManNativeApi.WSManPluginRequest request = WSManNativeApi.WSManPluginRequest.UnMarshal(requestDetails);
WSManNativeApi.WSManStreamIDSet_UnToMan streamIdSet = WSManNativeApi.WSManStreamIDSet_UnToMan.UnMarshal(streamSet);
pluginToUse.EnableShellOrCommandToSendDataToClient(pluginContext, request, flags, shellContext, commandContext, streamIdSet);
}
internal static void PerformWSManPluginSignal(
IntPtr pluginContext, // PVOID
IntPtr requestDetails, // WSMAN_PLUGIN_REQUEST*
int flags,
IntPtr shellContext, // PVOID
IntPtr commandContext, // PVOID
string code)
{
WSManNativeApi.WSManPluginRequest request = WSManNativeApi.WSManPluginRequest.UnMarshal(requestDetails);
// Close Command
if (IntPtr.Zero != commandContext)
{
if (!String.Equals(code, WSManPluginConstants.CtrlCSignal, StringComparison.Ordinal))
{
// Close operations associated with this command..
WSManPluginOperationShutdownContext cmdCtxt = new WSManPluginOperationShutdownContext(pluginContext, shellContext, commandContext, false);
if (null != cmdCtxt)
{
PerformCloseOperation(cmdCtxt);
}
else
{
ReportOperationComplete(request, WSManPluginErrorCodes.OutOfMemory);
return;
}
}
else
{
// we got crtl_c (stop) message from client. so stop powershell
WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext);
if (null == pluginToUse)
{
ReportOperationComplete(
request,
WSManPluginErrorCodes.PluginContextNotFound,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginContextNotFound));
return;
}
// this will ReportOperationComplete by itself..
// so we just here.
pluginToUse.StopCommand(request, shellContext, commandContext);
return;
}
}
ReportOperationComplete(request, WSManPluginErrorCodes.NoError);
}
/// <summary>
/// Close the operation specified by the supplied context.
/// </summary>
/// <param name="context"></param>
internal static void PerformCloseOperation(
WSManPluginOperationShutdownContext context)
{
WSManPluginInstance pluginToUse = GetFromActivePlugins(context.pluginContext);
if (null == pluginToUse)
{
return;
}
if (IntPtr.Zero == context.commandContext)
{
// this is targeted at shell
pluginToUse.CloseShellOperation(context);
}
else
{
// shutdown is targeted at command
pluginToUse.CloseCommandOperation(context);
}
}
/// <summary>
/// performs deinitialization during shutdown.
/// </summary>
/// <param name="pluginContext"></param>
internal static void PerformShutdown(
IntPtr pluginContext)
{
WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext);
if (null == pluginToUse)
{
return;
}
pluginToUse.Shutdown();
}
private static WSManPluginInstance GetFromActivePlugins(IntPtr pluginContext)
{
lock (s_activePlugins)
{
WSManPluginInstance result = null;
s_activePlugins.TryGetValue(pluginContext, out result);
return result;
}
}
private static void AddToActivePlugins(IntPtr pluginContext, WSManPluginInstance plugin)
{
lock (s_activePlugins)
{
if (!s_activePlugins.ContainsKey(pluginContext))
{
s_activePlugins.Add(pluginContext, plugin);
return;
}
}
}
#region Utilities
/// <summary>
/// report operation complete to WSMan and supply a reason (if any)
/// </summary>
/// <param name="requestDetails"></param>
/// <param name="errorCode"></param>
internal static void ReportWSManOperationComplete(
WSManNativeApi.WSManPluginRequest requestDetails,
WSManPluginErrorCodes errorCode)
{
Dbg.Assert(null != requestDetails, "requestDetails cannot be null in operation complete.");
PSEtwLog.LogAnalyticInformational(PSEventId.ReportOperationComplete,
PSOpcode.Close, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
(requestDetails.unmanagedHandle).ToString(),
Convert.ToString(errorCode, CultureInfo.InvariantCulture),
String.Empty,
String.Empty);
ReportOperationComplete(requestDetails.unmanagedHandle, errorCode);
}
/// <summary>
/// extract message from exception (if any) and report operation complete with it to WSMan
/// </summary>
/// <param name="requestDetails"></param>
/// <param name="reasonForClose"></param>
internal static void ReportWSManOperationComplete(
WSManNativeApi.WSManPluginRequest requestDetails,
Exception reasonForClose)
{
Dbg.Assert(null != requestDetails, "requestDetails cannot be null in operation complete.");
WSManPluginErrorCodes error = WSManPluginErrorCodes.NoError;
String errorMessage = String.Empty;
String stackTrace = String.Empty;
if (null != reasonForClose)
{
error = WSManPluginErrorCodes.ManagedException;
errorMessage = reasonForClose.Message;
stackTrace = reasonForClose.StackTrace;
}
PSEtwLog.LogAnalyticInformational(PSEventId.ReportOperationComplete,
PSOpcode.Close, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
requestDetails.ToString(),
Convert.ToString(error, CultureInfo.InvariantCulture),
errorMessage,
stackTrace);
if (null != reasonForClose)
{
// report operation complete to wsman with the error message (if any).
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.ManagedException,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginManagedException,
reasonForClose.Message));
}
else
{
ReportOperationComplete(
requestDetails.unmanagedHandle,
WSManPluginErrorCodes.NoError);
}
}
/// <summary>
/// Sets thread properties like UI Culture, Culture etc..This is needed as code is transitioning from
/// unmanaged heap to managed heap...and thread properties are not set correctly during this
/// transition.
/// Currently WSMan provider supplies only UI Culture related data..so only UI Cutlure is set.
/// </summary>
/// <param name="requestDetails"></param>
internal static void SetThreadProperties(
WSManNativeApi.WSManPluginRequest requestDetails)
{
// requestDetails cannot not be null.
Dbg.Assert(null != requestDetails, "requestDetails cannot be null");
//IntPtr nativeLocaleData = IntPtr.Zero;
WSManNativeApi.WSManDataStruct outputStruct = new WSManNativeApi.WSManDataStruct();
int hResult = wsmanPinvokeStatic.WSManPluginGetOperationParameters(
requestDetails.unmanagedHandle,
WSManPluginConstants.WSManPluginParamsGetRequestedLocale,
outputStruct);
//ref nativeLocaleData);
bool retreivingLocaleSucceeded = (0 == hResult);
WSManNativeApi.WSManData_UnToMan localeData = WSManNativeApi.WSManData_UnToMan.UnMarshal(outputStruct); // nativeLocaleData
//IntPtr nativeDataLocaleData = IntPtr.Zero;
hResult = wsmanPinvokeStatic.WSManPluginGetOperationParameters(
requestDetails.unmanagedHandle,
WSManPluginConstants.WSManPluginParamsGetRequestedDataLocale,
outputStruct);
//ref nativeDataLocaleData);
bool retreivingDataLocaleSucceeded = ((int)WSManPluginErrorCodes.NoError == hResult);
WSManNativeApi.WSManData_UnToMan dataLocaleData = WSManNativeApi.WSManData_UnToMan.UnMarshal(outputStruct); // nativeDataLocaleData
// Set the UI Culture
try
{
if (retreivingLocaleSucceeded && ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT == localeData.Type))
{
CultureInfo uiCultureToUse = new CultureInfo(localeData.Text);
ClrFacade.SetCurrentThreadUiCulture(uiCultureToUse);
}
}
// ignore if there is any exception constructing the culture..
catch (ArgumentException)
{
}
// Set the Culture
try
{
if (retreivingDataLocaleSucceeded && ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT == dataLocaleData.Type))
{
CultureInfo cultureToUse = new CultureInfo(dataLocaleData.Text);
ClrFacade.SetCurrentThreadCulture(cultureToUse);
}
}
// ignore if there is any exception constructing the culture..
catch (ArgumentException)
{
}
}
#if !CORECLR
/// <summary>
/// Handle any unhandled exceptions that get raised in the AppDomain
/// This will log the exception into Crimson logs.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
internal static void UnhandledExceptionHandler(
object sender,
UnhandledExceptionEventArgs args)
{
// args can never be null.
Exception exception = (Exception)args.ExceptionObject;
PSEtwLog.LogOperationalError(PSEventId.AppDomainUnhandledException,
PSOpcode.Close, PSTask.None,
PSKeyword.UseAlwaysOperational,
exception.GetType().ToString(), exception.Message,
exception.StackTrace);
PSEtwLog.LogAnalyticError(PSEventId.AppDomainUnhandledException_Analytic,
PSOpcode.Close, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
exception.GetType().ToString(), exception.Message,
exception.StackTrace);
}
#endif
/// <summary>
/// Alternate wrapper for WSManPluginOperationComplete. TODO: Needed? I could easily use the handle instead and get rid of this? It is only for easier refactoring...
/// </summary>
/// <param name="requestDetails"></param>
/// <param name="errorCode"></param>
/// <param name="errorMessage">Pre-formatted localized string</param>
/// <returns></returns>
internal static void ReportOperationComplete(
WSManNativeApi.WSManPluginRequest requestDetails,
WSManPluginErrorCodes errorCode,
string errorMessage)
{
if (null != requestDetails)
{
ReportOperationComplete(requestDetails.unmanagedHandle, errorCode, errorMessage);
}
// else cannot report if requestDetails is null.
}
/// <summary>
/// Wrapper for WSManPluginOperationComplete. It performs validation prior to making the call.
/// </summary>
/// <param name="requestDetails"></param>
/// <param name="errorCode"></param>
internal static void ReportOperationComplete(
WSManNativeApi.WSManPluginRequest requestDetails,
WSManPluginErrorCodes errorCode)
{
if (null != requestDetails &&
IntPtr.Zero != requestDetails.unmanagedHandle)
{
wsmanPinvokeStatic.WSManPluginOperationComplete(
requestDetails.unmanagedHandle,
0,
(int)errorCode,
null);
}
// else cannot report if requestDetails is null.
}
/// <summary>
/// Wrapper for WSManPluginOperationComplete. It performs validation prior to making the call.
/// </summary>
/// <param name="requestDetails"></param>
/// <param name="errorCode"></param>
/// <param name="errorMessage"></param>
/// <returns></returns>
internal static void ReportOperationComplete(
IntPtr requestDetails,
WSManPluginErrorCodes errorCode,
string errorMessage = "")
{
if (IntPtr.Zero == requestDetails)
{
// cannot report if requestDetails is null.
return;
}
wsmanPinvokeStatic.WSManPluginOperationComplete(
requestDetails,
0,
(int)errorCode,
errorMessage);
return;
}
#endregion
}
} // namespace System.Management.Automation.Remoting
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// PartitionerHelpers.cs
//
// Helper class containing extensions methods to unroll ranges into individual elements,
// find the size of ranges for different returns value of Partitioners
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public static class RangePartitionerHelpers
{
/// <summary>
/// Helpers to extract individual elements from Long range partitioner
/// </summary>
/// <param name="tuple"></param>
/// <returns></returns>
public static IEnumerable<long> UnRoll(this Tuple<long, long> tuple)
{
for (long i = tuple.Item1; i < tuple.Item2; i++)
yield return i;
}
/// <summary>
/// Helpers to extract individual elements from Long range partitioner
/// </summary>
/// <param name="pair"></param>
/// <returns></returns>
public static IEnumerable<long> UnRoll(this KeyValuePair<long, Tuple<long, long>> pair)
{
return pair.Value.UnRoll();
}
/// <summary>
/// Helpers to extract individual elements from Long range partitioner
/// </summary>
/// <param name="tupleEnumerator"></param>
/// <returns></returns>
public static IEnumerable<long> UnRoll(this IEnumerator<Tuple<long, long>> tupleEnumerator)
{
while (tupleEnumerator.MoveNext())
{
for (long i = tupleEnumerator.Current.Item1; i < tupleEnumerator.Current.Item2; i++)
yield return i;
}
}
/// <summary>
/// Helpers to extract individual elements from Long range partitioner
/// </summary>
/// <param name="pairEnumerator"></param>
/// <returns></returns>
public static IEnumerable<long> UnRoll(this IEnumerator<KeyValuePair<long, Tuple<long, long>>> pairEnumerator)
{
long key = -1;
while (pairEnumerator.MoveNext())
{
// Ensure that keys are normalized
if (key != -1)
{
Assert.True(
key.Equals(pairEnumerator.Current.Key - 1),
String.Format("Keys are not normalized {0} {1}", key, pairEnumerator.Current.Key));
}
key = pairEnumerator.Current.Key;
for (long i = pairEnumerator.Current.Value.Item1; i < pairEnumerator.Current.Value.Item2; i++)
yield return i;
}
}
/// <summary>
/// Helper to extract individual indices from Long range partitioner
/// </summary>
/// <param name="pairEnumerator"></param>
/// <returns></returns>
public static IEnumerable<long> UnRollIndices(this IEnumerator<KeyValuePair<long, Tuple<long, long>>> pairEnumerator)
{
long key = -1;
while (pairEnumerator.MoveNext())
{
// Ensure that keys are normalized
if (key != -1)
{
Assert.True(
key.Equals(pairEnumerator.Current.Key - 1),
String.Format("Keys are not normalized {0} {1}", key, pairEnumerator.Current.Key));
}
key = pairEnumerator.Current.Key;
var tuple = pairEnumerator.Current.Value;
yield return key;
}
}
/// <summary>
/// Helpers to extract individual range sizes from Long range partitioner
/// </summary>
/// <param name="tuple"></param>
/// <returns></returns>
public static long GetRangeSize(this Tuple<long, long> tuple)
{
long rangeSize = 0;
for (long i = tuple.Item1; i < tuple.Item2; i++)
{
rangeSize++;
}
return rangeSize;
}
/// <summary>
/// Helpers to extract individual range sizes from Long range partitioner
/// </summary>
/// <param name="pair"></param>
/// <returns></returns>
public static long GetRangeSize(this KeyValuePair<long, Tuple<long, long>> pair)
{
return GetRangeSize(pair.Value);
}
/// <summary>
/// Helpers to extract individual range sizes from Long range partitioner
/// </summary>
/// <param name="tupleEnumerator"></param>
/// <returns></returns>
public static IEnumerable<long> GetRangeSize(this IEnumerator<Tuple<long, long>> tupleEnumerator)
{
while (tupleEnumerator.MoveNext())
{
yield return GetRangeSize(tupleEnumerator.Current);
}
}
/// <summary>
/// Helpers to extract individual range sizes from Long range partitioner
/// </summary>
/// <param name="pairEnumerator"></param>
/// <returns></returns>
public static IEnumerable<long> GetRangeSize(this IEnumerator<KeyValuePair<long, Tuple<long, long>>> pairEnumerator)
{
while (pairEnumerator.MoveNext())
{
yield return GetRangeSize(pairEnumerator.Current.Value);
}
}
/// <summary>
/// Helpers to extract individual elements from int range partitioner
/// </summary>
/// <param name="tuple"></param>
/// <returns></returns>
public static IEnumerable<int> UnRoll(this Tuple<int, int> tuple)
{
for (int i = tuple.Item1; i < tuple.Item2; i++)
yield return i;
}
/// <summary>
/// Helpers to extract individual elements from int range partitioner
/// </summary>
/// <param name="pair"></param>
/// <returns></returns>
public static IEnumerable<int> UnRoll(this KeyValuePair<long, Tuple<int, int>> pair)
{
return pair.Value.UnRoll();
}
/// <summary>
/// Helpers to extract individual elements from int range partitioner
/// </summary>
/// <param name="tupleEnumerator"></param>
/// <returns></returns>
public static IEnumerable<int> UnRoll(this IEnumerator<Tuple<int, int>> tupleEnumerator)
{
while (tupleEnumerator.MoveNext())
{
for (int i = tupleEnumerator.Current.Item1; i < tupleEnumerator.Current.Item2; i++)
yield return i;
}
}
/// <summary>
/// Helpers to extract individual elements from int range partitioner
/// </summary>
/// <param name="pairEnumerator"></param>
/// <returns></returns>
public static IEnumerable<int> UnRoll(this IEnumerator<KeyValuePair<long, Tuple<int, int>>> pairEnumerator)
{
long key = -1;
while (pairEnumerator.MoveNext())
{
// Ensure that keys are normalized
if (key != -1)
{
Assert.True(
key.Equals(pairEnumerator.Current.Key - 1),
String.Format("Keys are not normalized {0} {1}", key, pairEnumerator.Current.Key));
}
key = pairEnumerator.Current.Key;
for (int i = pairEnumerator.Current.Value.Item1; i < pairEnumerator.Current.Value.Item2; i++)
yield return i;
}
}
/// <summary>
/// Helpers to extract individual indices from int range partitioner
/// </summary>
/// <param name="pairEnumerator"></param>
/// <returns></returns>
public static IEnumerable<long> UnRollIndices(this IEnumerator<KeyValuePair<long, Tuple<int, int>>> pairEnumerator)
{
long key = -1;
while (pairEnumerator.MoveNext())
{
// Ensure that keys are normalized
if (key != -1)
{
Assert.True(
key.Equals(pairEnumerator.Current.Key - 1),
String.Format("Keys are not normalized {0} {1}", key, pairEnumerator.Current.Key));
}
key = pairEnumerator.Current.Key;
var tuple = pairEnumerator.Current.Value;
yield return key;
}
}
/// <summary>
/// Helpers to extract individual range sizes from int range partitioner
/// </summary>
/// <param name="tuple"></param>
/// <returns></returns>
public static int GetRangeSize(this Tuple<int, int> tuple)
{
int rangeSize = 0;
for (int i = tuple.Item1; i < tuple.Item2; i++)
{
rangeSize++;
}
return rangeSize;
}
/// <summary>
/// Helpers to extract individual range sizes from int range partitioner
/// </summary>
/// <param name="pair"></param>
/// <returns></returns>
public static int GetRangeSize(this KeyValuePair<long, Tuple<int, int>> pair)
{
return GetRangeSize(pair.Value);
}
/// <summary>
/// Helpers to extract individual range sizes from int range partitioner
/// </summary>
/// <param name="tupleEnumerator"></param>
/// <returns></returns>
public static IEnumerable<int> GetRangeSize(this IEnumerator<Tuple<int, int>> tupleEnumerator)
{
while (tupleEnumerator.MoveNext())
{
yield return GetRangeSize(tupleEnumerator.Current);
}
}
/// <summary>
/// Helpers to extract individual range sizes from int range partitioner
/// </summary>
/// <param name="pairEnumerator"></param>
/// <returns></returns>
public static IEnumerable<int> GetRangeSize(this IEnumerator<KeyValuePair<long, Tuple<int, int>>> pairEnumerator)
{
while (pairEnumerator.MoveNext())
{
yield return GetRangeSize(pairEnumerator.Current.Value);
}
}
/// <summary>
/// Compares 2 enumerables and returns true if they contain the same elements
/// in the same order. Similar to SequenceEqual but with extra diagnostic messages
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="actual"></param>
/// <param name="expected"></param>
/// <returns></returns>
public static bool CompareSequences<T>(this IEnumerable<T> actual, IEnumerable<T> expected)
{
using (var e1 = expected.GetEnumerator())
using (var e2 = actual.GetEnumerator())
{
while (e1.MoveNext())
{
// 'actual' ran out of elements before expected.
if (!e2.MoveNext())
{
Console.WriteLine("Partitioner returned fewer elements. Next element expected: {0}", e1.Current);
return false;
}
if (!e1.Current.Equals(e2.Current))
{
Console.WriteLine("Mismatching elements. Expected: {0}, Actual: {1}", e1.Current, e2.Current);
return false;
}
}
// 'actual' still has elements
if (e2.MoveNext())
{
Console.WriteLine("Partitioner returned more elements. Next element returned by partitioner: {0}", e2.Current);
return false;
}
}
return true;
}
/// <summary>
/// Helper to yield an enumerable of long
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <returns></returns>
public static IEnumerable<long> LongEnumerable(long from, long to)
{
for (long i = from; i < to; i++)
yield return i;
}
/// <summary>
/// Helper to yield an enumerable of ints
/// used instead of Enumerable.Range since it doesn't support negative values
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <returns></returns>
public static IEnumerable<int> IntEnumerable(int from, int to)
{
for (int i = from; i < to; i++)
yield return i;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// Copyright (c) Lead Pipe Software. All rights reserved.
// Licensed under the MIT License. Please see the LICENSE file in the project root for full license information.
// --------------------------------------------------------------------------------------------------------------------
using LeadPipe.Net.Extensions;
using System;
namespace LeadPipe.Net
{
/// <summary>
/// A fluent guarding class.
/// </summary>
public class Guard
{
/// <summary>
/// The action to invoke.
/// </summary>
private Action actionToInvoke;
/// <summary>
/// The exception to throw.
/// </summary>
private Exception exception;
/// <summary>
/// Provides a context to help chain together exceptions that may occur in different threads.
/// </summary>
private string relationshipId;
/// <summary>
/// Gets the start of the fluent guard chain.
/// </summary>
public static Guard Will
{
get
{
return new Guard();
}
}
/// <summary>
/// Chaining candy.
/// </summary>
public Guard And
{
get
{
return this;
}
}
/// <summary>
/// Sets the relationship id.
/// </summary>
/// <param name="relationshipId">The relationship id.</param>
/// <remarks>
/// <para>
/// Note that this must be called BEFORE any Throw statements if you want the relationship displayed in the message.
/// </para>
/// </remarks>
/// <returns>The Guard with the relationship id set.</returns>
public Guard AssociateExceptionsWith(string relationshipId)
{
this.relationshipId = relationshipId;
return this;
}
/// <summary>
/// Sets the action to invoke when the guard condition is met.
/// </summary>
/// <param name="actionToInvoke">The action.</param>
public Guard Execute(Action actionToInvoke)
{
this.actionToInvoke = actionToInvoke;
return this;
}
public void Now()
{
// Invoke the action if there is one...
if (actionToInvoke.IsNotNull())
{
this.actionToInvoke.Invoke();
}
if (this.exception.IsNotNull())
{
throw this.exception;
}
}
/// <summary>
/// Guards against an argument with a default value.
/// </summary>
/// <typeparam name="T">The argument type.</typeparam>
/// <param name="argument">The argument.</param>
/// <exception cref="System.ArgumentNullException"></exception>
/// <remarks><code>
/// Guard.ProtectAgainstDefaultValueArgument(() => argument);
/// </code></remarks>
public void ProtectAgainstDefaultValueArgument<T>(Func<T> argument)
{
if (!argument().IsDefaultValue()) return;
var message = string.Format("Argument of type '{0}' cannot be the type's default value.", typeof(T));
var exceptionMessage = this.AddRelationshipIdToExceptionMessage(message);
var fieldName = GetFieldName(argument);
if (fieldName.IsNotNull())
{
throw new ArgumentOutOfRangeException(fieldName, exceptionMessage);
}
throw new ArgumentOutOfRangeException(exceptionMessage);
}
/// <summary>
/// Guards against a null argument.
/// </summary>
/// <typeparam name="T">The argument type.</typeparam>
/// <param name="argument">The argument.</param>
/// <exception cref="System.ArgumentNullException"></exception>
/// <remarks><code>
/// Guard.AgainstNullArgument(() => argument);
/// </code></remarks>
public void ProtectAgainstNullArgument<T>(Func<T> argument) where T : class
{
if (argument().IsNotNull())
{
return;
}
var message = string.Format("Argument of type '{0}' cannot be null.", typeof(T));
var exceptionMessage = this.AddRelationshipIdToExceptionMessage(message);
var fieldName = GetFieldName(argument);
if (fieldName.IsNotNull())
{
throw new ArgumentNullException(fieldName, exceptionMessage);
}
throw new ArgumentNullException(exceptionMessage);
}
/// <summary>
/// Guards against a null or empty string argument.
/// </summary>
/// <typeparam name="T">The argument type.</typeparam>
/// <param name="argument">The argument.</param>
/// <exception cref="System.ArgumentNullException"></exception>
/// <remarks><code>
/// Guard.AgainstNullArgument(() => argument);
/// </code></remarks>
public void ProtectAgainstNullOrEmptyStringArgument<T>(Func<T> argument) where T : class
{
var argumentAsString = argument().IsNull() ? null : argument().ToString();
if (!string.IsNullOrEmpty(argumentAsString))
{
return;
}
var message = string.Format("Argument of type '{0}' cannot be null.", typeof(T));
var exceptionMessage = this.AddRelationshipIdToExceptionMessage(message);
var fieldName = GetFieldName(argument);
if (fieldName.IsNotNull())
{
throw new ArgumentNullException(fieldName, exceptionMessage);
}
throw new ArgumentNullException(exceptionMessage);
}
/// <summary>
/// Gets an exception.
/// </summary>
/// <param name="parameterName">Name of the parameter.</param>
/// <returns>The Guard with an exception type set.</returns>
public Guard ThrowArgumentNullException(string parameterName)
{
this.exception = (ArgumentNullException)Activator.CreateInstance(typeof(ArgumentNullException), parameterName);
return this;
}
/// <summary>
/// Gets an exception.
/// </summary>
/// <param name="parameterName">Name of the parameter.</param>
/// <param name="message">The exception message.</param>
/// <returns>The Guard with an exception type set.</returns>
public Guard ThrowArgumentNullException(string parameterName, string message)
{
this.exception = (ArgumentNullException)Activator.CreateInstance(typeof(ArgumentNullException), parameterName, message);
return this;
}
/// <summary>
/// Sets up to throw an InvalidOperationException with no message if the assertion fails.
/// </summary>
/// <returns>The Guard with an exception type set.</returns>
public Guard ThrowException()
{
var exceptionMessage = this.AddRelationshipIdToExceptionMessage(string.Empty);
this.exception = (InvalidOperationException)Activator.CreateInstance(typeof(InvalidOperationException), exceptionMessage);
return this;
}
/// <summary>
/// Sets the message to include in the InvalidOperationException if the assertion fails.
/// </summary>
/// <param name="message">The exception message.</param>
/// <returns>The Guard with an exception type set.</returns>
public Guard ThrowException(string message)
{
var exceptionMessage = this.AddRelationshipIdToExceptionMessage(message);
this.exception = (InvalidOperationException)Activator.CreateInstance(typeof(InvalidOperationException), exceptionMessage);
return this;
}
/// <summary>
/// Sets the exception to throw if the assertion fails.
/// </summary>
/// <remarks>
/// <para>Note that the relationship will not included even if it is set when using this call.</para>
/// </remarks>
/// <param name="exceptionToThrow">The exception to throw.</param>
/// <returns>The Guard with an exception set.</returns>
public Guard ThrowException(Exception exceptionToThrow)
{
this.exception = exceptionToThrow;
return this;
}
/// <summary>
/// Gets an exception.
/// </summary>
/// <typeparam name="TException">The type of the exception.</typeparam>
/// <returns>The Guard with an exception type set.</returns>
public Guard ThrowExceptionOfType<TException>() where TException : Exception
{
var exceptionMessage = this.AddRelationshipIdToExceptionMessage(String.Empty);
this.exception = (TException)Activator.CreateInstance(typeof(TException), exceptionMessage);
return this;
}
/// <summary>
/// Gets an exception.
/// </summary>
/// <typeparam name="TException">The type of the exception.</typeparam>
/// <param name="message">The exception message.</param>
/// <returns>The Guard with an exception type set.</returns>
public Guard ThrowExceptionOfType<TException>(string message) where TException : Exception
{
var exceptionMessage = this.AddRelationshipIdToExceptionMessage(message);
this.exception = (TException)Activator.CreateInstance(typeof(TException), exceptionMessage);
return this;
}
/// <summary>
/// Conditions the specified assertion.
/// </summary>
/// <param name="assertion">if set to <c>true</c> [assertion].</param>
public void When(bool assertion)
{
// If the assertion is false then bail...
if (!assertion) return;
Now();
}
/// <summary>
/// Gets the name of the field.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="argument">The argument.</param>
/// <returns>The field name.</returns>
private static string GetFieldName<T>(Func<T> argument)
{
/*
* Good information about this technique can be found at http://abdullin.com/journal/2008/12/19/how-to-get-parameter-name-and-argument-value-from-c-lambda-v.html
*/
try
{
// Get the IL code behind the delegate...
var methodBody = argument.Method.GetMethodBody();
if (methodBody == null) return null;
var il = methodBody.GetILAsByteArray();
if (il == null) return null;
// Get the field handle (bytes 2-6 represent the field handle)...
var fieldHandle = BitConverter.ToInt32(il, 2);
// Resolve the handle...
var field = argument.Target.GetType().Module.ResolveField(fieldHandle);
if (field == null) return null;
return field.Name;
}
catch (Exception)
{
// By design
}
return null;
}
private string AddRelationshipIdToExceptionMessage(string rootMessage)
{
if (rootMessage.IsNullOrEmpty() && this.relationshipId.IsNotNullOrEmpty()) return this.relationshipId.FormattedWith("[{0}]");
return this.relationshipId.IsNotNullOrEmpty()
? string.Format("[{0}] {1}", this.relationshipId, rootMessage)
: rootMessage;
}
}
}
| |
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.Chrome, "Moving outside of view port throws exception in spec-compliant driver")]
[IgnoreBrowser(Browser.Edge, "Moving outside of view port throws exception in spec-compliant driver")]
[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")]
[IgnoreBrowser(Browser.Safari, "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]
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);
Assert.That(() => actionProvider.DragAndDropToOffset(img, 2147480000, 2147400000).Perform(), Throws.InstanceOf<WebDriverException>());
new Actions(driver).Release().Perform();
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Moving outside of view port throws exception in spec-compliant driver")]
[IgnoreBrowser(Browser.Edge, "Moving outside of view port throws exception in spec-compliant driver")]
[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")]
[IgnoreBrowser(Browser.Safari, "Moving outside of view port throws exception in spec-compliant driver")]
public void ShouldAllowUsersToDragAndDropToElementsOffTheCurrentViewPort()
{
Size originalSize = driver.Manage().Window.Size;
Size testSize = new Size(300, 300);
driver.Url = dragAndDropPage;
driver.Manage().Window.Size = testSize;
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
{
driver.Manage().Window.Size = originalSize;
}
}
[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).Perform();
actionProvider.Reset();
actionProvider.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;
}
}
}
| |
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Diagnostics;
using System.Windows.Input;
using AppStudio.Uwp.Actions;
using AppStudio.Uwp.Cache;
using AppStudio.Uwp.Commands;
using AppStudio.Uwp.DataSync;
using AppStudio.Uwp.Navigation;
using AppStudio.DataProviders;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI.Xaml.Controls;
using DJNanoShow.Config;
namespace DJNanoShow.ViewModels
{
public class ListViewModel : PageViewModelBase, INavigable
{
private ObservableCollection<ItemViewModel> _items = new ObservableCollection<ItemViewModel>();
private bool _hasMoreItems;
private bool _hasItems;
private int _visibleItems;
private Func<bool, Func<ItemViewModel, bool>, Task<DateTime?>> LoadDataInternal;
private ListViewModel()
{
}
public static ListViewModel CreateNew<TSchema>(SectionConfigBase<TSchema> sectionConfig, int visibleItems = 0) where TSchema : SchemaBase
{
var vm = new ListViewModel
{
SectionName = sectionConfig.Name,
Title = sectionConfig.ListPage.Title,
NavigationInfo = sectionConfig.ListPage.ListNavigationInfo,
PageTitle = sectionConfig.ListPage.PageTitle,
_visibleItems = visibleItems,
HasLocalData = !sectionConfig.NeedsNetwork
};
var settings = new CacheSettings
{
Key = sectionConfig.Name,
Expiration = vm.CacheExpiration,
NeedsNetwork = sectionConfig.NeedsNetwork,
UseStorage = sectionConfig.NeedsNetwork,
};
//we save a reference to the load delegate in order to avoid export TSchema outside the view model
vm.LoadDataInternal = (refresh, filterFunc) => AppCache.LoadItemsAsync<TSchema>(settings, sectionConfig.LoadDataAsyncFunc, (content) => vm.ParseItems(sectionConfig.ListPage, content, filterFunc), refresh);
if (sectionConfig.NeedsNetwork)
{
vm.Actions.Add(new ActionInfo
{
Command = vm.Refresh,
Style = ActionKnownStyles.Refresh,
Name = "RefreshButton",
ActionType = ActionType.Primary
});
}
return vm;
}
public async Task LoadDataAsync(bool forceRefresh = false)
{
try
{
HasLoadDataErrors = false;
IsBusy = true;
LastUpdated = await LoadDataInternal(forceRefresh, null);
}
catch (Exception ex)
{
Microsoft.ApplicationInsights.TelemetryClient telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
telemetry.TrackException(ex);
HasLoadDataErrors = true;
Debug.WriteLine(ex.ToString());
}
finally
{
IsBusy = false;
}
}
public async Task SearchDataAsync(string searchTerm)
{
if (!string.IsNullOrEmpty(searchTerm))
{
try
{
HasLoadDataErrors = false;
IsBusy = true;
LastUpdated = await LoadDataInternal(true, i => i.ContainsString(searchTerm));
}
catch (Exception ex)
{
Microsoft.ApplicationInsights.TelemetryClient telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
telemetry.TrackException(ex);
HasLoadDataErrors = true;
Debug.WriteLine(ex.ToString());
}
finally
{
IsBusy = false;
}
}
}
public async Task FilterDataAsync(List<string> itemsId)
{
if (itemsId != null && itemsId.Any())
{
try
{
HasLoadDataErrors = false;
IsBusy = true;
LastUpdated = await LoadDataInternal(true, i => itemsId.Contains(i.Id));
}
catch (Exception ex)
{
Microsoft.ApplicationInsights.TelemetryClient telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
telemetry.TrackException(ex);
HasLoadDataErrors = true;
Debug.WriteLine(ex.ToString());
}
finally
{
IsBusy = false;
}
}
}
internal void CleanItems()
{
this.Items.Clear();
this.HasItems = false;
}
public RelayCommand<ItemViewModel> ItemClickCommand
{
get
{
return new RelayCommand<ItemViewModel>(
(item) =>
{
NavigationService.NavigateTo(item);
});
}
}
public RelayCommand<INavigable> SectionHeaderClickCommand
{
get
{
return new RelayCommand<INavigable>(
(item) =>
{
NavigationService.NavigateTo(item);
});
}
}
public NavigationInfo NavigationInfo { get; set; }
public string PageTitle { get; set; }
public ObservableCollection<ItemViewModel> Items
{
get { return _items; }
private set { SetProperty(ref _items, value); }
}
public bool HasMoreItems
{
get { return _hasMoreItems; }
private set { SetProperty(ref _hasMoreItems, value); }
}
public bool HasItems
{
get { return _hasItems; }
private set { SetProperty(ref _hasItems, value); }
}
public ICommand Refresh
{
get
{
return new RelayCommand(async () =>
{
await LoadDataAsync(true);
});
}
}
public void ShareContent(DataRequest dataRequest, bool supportsHtml = true)
{
if (Items != null && Items.Count > 0)
{
ShareContent(dataRequest, Items[0], supportsHtml);
}
}
private void ParseItems<TSchema>(ListPageConfig<TSchema> listConfig, CachedContent<TSchema> content, Func<ItemViewModel, bool> filterFunc) where TSchema : SchemaBase
{
var parsedItems = new List<ItemViewModel>();
foreach (var item in GetVisibleItems(content, _visibleItems))
{
var parsedItem = new ItemViewModel
{
Id = item._id,
NavigationInfo = listConfig.DetailNavigation(item)
};
listConfig.LayoutBindings(parsedItem, item);
if (filterFunc == null)
{
parsedItems.Add(parsedItem);
}
else if (filterFunc(parsedItem))
{
parsedItems.Add(parsedItem);
}
}
Items.Sync(parsedItems);
HasItems = Items.Count > 0;
HasMoreItems = content.Items.Count() > Items.Count;
}
private IEnumerable<TSchema> GetVisibleItems<TSchema>(CachedContent<TSchema> content, int visibleItems) where TSchema : SchemaBase
{
if (visibleItems == 0)
{
return content.Items;
}
else
{
return content.Items
.Take(visibleItems);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Net.Http.Headers
{
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix",
Justification = "This is not a collection")]
public sealed class HttpRequestHeaders : HttpHeaders
{
private const int AcceptSlot = 0;
private const int AcceptCharsetSlot = 1;
private const int AcceptEncodingSlot = 2;
private const int AcceptLanguageSlot = 3;
private const int ExpectSlot = 4;
private const int IfMatchSlot = 5;
private const int IfNoneMatchSlot = 6;
private const int TransferEncodingSlot = 7;
private const int UserAgentSlot = 8;
private const int NumCollectionsSlots = 9;
private object[] _specialCollectionsSlots;
private HttpGeneralHeaders _generalHeaders;
private bool _expectContinueSet;
#region Request Headers
private T GetSpecializedCollection<T>(int slot, Func<HttpRequestHeaders, T> creationFunc)
{
// 9 properties each lazily allocate a collection to store the value(s) for that property.
// Rather than having a field for each of these, store them untyped in an array that's lazily
// allocated. Then we only pay for the 72 bytes for those fields when any is actually accessed.
object[] collections = _specialCollectionsSlots ?? (_specialCollectionsSlots = new object[NumCollectionsSlots]);
object result = collections[slot];
if (result == null)
{
collections[slot] = result = creationFunc(this);
}
return (T)result;
}
public HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue> Accept =>
GetSpecializedCollection(AcceptSlot, thisRef => new HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue>(KnownHeaders.Accept.Descriptor, thisRef));
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Charset", Justification = "The HTTP header name is 'Accept-Charset'.")]
public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptCharset =>
GetSpecializedCollection(AcceptCharsetSlot, thisRef => new HttpHeaderValueCollection<StringWithQualityHeaderValue>(KnownHeaders.AcceptCharset.Descriptor, thisRef));
public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptEncoding =>
GetSpecializedCollection(AcceptEncodingSlot, thisRef => new HttpHeaderValueCollection<StringWithQualityHeaderValue>(KnownHeaders.AcceptEncoding.Descriptor, thisRef));
public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptLanguage =>
GetSpecializedCollection(AcceptLanguageSlot, thisRef => new HttpHeaderValueCollection<StringWithQualityHeaderValue>(KnownHeaders.AcceptLanguage.Descriptor, thisRef));
public AuthenticationHeaderValue Authorization
{
get { return (AuthenticationHeaderValue)GetParsedValues(KnownHeaders.Authorization.Descriptor); }
set { SetOrRemoveParsedValue(KnownHeaders.Authorization.Descriptor, value); }
}
public HttpHeaderValueCollection<NameValueWithParametersHeaderValue> Expect
{
get { return ExpectCore; }
}
public bool? ExpectContinue
{
get
{
if (ExpectCore.IsSpecialValueSet)
{
return true;
}
if (_expectContinueSet)
{
return false;
}
return null;
}
set
{
if (value == true)
{
_expectContinueSet = true;
ExpectCore.SetSpecialValue();
}
else
{
_expectContinueSet = value != null;
ExpectCore.RemoveSpecialValue();
}
}
}
public string From
{
get { return (string)GetParsedValues(KnownHeaders.From.Descriptor); }
set
{
// Null and empty string are equivalent. In this case it means, remove the From header value (if any).
if (value == string.Empty)
{
value = null;
}
if ((value != null) && !HeaderUtilities.IsValidEmailAddress(value))
{
throw new FormatException(SR.net_http_headers_invalid_from_header);
}
SetOrRemoveParsedValue(KnownHeaders.From.Descriptor, value);
}
}
public string Host
{
get { return (string)GetParsedValues(KnownHeaders.Host.Descriptor); }
set
{
// Null and empty string are equivalent. In this case it means, remove the Host header value (if any).
if (value == string.Empty)
{
value = null;
}
string host = null;
if ((value != null) && (HttpRuleParser.GetHostLength(value, 0, false, out host) != value.Length))
{
throw new FormatException(SR.net_http_headers_invalid_host_header);
}
SetOrRemoveParsedValue(KnownHeaders.Host.Descriptor, value);
}
}
public HttpHeaderValueCollection<EntityTagHeaderValue> IfMatch =>
GetSpecializedCollection(IfMatchSlot, thisRef => new HttpHeaderValueCollection<EntityTagHeaderValue>(KnownHeaders.IfMatch.Descriptor, thisRef));
public DateTimeOffset? IfModifiedSince
{
get { return HeaderUtilities.GetDateTimeOffsetValue(KnownHeaders.IfModifiedSince.Descriptor, this); }
set { SetOrRemoveParsedValue(KnownHeaders.IfModifiedSince.Descriptor, value); }
}
public HttpHeaderValueCollection<EntityTagHeaderValue> IfNoneMatch =>
GetSpecializedCollection(IfNoneMatchSlot, thisRef => new HttpHeaderValueCollection<EntityTagHeaderValue>(KnownHeaders.IfNoneMatch.Descriptor, thisRef));
public RangeConditionHeaderValue IfRange
{
get { return (RangeConditionHeaderValue)GetParsedValues(KnownHeaders.IfRange.Descriptor); }
set { SetOrRemoveParsedValue(KnownHeaders.IfRange.Descriptor, value); }
}
public DateTimeOffset? IfUnmodifiedSince
{
get { return HeaderUtilities.GetDateTimeOffsetValue(KnownHeaders.IfUnmodifiedSince.Descriptor, this); }
set { SetOrRemoveParsedValue(KnownHeaders.IfUnmodifiedSince.Descriptor, value); }
}
public int? MaxForwards
{
get
{
object storedValue = GetParsedValues(KnownHeaders.MaxForwards.Descriptor);
if (storedValue != null)
{
return (int)storedValue;
}
return null;
}
set { SetOrRemoveParsedValue(KnownHeaders.MaxForwards.Descriptor, value); }
}
public AuthenticationHeaderValue ProxyAuthorization
{
get { return (AuthenticationHeaderValue)GetParsedValues(KnownHeaders.ProxyAuthorization.Descriptor); }
set { SetOrRemoveParsedValue(KnownHeaders.ProxyAuthorization.Descriptor, value); }
}
public RangeHeaderValue Range
{
get { return (RangeHeaderValue)GetParsedValues(KnownHeaders.Range.Descriptor); }
set { SetOrRemoveParsedValue(KnownHeaders.Range.Descriptor, value); }
}
public Uri Referrer
{
get { return (Uri)GetParsedValues(KnownHeaders.Referer.Descriptor); }
set { SetOrRemoveParsedValue(KnownHeaders.Referer.Descriptor, value); }
}
public HttpHeaderValueCollection<TransferCodingWithQualityHeaderValue> TE =>
GetSpecializedCollection(TransferEncodingSlot, thisRef => new HttpHeaderValueCollection<TransferCodingWithQualityHeaderValue>(KnownHeaders.TE.Descriptor, thisRef));
public HttpHeaderValueCollection<ProductInfoHeaderValue> UserAgent =>
GetSpecializedCollection(UserAgentSlot, thisRef => new HttpHeaderValueCollection<ProductInfoHeaderValue>(KnownHeaders.UserAgent.Descriptor, thisRef));
private HttpHeaderValueCollection<NameValueWithParametersHeaderValue> ExpectCore =>
GetSpecializedCollection(ExpectSlot, thisRef => new HttpHeaderValueCollection<NameValueWithParametersHeaderValue>(KnownHeaders.Expect.Descriptor, thisRef, HeaderUtilities.ExpectContinue));
#endregion
#region General Headers
public CacheControlHeaderValue CacheControl
{
get { return GeneralHeaders.CacheControl; }
set { GeneralHeaders.CacheControl = value; }
}
public HttpHeaderValueCollection<string> Connection
{
get { return GeneralHeaders.Connection; }
}
public bool? ConnectionClose
{
get { return HttpGeneralHeaders.GetConnectionClose(this, _generalHeaders); } // special-cased to avoid forcing _generalHeaders initialization
set { GeneralHeaders.ConnectionClose = value; }
}
public DateTimeOffset? Date
{
get { return GeneralHeaders.Date; }
set { GeneralHeaders.Date = value; }
}
public HttpHeaderValueCollection<NameValueHeaderValue> Pragma
{
get { return GeneralHeaders.Pragma; }
}
public HttpHeaderValueCollection<string> Trailer
{
get { return GeneralHeaders.Trailer; }
}
public HttpHeaderValueCollection<TransferCodingHeaderValue> TransferEncoding
{
get { return GeneralHeaders.TransferEncoding; }
}
public bool? TransferEncodingChunked
{
get { return HttpGeneralHeaders.GetTransferEncodingChunked(this, _generalHeaders); } // special-cased to avoid forcing _generalHeaders initialization
set { GeneralHeaders.TransferEncodingChunked = value; }
}
public HttpHeaderValueCollection<ProductHeaderValue> Upgrade
{
get { return GeneralHeaders.Upgrade; }
}
public HttpHeaderValueCollection<ViaHeaderValue> Via
{
get { return GeneralHeaders.Via; }
}
public HttpHeaderValueCollection<WarningHeaderValue> Warning
{
get { return GeneralHeaders.Warning; }
}
#endregion
internal HttpRequestHeaders()
: base(HttpHeaderType.General | HttpHeaderType.Request | HttpHeaderType.Custom, HttpHeaderType.Response)
{
}
internal override void AddHeaders(HttpHeaders sourceHeaders)
{
base.AddHeaders(sourceHeaders);
HttpRequestHeaders sourceRequestHeaders = sourceHeaders as HttpRequestHeaders;
Debug.Assert(sourceRequestHeaders != null);
// Copy special values but do not overwrite.
if (sourceRequestHeaders._generalHeaders != null)
{
GeneralHeaders.AddSpecialsFrom(sourceRequestHeaders._generalHeaders);
}
bool? expectContinue = ExpectContinue;
if (!expectContinue.HasValue)
{
ExpectContinue = sourceRequestHeaders.ExpectContinue;
}
}
private HttpGeneralHeaders GeneralHeaders => _generalHeaders ?? (_generalHeaders = new HttpGeneralHeaders(this));
}
}
| |
// 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 will encapsulate an uint and
** provide an Object representation of it.
**
**
===========================================================*/
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System
{
// * Wrapper for unsigned 32 bit integers.
[CLSCompliant(false)]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
[System.Runtime.InteropServices.ComVisible(true)]
public struct UInt32 : IComparable, IFormattable, IComparable<UInt32>, IEquatable<UInt32>, IConvertible
{
private uint _value;
public const uint MaxValue = (uint)0xffffffff;
public const uint MinValue = 0U;
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type UInt32, this method throws an ArgumentException.
//
int IComparable.CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is UInt32)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
uint i = (uint)value;
if (_value < i) return -1;
if (_value > i) return 1;
return 0;
}
throw new ArgumentException(SR.Arg_MustBeUInt32);
}
public int CompareTo(UInt32 value)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (_value < value) return -1;
if (_value > value) return 1;
return 0;
}
public override bool Equals(Object obj)
{
if (!(obj is UInt32))
{
return false;
}
return _value == ((UInt32)obj)._value;
}
[NonVersionable]
public bool Equals(UInt32 obj)
{
return _value == obj;
}
// The absolute value of the int contained.
public override int GetHashCode()
{
return ((int)_value);
}
// The base 10 representation of the number with no extra padding.
[System.Security.SecuritySafeCritical] // auto-generated
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatUInt32(_value, null, null);
}
[System.Security.SecuritySafeCritical] // auto-generated
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatUInt32(_value, null, provider);
}
[System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatUInt32(_value, format, null);
}
[System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatUInt32(_value, format, provider);
}
[CLSCompliant(false)]
public static uint Parse(String s)
{
return FormatProvider.ParseUInt32(s, NumberStyles.Integer, null);
}
internal static void ValidateParseStyleInteger(NumberStyles style)
{
// Check for undefined flags
if ((style & Decimal.InvalidNumberStyles) != 0)
{
throw new ArgumentException(SR.Argument_InvalidNumberStyles, "style");
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // Check for hex number
if ((style & ~NumberStyles.HexNumber) != 0)
{
throw new ArgumentException(SR.Arg_InvalidHexStyle);
}
}
}
[CLSCompliant(false)]
public static uint Parse(String s, NumberStyles style)
{
ValidateParseStyleInteger(style);
return FormatProvider.ParseUInt32(s, style, null);
}
[CLSCompliant(false)]
public static uint Parse(String s, IFormatProvider provider)
{
return FormatProvider.ParseUInt32(s, NumberStyles.Integer, provider);
}
[CLSCompliant(false)]
public static uint Parse(String s, NumberStyles style, IFormatProvider provider)
{
ValidateParseStyleInteger(style);
return FormatProvider.ParseUInt32(s, style, provider);
}
[CLSCompliant(false)]
public static bool TryParse(String s, out UInt32 result)
{
return FormatProvider.TryParseUInt32(s, NumberStyles.Integer, null, out result);
}
[CLSCompliant(false)]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt32 result)
{
ValidateParseStyleInteger(style);
return FormatProvider.TryParseUInt32(s, style, provider, out result);
}
//
// IConvertible implementation
//
TypeCode IConvertible.GetTypeCode()
{
return TypeCode.UInt32;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(_value);
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(_value);
}
/// <internalonly/>
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(_value);
}
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(_value);
}
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(_value);
}
/// <internalonly/>
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(_value);
}
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(_value);
}
/// <internalonly/>
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return _value;
}
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(_value);
}
/// <internalonly/>
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(_value);
}
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(_value);
}
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(_value);
}
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(_value);
}
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "UInt32", "DateTime"));
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
using System.Collections.Generic;
using System.Collections.Immutable;
using NLog;
using Logger = NLog.Logger;
namespace nJocLogic.propNet.factory.flattener
{
using System;
using System.Linq;
using data;
using gameContainer;
using util.gdl;
using util.gdl.model.assignments;
/// <summary>
/// PropNetFlattener is an implementation of a GDL flattener using fixed-point
/// analysis of the rules. This flattener works on many small and medium-sized
/// games, but can fail on very large games.
///
/// To use this class:
/// PropNetFlattener PF = new PropNetFlattener(description);
/// var flatDescription = PF.flatten();
/// return converter.convert(flatDescription);
/// </summary>
public class PropNetFlattener
{
private static readonly Logger Logger = LogManager.GetLogger("logic.flattener");
private readonly List<Expression> _description;
/// <summary>
/// A mapping from a TermObject to each assignment that it exists in
/// </summary>
public class Index : Dictionary<TermObject, Assignments> { }
/// <summary>
/// Holds a term, its constants and variables and a generic version of itself (where constants and variables have been replaced by a generic variable)
/// Also holds the domain of the condition
/// </summary>
public class Condition
{
private readonly PropNetFlattener _flattener;
public Condition(Term template, PropNetFlattener flattener)
{
_flattener = flattener;
Template = GetConstantAndVariableList(template);
_key = FindGenericForm(template);
UpdateDom();
}
internal void UpdateDom()
{
Dom = !_flattener._domains.ContainsKey(_key) ? null : _flattener._domains[_key];
}
public readonly List<Term> Template; // A list of contants and variables that are used in the term (_key)
public Domain Dom;
readonly Term _key;
public override String ToString()
{
return Template.ToString();
}
public override int GetHashCode()
{
return _key.GetHashCode();
}
public override bool Equals(object obj)
{
var cond = obj as Condition;
return cond != null && _key.Equals(cond._key);
}
}
/// <summary>
/// Holds a term and all its rules and possible assignments that aren't constant
/// </summary>
public class Domain
{
public Domain(Term name)
{
_name = name;
}
public readonly Assignments Assignments = new Assignments();
public readonly List<Index> Indices = new List<Index>();
public readonly HashSet<RuleReference> RuleRefs = new HashSet<RuleReference>();
private readonly Term _name;
public override String ToString()
{
return "\nName: " + _name + "\nvalues: " + Assignments;//+"\nruleRefs: "+ruleRefs;
}
/// <summary>
/// First index all the term objects in all the assignments
/// Then remove any conditiions from Rules that contain constant terms
/// </summary>
public void BuildIndices()
{
foreach (Assignment assignment in Assignments)
AddAssignmentToIndex(assignment);
RemoveConstantConditions(RuleRefs);
}
/// <summary>
/// For each term object in the assignment sure add a mapping (in Indicies) from that term object to this assignment
/// </summary>
/// <param name="assignment"></param>
public void AddAssignmentToIndex(Assignment assignment)
{
for (int i = 0; i < assignment.Count; i++)
{
TermObject c = assignment[i];
if (Indices.Count <= i)
Indices.Add(new Index());
Index index = Indices[i];
if (!index.ContainsKey(c))
index[c] = new Assignments();
Assignments val = index[c];
val.Add(assignment);
}
}
}
private static readonly TermVariable FillerVar = new TermVariable(GameContainer.SymbolTable["?#*#"]);
readonly Dictionary<Term, Domain> _domains = new Dictionary<Term, Domain>();
private readonly List<RuleReference> _extraRefs = new List<RuleReference>();
public PropNetFlattener(List<Expression> description)
{
_description = description;
}
public List<Implication> Flatten()
{
//Find universe and initial domains
foreach (Expression gdl in _description)
InitializeDomains(gdl);
foreach (Domain d in _domains.Values)
d.BuildIndices();
//Compute the actual domains of everything
UpdateDomains();
return GetAllInstantiations();
}
private List<Implication> GetAllInstantiations()
{
List<Implication> rval = (from relation in _description.OfType<Fact>()
where !GameContainer.SymbolTable[relation.RelationName].Equals("base")
select new Implication(relation)).ToList();
foreach (Domain d in _domains.Values)
foreach (RuleReference r in d.RuleRefs)
foreach (TermObjectSubstitution varInstantiation in FindSatisfyingInstantiations(r))
{
if (varInstantiation.IsMappedTo(null))
throw new Exception("Shouldn't instantiate anything to null.");
rval.Add((Implication) r.OriginalRule.ApplySubstitution(varInstantiation));
if (rval.Last().ToString().Contains("null"))
throw new Exception("Shouldn't instantiate anything to null: " + rval.Last());
}
RemoveConstantConditions(_extraRefs);
foreach (RuleReference r in _extraRefs)
{
var varInstantiations = FindSatisfyingInstantiations(r);
foreach (TermObjectSubstitution varInstantiation in varInstantiations)
{
if (varInstantiation.IsMappedTo(null))
throw new Exception("Shouldn't instantiate anything to null.");
rval.Add((Implication)r.OriginalRule.ApplySubstitution(varInstantiation));
if (rval.Last().ToString().Contains("null"))
throw new Exception("Shouldn't instantiate anything to null.");
}
if (!varInstantiations.Any())
rval.Add((Implication)r.OriginalRule.ApplySubstitution(new TermObjectSubstitution()));
}
return rval;
}
private static void RemoveConstantConditions(ICollection<RuleReference> ruleRefs)
{
foreach (RuleReference ruleRef in ruleRefs.ToImmutableList())
{
var newConditions = new List<Condition>();
foreach (Condition c in ruleRef.Conditions)
{
if (c.Dom == null)
c.UpdateDom();
if (c.Dom != null)
newConditions.Add(c);
}
if (newConditions.Count != ruleRef.Conditions.Count)
{
ruleRefs.Remove(ruleRef);
ruleRefs.Add(new RuleReference(ruleRef.OriginalRule, newConditions, ruleRef.ProductionTemplate));
}
}
}
/// <summary>
/// Go through each expression, if it is a fact find what constants it is using and create assignments for them;
/// for implications find the constants and variables used in the head (if any) and add each of expressions in the body as conditions
/// This is the precursor step for resolving the domains
/// </summary>
/// <param name="gdl"></param>
void InitializeDomains(Expression gdl)
{
var relation = gdl as Fact;
var rule = gdl as Implication;
if (relation != null)
{
String name = GameContainer.SymbolTable[relation.RelationName];
if (!name.Equals("base"))
{
Term term = relation.ToTerm();
Term generified = FindGenericForm(term);
Assignment instantiation = GetConstantList(term);
if (!_domains.ContainsKey(generified))
_domains[generified] = new Domain(generified);
_domains[generified].Assignments.Add(instantiation);
}
}
else if (rule != null)
{
Fact head = rule.Consequent;
List<Term> productionTemplate = null;
ICollection<RuleReference> rules= _extraRefs;
if (head.Arity > 0)
{
Term term = head.ToTerm();
Term generified = FindGenericForm(term);
if (!_domains.ContainsKey(generified))
_domains[generified] = new Domain(generified);
Domain dom = _domains[generified];
productionTemplate = GetConstantAndVariableList(term);
rules = dom.RuleRefs;
}
IEnumerable<List<Expression>> newRHSs = DeORer.DeOr(rule.Antecedents.Conjuncts.ToList());
foreach (List<Expression> rhs in newRHSs)
{
IEnumerable<Condition> conditions = rhs.OfType<Fact>().Select(fact => new Condition(fact.ToTerm(), this));
var ruleRef = new RuleReference(new Implication(head, rhs.ToArray()), conditions, productionTemplate);
rules.Add(ruleRef);
}
}
}
/// <summary>
/// Returns all constants that are using in the term and any term functions contained within it
/// </summary>
private static Assignment GetConstantList(Term term)
{
var termObject = term as TermObject;
var rval = new Assignment();
if (termObject != null)
rval.Add(termObject);
else if (term is TermVariable)
throw new Exception("Called getConstantList on something containing a variable.");
else
rval.AddRange(((TermFunction)term).Arguments.SelectMany(GetConstantList));
return rval;
}
/// <summary>
/// Returns all constants and variables that are using in the term and any term functions contained within it
/// </summary>
private static List<Term> GetConstantAndVariableList(Term term)
{
var rval = new List<Term>();
if (term is TermObject)
{
rval.Add(term);
return rval;
}
if (term is TermVariable)
{
rval.Add(term);
return rval;
}
var func = (TermFunction)term;
rval.AddRange(func.Arguments.SelectMany(GetConstantAndVariableList));
return rval;
}
/// <summary>
/// Returns a generic form of the term where all constants and variables have been replaced by a generic variable
/// </summary>
private static Term FindGenericForm(Term term)
{
if (term is TermObject)
return FillerVar;
if (term is TermVariable)
return FillerVar;
var func = (TermFunction)term;
Term[] newBody = func.Arguments.Select(FindGenericForm).ToArray();
int name = func.FunctionName;
if (name == GameContainer.Parser.TokLegal)
name = GameContainer.Parser.TokDoes;
else if (name == GameContainer.Parser.TokNext)
name = GameContainer.Parser.TokTrue;
else if (name == GameContainer.Parser.TokInit)
name = GameContainer.Parser.TokTrue;
return new TermFunction(name, newBody);
}
void UpdateDomains()
{
bool changedSomething = true;
int itrNum = 0;
var lastUpdatedDomains = new HashSet<Domain>(_domains.Values);
while (changedSomething)
{
Logger.Info("StateMachine", "Beginning domain finding iteration: " + itrNum);
var currUpdatedDomains = new HashSet<Domain>();
changedSomething = false;
int rulesConsidered = 0;
foreach (Domain d in _domains.Values)
{
foreach (RuleReference ruleRef in d.RuleRefs)
{
if (!ruleRef.Conditions.Any(c => lastUpdatedDomains.Contains(c.Dom)))
continue;
rulesConsidered++;
HashSet<TermObjectSubstitution> instantiations = FindSatisfyingInstantiations(ruleRef);
foreach (TermObjectSubstitution instantiation in instantiations)
{
var a = new Assignment();
foreach (Term t in ruleRef.ProductionTemplate)
{
var term = t as TermObject;
if (term != null)
a.Add(term);
else
{
var var = (TermVariable)t;
a.Add((TermObject)instantiation.GetMapping(var));
}
}
if (!d.Assignments.Contains(a))
{
currUpdatedDomains.Add(d);
d.Assignments.Add(a);
changedSomething = true;
d.AddAssignmentToIndex(a);
}
}
if (!instantiations.Any())
{ //There might just be no variables in the rule
var a = new Assignment();
//FindSatisfyingInstantiations(ruleRef); //just for debugging
bool isVar = false;
foreach (Term t in ruleRef.ProductionTemplate)
{
var term = t as TermObject;
if (term != null)
a.Add(term);
else
{
//There's a variable and we didn't find an instantiation
isVar = true;
break;
}
}
if (!isVar && !d.Assignments.Contains(a))
{
currUpdatedDomains.Add(d);
d.Assignments.Add(a);
changedSomething = true;
d.AddAssignmentToIndex(a);
}
}
}
}
itrNum++;
lastUpdatedDomains = currUpdatedDomains;
Logger.Info("\tDone with iteration. Considered " + rulesConsidered + " rules.");
}
}
private static HashSet<TermObjectSubstitution> FindSatisfyingInstantiations(RuleReference ruleRef)
{
return FindSatisfyingInstantiations(ruleRef.Conditions, 0, new TermObjectSubstitution());
}
private static HashSet<TermObjectSubstitution> FindSatisfyingInstantiations(IList<Condition> conditions, int idx, TermObjectSubstitution instantiation)
{
var rval = new HashSet<TermObjectSubstitution>();
if (idx == conditions.Count)
{
rval.Add(instantiation);
return rval;
}
Condition cond = conditions[idx];
Domain dom = cond.Dom;
Assignments assignments = null;
for (int i = 0; i < cond.Template.Count; i++)
{
Term t = cond.Template[i];
TermObject c = null;
var v = t as TermVariable;
var obj = t as TermObject;
if (v != null)
c = (TermObject)instantiation.GetMapping(v);
else if (obj != null)
c = obj;
if (c != null)
{
if (assignments == null)
{
assignments = new Assignments();
if (dom.Indices.Count > i) //if this doesn't hold it is because there are no assignments and the indices haven't been set up yet
{
Index index = dom.Indices[i];
if (index.ContainsKey(c)) //Might be no assignment which satisfies this condition
index[c].ToList().ForEach(idxc => assignments.Add(idxc));
}
}
else
{
if (dom.Indices.Count > i)
{
Index index = dom.Indices[i];
if (index.ContainsKey(c)) //Might be no assignment which satisfies this condition
assignments.RemoveWhere(r => !index[c].Contains(r));
}
else //This is when we've tried to find an assignment for a form that doesn't have any assignments yet. Pretend it returned an empty set
assignments.Clear();
}
}
}
if (assignments == null) //case where there are no constants to be consistent with
assignments = dom.Assignments;
foreach (Assignment a in assignments)
{
var newInstantiation = new TermObjectSubstitution().Copy(instantiation);
for (int i = 0; i < a.Count; i++)
{
var var = cond.Template[i] as TermVariable;
if (var != null)
{
Term mapping = instantiation.GetMapping(var);
if (mapping == null)
newInstantiation.AddMapping(var, a[i]);
}
}
FindSatisfyingInstantiations(conditions, idx + 1, newInstantiation).ToList().ForEach(f => rval.Add(f));
}
return rval;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI.WebControls;
using Cuyahoga.Core.DataAccess;
using Cuyahoga.Core.Domain;
using Cuyahoga.Core.Service;
using Cuyahoga.Core.Service.Membership;
using Cuyahoga.Core.Service.SiteStructure;
using Cuyahoga.Core.Util;
using Cuyahoga.Web.Components;
using Cuyahoga.Web.UI;
using Cuyahoga.Web.Util;
namespace Cuyahoga.Web.Install
{
/// <summary>
/// Summary description for Install.
/// </summary>
public class Install : CuyahogaPage
{
private ICommonDao _commonDao;
private ISiteService _siteService;
private ModuleLoader _moduleLoader;
protected Panel pnlErrors;
protected Panel pnlIntro;
protected Panel pnlAdmin;
protected Panel pnlModules;
protected HyperLink hplContinue;
protected Label lblError;
protected Button btnInstallDatabase;
protected TextBox txtPassword;
protected Button btnAdmin;
protected RequiredFieldValidator rfvPassword;
protected Label lblCoreAssembly;
protected Label lblModulesAssembly;
protected TextBox txtConfirmPassword;
protected CompareValidator cpvPassword;
protected RequiredFieldValidator rfvConfirmPassword;
protected Label lblMessage;
protected Panel pnlMessage;
protected Panel pnlCreateSite;
protected Button btnCreateSite;
protected Button btnSkipCreateSite;
protected Panel pnlFinished;
protected Repeater rptModules;
/// <summary>
/// Constructor.
/// </summary>
public Install()
{
this._commonDao = IoC.Resolve<ICommonDao>();
this._siteService = IoC.Resolve<ISiteService>();
this._moduleLoader = IoC.Resolve<ModuleLoader>();
}
private void Page_Load(object sender, EventArgs e)
{
this.pnlErrors.Visible = false;
if (! this.IsPostBack)
{
try
{
// Check installable state. Check both Cuyahoga.Core and Cuyahoga.Modules.
bool canInstall = false;
// Core
DatabaseInstaller dbInstaller = new DatabaseInstaller(Server.MapPath("~/Install/Core"), Assembly.Load("Cuyahoga.Core"));
if (dbInstaller.CanInstall)
{
lblCoreAssembly.Text = "Cuyahoga Core " + dbInstaller.NewAssemblyVersion.ToString(3);
// Core modules
DatabaseInstaller moduleDbInstaller = new DatabaseInstaller(Server.MapPath("~/Install/Modules"), Assembly.Load("Cuyahoga.Modules"));
if (moduleDbInstaller.CanInstall)
{
canInstall = true;
lblModulesAssembly.Text = "Cuyahoga Core Modules " + moduleDbInstaller.NewAssemblyVersion.ToString(3);
}
}
if (canInstall)
{
this.pnlIntro.Visible = true;
}
else
{
// Check if we perhaps need to add an admin
if (this._commonDao.GetAll(typeof(User)).Count == 0)
{
this.pnlAdmin.Visible = true;
}
else
{
ShowError("Can't install Cuyahoga. Check if the install.sql file exists in the /Install/Core|Modules/Database/DATABASE_TYPE/ directory and that there isn't already a version installed.");
}
}
}
catch (Exception ex)
{
ShowError("An error occured: <br/><br/>" + ex.ToString());
}
}
}
private void BindOptionalModules()
{
// Retrieve the modules that are already installed.
IList availableModules = this._commonDao.GetAll(typeof(ModuleType), "Name");
// Retrieve the available modules from the filesystem.
string moduleRootDir = HttpContext.Current.Server.MapPath("~/Modules");
DirectoryInfo[] moduleDirectories = new DirectoryInfo(moduleRootDir).GetDirectories();
// Go through the directories and add the modules that can be installed
ArrayList installableModules = new ArrayList();
foreach (DirectoryInfo di in moduleDirectories)
{
// Skip hidden directories.
bool shouldAdd = (di.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden;
foreach (ModuleType moduleType in availableModules)
{
if (moduleType.Name == di.Name)
{
shouldAdd = false;
break;
}
}
if (shouldAdd)
{
// Check if the module can be installed
DatabaseInstaller moduleInstaller = new DatabaseInstaller(Path.Combine(Server.MapPath("~/Modules/" + di.Name), "Install"), null);
if (moduleInstaller.CanInstall)
{
installableModules.Add(di.Name);
}
}
}
this.rptModules.DataSource = installableModules;
this.rptModules.DataBind();
}
private void InstallOptionalModules()
{
foreach (RepeaterItem ri in this.rptModules.Items)
{
CheckBox chkInstall = ri.FindControl("chkInstall") as CheckBox;
if (chkInstall != null && chkInstall.Checked)
{
Literal litModuleName = (Literal) ri.FindControl("litModuleName");
string moduleName = litModuleName.Text;
DatabaseInstaller moduleInstaller = new DatabaseInstaller(Path.Combine(Server.MapPath("~/Modules/" + moduleName), "Install"), null);
moduleInstaller.Install();
}
}
}
private void ShowError(string message)
{
this.lblError.Text = message;
this.pnlErrors.Visible = true;
this.pnlMessage.Visible = false;
}
private void ShowMessage(string message)
{
this.lblMessage.Text = message;
this.pnlMessage.Visible = true;
this.pnlErrors.Visible = false;
}
private void FinishInstall()
{
//upon first install, the registration (on app startup) will have no effect,
//so make sure this happens after installation
this._moduleLoader.RegisterActivatedModules();
}
#region Site creation code
private void CreateSite()
{
Role defaultAuthenticatedRole = this._commonDao.GetObjectByDescription(typeof(Role), "Name", "Authenticated user") as Role;
// Site
Site site = new Site();
site.Name = "Cuyahoga Sample Site";
site.SiteUrl = UrlHelper.GetSiteUrl();
site.WebmasterEmail = "[email protected]";
site.UseFriendlyUrls = true;
site.DefaultCulture = "en-US";
site.DefaultPlaceholder = "maincontent";
site.DefaultRole = defaultAuthenticatedRole;
string systemTemplatePath = Server.MapPath(Config.GetConfiguration()["TemplateDir"]);
this._siteService.CreateSite(site, Server.MapPath("~/SiteData"), this._commonDao.GetAll<Template>(), systemTemplatePath);
// Template
Template defaultTemplate =
this._commonDao.GetAll<Template>().Where(t => t.Site == site && t.BasePath == "Templates/AnotherRed").Single();
site.DefaultTemplate = defaultTemplate;
this._commonDao.UpdateObject(site);
// Root node
Node rootNode = new Node();
rootNode.Culture = site.DefaultCulture;
rootNode.Position = 0;
rootNode.ShortDescription = "home";
rootNode.ShowInNavigation = true;
rootNode.Site = site;
rootNode.Template = defaultTemplate;
rootNode.Title = "Home";
IList allRoles = this._commonDao.GetAll(typeof(Role));
foreach (Role role in allRoles)
{
NodePermission np = new NodePermission();
np.Node = rootNode;
np.Role = role;
np.ViewAllowed = true;
np.EditAllowed = role.HasRight(Rights.Administrator);
rootNode.NodePermissions.Add(np);
}
this._commonDao.SaveOrUpdateObject(rootNode);
// Sections on root Node
Section loginSection = new Section();
loginSection.Site = site;
loginSection.ModuleType = this._commonDao.GetObjectByDescription(typeof(ModuleType), "Name", "User") as ModuleType;
loginSection.Title = "Login";
loginSection.CacheDuration = 0;
loginSection.Node = rootNode;
loginSection.PlaceholderId = "side1content";
loginSection.Position = 0;
loginSection.ShowTitle = true;
loginSection.Settings.Add("SHOW_EDIT_PROFILE", "True");
loginSection.Settings.Add("SHOW_RESET_PASSWORD", "True");
loginSection.Settings.Add("SHOW_REGISTER", "True");
loginSection.CopyRolesFromNode();
rootNode.Sections.Add(loginSection);
this._commonDao.SaveOrUpdateObject(loginSection);
Section introSection = new Section();
introSection.Site = site;
introSection.ModuleType = this._commonDao.GetObjectByDescription(typeof(ModuleType), "Name", "StaticHtml") as ModuleType;
introSection.Title = "Welcome";
introSection.CacheDuration = 0;
introSection.Node = rootNode;
introSection.PlaceholderId = "maincontent";
introSection.Position = 0;
introSection.ShowTitle = true;
introSection.CopyRolesFromNode();
rootNode.Sections.Add(introSection);
this._commonDao.SaveOrUpdateObject(introSection);
// Pages
Node page1 = new Node();
page1.Culture = site.DefaultCulture;
page1.Position = 0;
page1.ShortDescription = "page1";
page1.ShowInNavigation = true;
page1.Site = site;
page1.Template = defaultTemplate;
page1.Title = "Articles";
page1.ParentNode = rootNode;
page1.CopyRolesFromParent();
this._commonDao.SaveOrUpdateObject(page1);
ModuleType articlesModuleType = this._commonDao.GetObjectByDescription(typeof(ModuleType), "Name", "Articles") as ModuleType;
// Check if the articles module is installed
if (articlesModuleType != null)
{
Section articleSection = new Section();
articleSection.Site = site;
articleSection.ModuleType = articlesModuleType;
articleSection.Title = "Articles";
articleSection.CacheDuration = 0;
articleSection.Node = page1;
articleSection.PlaceholderId = "maincontent";
articleSection.Position = 0;
articleSection.ShowTitle = true;
articleSection.Settings.Add("DISPLAY_TYPE", "FullContent");
articleSection.Settings.Add("ALLOW_ANONYMOUS_COMMENTS", "True");
articleSection.Settings.Add("ALLOW_COMMENTS", "True");
articleSection.Settings.Add("SORT_BY", "DateOnline");
articleSection.Settings.Add("SORT_DIRECTION", "DESC");
articleSection.Settings.Add("ALLOW_SYNDICATION", "True");
articleSection.Settings.Add("NUMBER_OF_ARTICLES_IN_LIST", "5");
articleSection.CopyRolesFromNode();
page1.Sections.Add(articleSection);
this._commonDao.SaveOrUpdateObject(articleSection);
}
Node page2 = new Node();
page2.Culture = site.DefaultCulture;
page2.Position = 1;
page2.ShortDescription = "page2";
page2.ShowInNavigation = true;
page2.Site = site;
page2.Template = defaultTemplate;
page2.Title = "Page 2";
page2.ParentNode = rootNode;
page2.CopyRolesFromParent();
this._commonDao.SaveOrUpdateObject(page2);
Section page2Section = new Section();
page2Section.Site = site;
page2Section.ModuleType = this._commonDao.GetObjectByDescription(typeof(ModuleType), "Name", "StaticHtml") as ModuleType;
page2Section.Title = "Page 2";
page2Section.CacheDuration = 0;
page2Section.Node = page2;
page2Section.PlaceholderId = "maincontent";
page2Section.Position = 0;
page2Section.ShowTitle = true;
page2Section.CopyRolesFromNode();
rootNode.Sections.Add(page2Section);
this._commonDao.SaveOrUpdateObject(page2Section);
// User Profile node
Node userProfileNode = new Node();
userProfileNode.Culture = site.DefaultCulture;
userProfileNode.Position = 2;
userProfileNode.ShortDescription = "userprofile";
userProfileNode.ShowInNavigation = false;
userProfileNode.Site = site;
userProfileNode.Template = defaultTemplate;
userProfileNode.Title = "User Profile";
userProfileNode.ParentNode = rootNode;
userProfileNode.CopyRolesFromParent();
this._commonDao.SaveOrUpdateObject(userProfileNode);
Section userProfileSection = new Section();
userProfileSection.Site = site;
userProfileSection.ModuleType = this._commonDao.GetObjectByDescription(typeof(ModuleType), "Name", "UserProfile") as ModuleType;
userProfileSection.Title = "User Profile";
userProfileSection.CacheDuration = 0;
userProfileSection.Node = userProfileNode;
userProfileSection.PlaceholderId = "maincontent";
userProfileSection.Position = 0;
userProfileSection.ShowTitle = false;
userProfileSection.CopyRolesFromNode();
userProfileNode.Sections.Add(userProfileSection);
this._commonDao.SaveOrUpdateObject(userProfileSection);
// Connections from Login to User Profile
loginSection.Connections.Add("Register", userProfileSection);
loginSection.Connections.Add("ResetPassword", userProfileSection);
loginSection.Connections.Add("ViewProfile", userProfileSection);
loginSection.Connections.Add("EditProfile", userProfileSection);
this._commonDao.SaveOrUpdateObject(loginSection);
}
private void RemoveInstallLock()
{
HttpContext.Current.Application.Lock();
HttpContext.Current.Application["IsInstalling"] = false;
HttpContext.Current.Application.UnLock();
}
#endregion
#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()
{
this.btnInstallDatabase.Click += new System.EventHandler(this.btnInstallDatabase_Click);
this.btnAdmin.Click += new System.EventHandler(this.btnAdmin_Click);
this.btnCreateSite.Click += new System.EventHandler(this.btnCreateSite_Click);
this.btnSkipCreateSite.Click += new System.EventHandler(this.btnSkipCreateSite_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btnInstallDatabase_Click(object sender, EventArgs e)
{
DatabaseInstaller dbInstaller = new DatabaseInstaller(Server.MapPath("~/Install/Core"), Assembly.Load("Cuyahoga.Core"));
DatabaseInstaller modulesDbInstaller = new DatabaseInstaller(Server.MapPath("~/Install/Modules"), Assembly.Load("Cuyahoga.Modules"));
try
{
dbInstaller.Install();
modulesDbInstaller.Install();
this.pnlIntro.Visible = false;
this.pnlModules.Visible = true;
BindOptionalModules();
ShowMessage("Database tables successfully created.");
}
catch (Exception ex)
{
ShowError("An error occured while installing the database tables: <br/>" + ex.ToString());
}
}
protected void btnInstallModules_Click(object sender, EventArgs e)
{
try
{
InstallOptionalModules();
this.pnlModules.Visible = false;
this.pnlAdmin.Visible = true;
}
catch (Exception ex)
{
ShowError("An error occured while installing additional modules: <br/>" + ex.ToString());
}
}
protected void btnSkipInstallModules_Click(object sender, EventArgs e)
{
this.pnlModules.Visible = false;
this.pnlAdmin.Visible = true;
}
private void btnAdmin_Click(object sender, EventArgs e)
{
if (this.IsValid)
{
// Only create an admin if there are really NO users.
if (this._commonDao.GetAll(typeof(User)).Count > 0)
{
ShowError("There is already a user in the database. For security reasons Cuyahoga won't add a new user!");
}
else
{
User newAdmin = new User();
newAdmin.UserName = "admin";
newAdmin.Email = "[email protected]";
newAdmin.Password = Core.Domain.User.HashPassword(this.txtPassword.Text);
newAdmin.IsActive = true;
newAdmin.TimeZone = 0;
try
{
Role adminRole = (Role)this._commonDao.GetObjectById(typeof(Role), 1);
newAdmin.Roles.Add(adminRole);
this._commonDao.SaveOrUpdateObject(newAdmin);
this.pnlAdmin.Visible = false;
this.pnlCreateSite.Visible = true;
}
catch (Exception ex)
{
ShowError("An error occured while creating the administrator: <br/>" + ex.ToString());
}
}
}
}
private void btnCreateSite_Click(object sender, EventArgs e)
{
try
{
CreateSite();
//at the moment, this is the last step of the installation, so
//call the finishing routine here
this.FinishInstall();
this.pnlCreateSite.Visible = false;
this.pnlFinished.Visible = true;
RemoveInstallLock();
}
catch (Exception ex)
{
ShowError("An error occured while creating the site: <br/>" + ex.ToString());
}
}
private void btnSkipCreateSite_Click(object sender, EventArgs e)
{
//at the moment, this is the last step of the installation, so
//call the finishing routine here
this.FinishInstall();
this.pnlCreateSite.Visible = false;
this.pnlFinished.Visible = true;
RemoveInstallLock();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Globalization;
using System.Collections.Generic;
using System.Configuration.Assemblies;
using System.Runtime.Serialization;
using System.Security;
using Internal.Reflection.Augments;
namespace System.Reflection
{
public abstract class Assembly : ICustomAttributeProvider, ISerializable
{
protected Assembly() { }
public virtual IEnumerable<TypeInfo> DefinedTypes
{
get
{
Type[] types = GetTypes();
TypeInfo[] typeinfos = new TypeInfo[types.Length];
for (int i = 0; i < types.Length; i++)
{
TypeInfo typeinfo = types[i].GetTypeInfo();
if (typeinfo == null)
throw new NotSupportedException(SR.NotSupported_NoTypeInfo);
typeinfos[i] = typeinfo;
}
return typeinfos;
}
}
public virtual Type[] GetTypes()
{
Module[] m = GetModules(false);
int finalLength = 0;
Type[][] moduleTypes = new Type[m.Length][];
for (int i = 0; i < moduleTypes.Length; i++)
{
moduleTypes[i] = m[i].GetTypes();
finalLength += moduleTypes[i].Length;
}
int current = 0;
Type[] ret = new Type[finalLength];
for (int i = 0; i < moduleTypes.Length; i++)
{
int length = moduleTypes[i].Length;
Array.Copy(moduleTypes[i], 0, ret, current, length);
current += length;
}
return ret;
}
public virtual IEnumerable<Type> ExportedTypes => GetExportedTypes();
public virtual Type[] GetExportedTypes() { throw NotImplemented.ByDesign; }
public virtual string CodeBase { get { throw NotImplemented.ByDesign; } }
public virtual MethodInfo EntryPoint { get { throw NotImplemented.ByDesign; } }
public virtual string FullName { get { throw NotImplemented.ByDesign; } }
public virtual string ImageRuntimeVersion { get { throw NotImplemented.ByDesign; } }
public virtual bool IsDynamic => false;
public virtual string Location { get { throw NotImplemented.ByDesign; } }
public virtual bool ReflectionOnly { get { throw NotImplemented.ByDesign; } }
public virtual ManifestResourceInfo GetManifestResourceInfo(string resourceName) { throw NotImplemented.ByDesign; }
public virtual string[] GetManifestResourceNames() { throw NotImplemented.ByDesign; }
public virtual Stream GetManifestResourceStream(string name) { throw NotImplemented.ByDesign; }
public virtual Stream GetManifestResourceStream(Type type, string name) { throw NotImplemented.ByDesign; }
public bool IsFullyTrusted => true;
public virtual AssemblyName GetName() => GetName(copiedName: false);
public virtual AssemblyName GetName(bool copiedName) { throw NotImplemented.ByDesign; }
public virtual Type GetType(string name) => GetType(name, throwOnError: false, ignoreCase: false);
public virtual Type GetType(string name, bool throwOnError) => GetType(name, throwOnError: throwOnError, ignoreCase: false);
public virtual Type GetType(string name, bool throwOnError, bool ignoreCase) { throw NotImplemented.ByDesign; }
public virtual bool IsDefined(Type attributeType, bool inherit) { throw NotImplemented.ByDesign; }
public virtual IEnumerable<CustomAttributeData> CustomAttributes => GetCustomAttributesData();
public virtual IList<CustomAttributeData> GetCustomAttributesData() { throw NotImplemented.ByDesign; }
public virtual object[] GetCustomAttributes(bool inherit) { throw NotImplemented.ByDesign; }
public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) { throw NotImplemented.ByDesign; }
public virtual String EscapedCodeBase => AssemblyName.EscapeCodeBase(CodeBase);
public object CreateInstance(string typeName) => CreateInstance(typeName, false, BindingFlags.Public | BindingFlags.Instance, binder: null, args: null, culture: null, activationAttributes: null);
public object CreateInstance(string typeName, bool ignoreCase) => CreateInstance(typeName, ignoreCase, BindingFlags.Public | BindingFlags.Instance, binder: null, args: null, culture: null, activationAttributes: null);
public virtual object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
{
Type t = GetType(typeName, throwOnError: false, ignoreCase: ignoreCase);
if (t == null)
return null;
return Activator.CreateInstance(t, bindingAttr, binder, args, culture, activationAttributes);
}
public virtual event ModuleResolveEventHandler ModuleResolve { add { throw NotImplemented.ByDesign; } remove { throw NotImplemented.ByDesign; } }
public virtual Module ManifestModule { get { throw NotImplemented.ByDesign; } }
public virtual Module GetModule(string name) { throw NotImplemented.ByDesign; }
public Module[] GetModules() => GetModules(getResourceModules: false);
public virtual Module[] GetModules(bool getResourceModules) { throw NotImplemented.ByDesign; }
public virtual IEnumerable<Module> Modules => GetLoadedModules(getResourceModules: true);
public Module[] GetLoadedModules() => GetLoadedModules(getResourceModules: false);
public virtual Module[] GetLoadedModules(bool getResourceModules) { throw NotImplemented.ByDesign; }
public virtual AssemblyName[] GetReferencedAssemblies() { throw NotImplemented.ByDesign; }
public virtual Assembly GetSatelliteAssembly(CultureInfo culture) { throw NotImplemented.ByDesign; }
public virtual Assembly GetSatelliteAssembly(CultureInfo culture, Version version) { throw NotImplemented.ByDesign; }
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw NotImplemented.ByDesign; }
public override string ToString()
{
string displayName = FullName;
if (displayName == null)
return base.ToString();
else
return displayName;
}
/*
Returns true if the assembly was loaded from the global assembly cache.
*/
public virtual bool GlobalAssemblyCache { get { throw NotImplemented.ByDesign; } }
public virtual Int64 HostContext { get { throw NotImplemented.ByDesign; } }
public override bool Equals(object o) => base.Equals(o);
public override int GetHashCode() => base.GetHashCode();
public static bool operator ==(Assembly left, Assembly right)
{
if (object.ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null)
return false;
return left.Equals(right);
}
public static bool operator !=(Assembly left, Assembly right)
{
return !(left == right);
}
public static string CreateQualifiedName(string assemblyName, string typeName) => typeName + ", " + assemblyName;
public static Assembly GetAssembly(Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
Module m = type.Module;
if (m == null)
return null;
else
return m.Assembly;
}
public static Assembly GetEntryAssembly() => Internal.Runtime.CompilerHelpers.StartupCodeHelpers.GetEntryAssembly();
public static Assembly GetExecutingAssembly() { throw new NotImplementedException(); }
public static Assembly GetCallingAssembly() { throw new NotImplementedException(); }
public static Assembly Load(AssemblyName assemblyRef) => ReflectionAugments.ReflectionCoreCallbacks.Load(assemblyRef);
public static Assembly Load(byte[] rawAssembly) => Load(rawAssembly, rawSymbolStore: null);
public static Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore) => ReflectionAugments.ReflectionCoreCallbacks.Load(rawAssembly, rawSymbolStore);
public static Assembly Load(string assemblyString)
{
if (assemblyString == null)
throw new ArgumentNullException(nameof(assemblyString));
AssemblyName name = new AssemblyName(assemblyString);
return Load(name);
}
public static Assembly LoadFile(String path) { throw new PlatformNotSupportedException(); }
public static Assembly LoadFrom(String assemblyFile) { throw new PlatformNotSupportedException(); }
public static Assembly LoadFrom(String assemblyFile, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm) { throw new PlatformNotSupportedException(); }
[Obsolete("This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static Assembly LoadWithPartialName(String partialName)
{
if (partialName == null)
throw new ArgumentNullException(nameof(partialName));
return Load(partialName);
}
public static Assembly UnsafeLoadFrom(string assemblyFile) => LoadFrom(assemblyFile);
public Module LoadModule(String moduleName, byte[] rawModule) => LoadModule(moduleName, rawModule, null);
public virtual Module LoadModule(String moduleName, byte[] rawModule, byte[] rawSymbolStore) { throw NotImplemented.ByDesign; }
public static Assembly ReflectionOnlyLoad(byte[] rawAssembly) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); }
public static Assembly ReflectionOnlyLoad(string assemblyString) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); }
public static Assembly ReflectionOnlyLoadFrom(string assemblyFile) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); }
public virtual SecurityRuleSet SecurityRuleSet => SecurityRuleSet.None;
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Iis6VirtualDirectory.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Web
{
using System;
using System.DirectoryServices;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Build.Framework;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>CheckExists</i> (<b>Required: </b> Website <b>Optional:</b> Name</para>
/// <para><i>Create</i> (<b>Required: </b> Website <b>Optional:</b> Name, Parent, RequireApplication, DirectoryType, AppPool, Properties)</para>
/// <para><i>Delete</i> (<b>Required: </b> Website <b>Optional:</b> Name, Parent</para>
/// <para><b>Remote Execution Support:</b> Yes. Please note that the machine you execute from must have IIS installed.</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <!-- Create an IIsWebVirtualDir at the ROOT of the website -->
/// <MSBuild.ExtensionPack.Web.Iis6VirtualDirectory TaskAction="Create" Website="awebsite" Properties="AccessRead=True;AccessWrite=False;AccessExecute=False;AccessScript=True;AccessSource=False;AspScriptErrorSentToBrowser=False;AspScriptErrorMessage=An error occurred on the server.;AspEnableApplicationRestart=False;DefaultDoc=SubmissionProtocol.aspx;DontLog=False;EnableDefaultDoc=True;HttpExpires=D, 0;HttpErrors=;Path=c:\Demo1;ScriptMaps=.htm,C:\Windows\System32\Inetsrv\Test.dll,5,GET, HEAD, POST"/>
/// <!-- Check if a virtual directory exists-->
/// <MSBuild.ExtensionPack.Web.Iis6VirtualDirectory TaskAction="CheckExists" Website="awebsite" Name="AVDir" >
/// <Output TaskParameter="Exists" PropertyName="CheckExists" />
/// </MSBuild.ExtensionPack.Web.Iis6VirtualDirectory>
/// <!-- Create another IIsWebVirtualDir -->
/// <MSBuild.ExtensionPack.Web.Iis6VirtualDirectory TaskAction="Create" Website="awebsite" Name="AVDir" Properties="Path=c:\Demo2"/>
/// <!-- Delete the IIsWebVirtualDir-->
/// <MSBuild.ExtensionPack.Web.Iis6VirtualDirectory TaskAction="Delete" Website="awebsite" Name="AVDir"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class Iis6VirtualDirectory : BaseTask, IDisposable
{
private const string CheckExistsTaskAction = "CheckExists";
private const string CreateTaskAction = "Create";
private const string DeleteTaskAction = "Delete";
private DirectoryEntry websiteEntry;
private string properties;
private string directoryType = "IIsWebVirtualDir";
private bool requireApplication = true;
private string appPool = "DefaultAppPool";
private string name = "ROOT";
private string parent = "/ROOT";
/// <summary>
/// Gets whether the Virtual Directory exists
/// </summary>
[Output]
public bool Exists { get; set; }
/// <summary>
/// Sets the Parent. Defaults to /ROOT
/// </summary>
public string Parent
{
get { return this.parent; }
set { this.parent = value; }
}
/// <summary>
/// Sets whether an Application is required. Defaults to true.
/// </summary>
public bool RequireApplication
{
get { return this.requireApplication; }
set { this.requireApplication = value; }
}
/// <summary>
/// Sets the DirectoryType. Supports IIsWebDirectory and IIsWebVirtualDir. Default is IIsWebVirtualDir.
/// </summary>
public string DirectoryType
{
get { return this.directoryType; }
set { this.directoryType = value; }
}
/// <summary>
/// Sets the AppPool to run in. Default is 'DefaultAppPool'
/// </summary>
public string AppPool
{
get { return this.appPool; }
set { this.appPool = value; }
}
/// <summary>
/// Sets the Properties. Use a semi-colon delimiter. See <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/cde669f1-5714-4159-af95-f334251c8cbd.mspx?mfr=true">Metabase Property Reference (IIS 6.0)</a>
/// If a property contains =, enter #~# as a special sequence which will be replaced with = during processing
/// </summary>
public string Properties
{
get { return System.Web.HttpUtility.HtmlDecode(this.properties); }
set { this.properties = value; }
}
/// <summary>
/// Sets the name of the Virtual Directory. Defaults to 'ROOT'
/// </summary>
public string Name
{
get { return this.name; }
set { this.name = value; }
}
/// <summary>
/// Sets the name of the Website to add the Virtual Directory to.
/// </summary>
[Required]
public string Website { get; set; }
internal string IisPath
{
get { return "IIS://" + this.MachineName + "/W3SVC"; }
}
internal string AppPoolsPath
{
get { return "IIS://" + this.MachineName + "/W3SVC/AppPools"; }
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.websiteEntry.Dispose();
}
}
protected override void InternalExecute()
{
switch (this.TaskAction)
{
case CheckExistsTaskAction:
this.CheckExists();
break;
case CreateTaskAction:
this.Create();
break;
case DeleteTaskAction:
this.Delete();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private static void UpdateMetaBaseProperty(DirectoryEntry entry, string metaBasePropertyName, string metaBaseProperty)
{
if (metaBaseProperty.IndexOf('|') == -1)
{
string propertyTypeName;
using (DirectoryEntry di = new DirectoryEntry(entry.SchemaEntry.Parent.Path + "/" + metaBasePropertyName))
{
propertyTypeName = (string)di.Properties["Syntax"].Value;
}
if (string.Compare(propertyTypeName, "binary", StringComparison.OrdinalIgnoreCase) == 0)
{
object[] metaBasePropertyBinaryFormat = new object[metaBaseProperty.Length / 2];
for (int i = 0; i < metaBasePropertyBinaryFormat.Length; i++)
{
metaBasePropertyBinaryFormat[i] = metaBaseProperty.Substring(i * 2, 2);
}
PropertyValueCollection propValues = entry.Properties[metaBasePropertyName];
propValues.Clear();
propValues.Add(metaBasePropertyBinaryFormat);
entry.CommitChanges();
}
else
{
if (string.Compare(metaBasePropertyName, "path", StringComparison.OrdinalIgnoreCase) == 0)
{
DirectoryInfo f = new DirectoryInfo(metaBaseProperty);
metaBaseProperty = f.FullName;
}
entry.Invoke("Put", metaBasePropertyName, metaBaseProperty);
entry.Invoke("SetInfo");
}
}
else
{
entry.Invoke("Put", metaBasePropertyName, string.Empty);
entry.Invoke("SetInfo");
string[] metabaseProperties = metaBaseProperty.Split('|');
foreach (string metabasePropertySplit in metabaseProperties)
{
entry.Properties[metaBasePropertyName].Add(metabasePropertySplit);
}
entry.CommitChanges();
}
}
private DirectoryEntry LoadWebService()
{
DirectoryEntry webService = new DirectoryEntry(this.IisPath);
if (webService == null)
{
throw new ApplicationException(string.Format(CultureInfo.CurrentUICulture, "Iis DirectoryServices Unavailable: {0}", this.IisPath));
}
return webService;
}
private DirectoryEntry LoadWebsite(string websiteName)
{
DirectoryEntry webService = null;
try
{
webService = this.LoadWebService();
DirectoryEntries webEntries = webService.Children;
foreach (DirectoryEntry webEntry in webEntries)
{
if (webEntry.SchemaClassName == "IIsWebServer")
{
if (string.Compare(websiteName, webEntry.Properties["ServerComment"][0].ToString(), StringComparison.CurrentCultureIgnoreCase) == 0)
{
return webEntry;
}
}
webEntry.Dispose();
}
return null;
}
finally
{
if (webService != null)
{
webService.Dispose();
}
}
}
private DirectoryEntry LoadVirtualRoot(string websiteName)
{
DirectoryEntry webService = null;
try
{
webService = this.LoadWebService();
DirectoryEntries webEntries = webService.Children;
foreach (DirectoryEntry webEntry in webEntries)
{
if (webEntry.SchemaClassName == "IIsWebServer")
{
if (string.Compare(webEntry.Properties["ServerComment"][0].ToString(), websiteName, StringComparison.CurrentCultureIgnoreCase) == 0)
{
int websiteIdentifier = int.Parse(webEntry.Name, CultureInfo.InvariantCulture);
string rootVdirPath = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/ROOT", this.IisPath, websiteIdentifier);
return new DirectoryEntry(rootVdirPath);
}
}
webEntry.Dispose();
}
return null;
}
finally
{
if (webService != null)
{
webService.Dispose();
}
}
}
private void CheckExists()
{
this.LogTaskMessage(MessageImportance.High, string.Format(CultureInfo.CurrentUICulture, "Checking if Virtual Directory: {0} exists under {1}", this.Name, this.Website));
// Locate the website.
this.websiteEntry = this.LoadWebsite(this.Website);
if (this.websiteEntry == null)
{
this.Log.LogError(string.Format(CultureInfo.CurrentUICulture, "Website not found: {0}", this.Website));
return;
}
if (this.Name != "ROOT")
{
string parentPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", this.websiteEntry.Path, this.Parent);
this.websiteEntry = new DirectoryEntry(parentPath);
if (this.websiteEntry.Children.Cast<DirectoryEntry>().Any(vd => vd.Name == this.Name))
{
this.Exists = true;
}
}
}
private void Delete()
{
this.LogTaskMessage(MessageImportance.High, string.Format(CultureInfo.CurrentUICulture, "Deleting Virtual Directory: {0} under {1}", this.Name, this.Website));
// Locate the website.
this.websiteEntry = this.LoadWebsite(this.Website);
if (this.websiteEntry == null)
{
this.Log.LogError(string.Format(CultureInfo.CurrentUICulture, "Website not found: {0}", this.Website));
return;
}
if (this.Name != "ROOT")
{
string parentPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", this.websiteEntry.Path, this.Parent);
this.websiteEntry = new DirectoryEntry(parentPath);
}
this.websiteEntry.Invoke("Delete", new[] { "IIsWebVirtualDir", this.Name });
}
private void Create()
{
DirectoryEntry vdirEntry = null;
try
{
this.LogTaskMessage(MessageImportance.High, string.Format(CultureInfo.CurrentUICulture, "Creating Virtual Directory: {0} under {1}", this.Name, this.Website));
// Locate the website.
this.websiteEntry = this.LoadWebsite(this.Website);
if (this.websiteEntry == null)
{
this.Log.LogError(string.Format(CultureInfo.CurrentUICulture, "Website not found: {0}", this.Website));
return;
}
if (this.Name == "ROOT")
{
vdirEntry = this.LoadVirtualRoot(this.Website);
}
else
{
// Otherwise we create it.
string parentPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", this.websiteEntry.Path, this.Parent);
this.websiteEntry = new DirectoryEntry(parentPath);
try
{
vdirEntry = (DirectoryEntry)this.websiteEntry.Invoke("Create", this.DirectoryType, this.Name);
}
catch (TargetInvocationException ex)
{
Exception e = ex.InnerException;
COMException ce = (COMException)e;
if (ce != null)
{
// HRESULT 0x800700B7, "Cannot create a file when that file already exists. "
if (ce.ErrorCode == -2147024713)
{
// The child already exists, so let's get it.
string childPath = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", parentPath, this.Name);
vdirEntry = new DirectoryEntry(childPath);
}
else
{
throw;
}
}
else
{
throw;
}
}
this.websiteEntry.CommitChanges();
vdirEntry.CommitChanges();
UpdateMetaBaseProperty(vdirEntry, "AppFriendlyName", this.Name);
}
// Now loop through all the metabase properties specified.
if (string.IsNullOrEmpty(this.Properties) == false)
{
string[] propList = this.Properties.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in propList)
{
string[] propPair = s.Split(new[] { '=' });
string propName = propPair[0];
string propValue = propPair.Length > 1 ? propPair[1] : string.Empty;
// handle the special character sequence to insert '=' if property requires it
propValue = propValue.Replace("#~#", "=");
this.LogTaskMessage(string.Format(CultureInfo.CurrentUICulture, "\tAdding Property: {0}({1})", propName, propValue));
UpdateMetaBaseProperty(vdirEntry, propName, propValue);
}
}
vdirEntry.CommitChanges();
if (this.RequireApplication)
{
if (string.IsNullOrEmpty(this.AppPool))
{
vdirEntry.Invoke("AppCreate2", 1);
}
else
{
if (!DirectoryEntry.Exists(this.AppPoolsPath + @"/" + this.AppPool))
{
this.Log.LogError(string.Format(CultureInfo.CurrentUICulture, "AppPool not found: {0}", this.AppPool));
return;
}
vdirEntry.Invoke("AppCreate3", 1, this.AppPool, false);
}
}
else
{
vdirEntry.Invoke("AppDelete");
}
vdirEntry.CommitChanges();
}
finally
{
if (this.websiteEntry != null)
{
this.websiteEntry.Dispose();
}
if (vdirEntry != null)
{
vdirEntry.Dispose();
}
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using JetBrains.Annotations;
using osu.Framework.Extensions.ObjectExtensions;
using osu.Framework.Graphics.Containers;
using osu.Framework.Statistics;
namespace osu.Framework.Graphics.Performance
{
/// <summary>
/// Provides time-optimised updates for lifetime change notifications.
/// This is used in specialised <see cref="CompositeDrawable"/>s to optimise lifetime changes (see: <see cref="LifetimeManagementContainer"/>).
/// </summary>
/// <remarks>
/// The time complexity of updating lifetimes is O(number of alive items).
/// </remarks>
public class LifetimeEntryManager
{
/// <summary>
/// Invoked immediately when a <see cref="LifetimeEntry"/> becomes alive.
/// </summary>
public event Action<LifetimeEntry> EntryBecameAlive;
/// <summary>
/// Invoked immediately when a <see cref="LifetimeEntry"/> becomes dead.
/// </summary>
public event Action<LifetimeEntry> EntryBecameDead;
/// <summary>
/// Invoked when a <see cref="LifetimeEntry"/> crosses a lifetime boundary.
/// </summary>
public event Action<LifetimeEntry, LifetimeBoundaryKind, LifetimeBoundaryCrossingDirection> EntryCrossedBoundary;
/// <summary>
/// Contains all the newly-added (but not yet processed) entries.
/// </summary>
private readonly List<LifetimeEntry> newEntries = new List<LifetimeEntry>();
/// <summary>
/// Contains all the currently-alive entries.
/// </summary>
private readonly List<LifetimeEntry> activeEntries = new List<LifetimeEntry>();
/// <summary>
/// Contains all entries that should come alive in the future.
/// </summary>
private readonly SortedSet<LifetimeEntry> futureEntries = new SortedSet<LifetimeEntry>(new LifetimeStartComparator());
/// <summary>
/// Contains all entries that were alive in the past.
/// </summary>
private readonly SortedSet<LifetimeEntry> pastEntries = new SortedSet<LifetimeEntry>(new LifetimeEndComparator());
private readonly Queue<(LifetimeEntry, LifetimeBoundaryKind, LifetimeBoundaryCrossingDirection)> eventQueue =
new Queue<(LifetimeEntry, LifetimeBoundaryKind, LifetimeBoundaryCrossingDirection)>();
/// <summary>
/// Used to ensure a stable sort if multiple entries with the same lifetime are added.
/// </summary>
private ulong currentChildId;
/// <summary>
/// Adds an entry.
/// </summary>
/// <param name="entry">The <see cref="LifetimeEntry"/> to add.</param>
public void AddEntry(LifetimeEntry entry)
{
entry.RequestLifetimeUpdate += requestLifetimeUpdate;
entry.ChildId = ++currentChildId;
entry.State = LifetimeEntryState.New;
newEntries.Add(entry);
}
/// <summary>
/// Removes an entry.
/// </summary>
/// <param name="entry">The <see cref="LifetimeEntry"/> to remove.</param>
/// <returns>Whether <paramref name="entry"/> was contained by this <see cref="LifetimeEntryManager"/>.</returns>
public bool RemoveEntry(LifetimeEntry entry)
{
entry.RequestLifetimeUpdate -= requestLifetimeUpdate;
bool removed = false;
switch (entry.State)
{
case LifetimeEntryState.New:
removed = newEntries.Remove(entry);
break;
case LifetimeEntryState.Current:
removed = activeEntries.Remove(entry);
if (removed)
EntryBecameDead?.Invoke(entry);
break;
case LifetimeEntryState.Past:
// Past entries may be found in the newEntries set after a lifetime change (see requestLifetimeUpdate).
removed = pastEntries.Remove(entry) || newEntries.Remove(entry);
break;
case LifetimeEntryState.Future:
// Future entries may be found in the newEntries set after a lifetime change (see requestLifetimeUpdate).
removed = futureEntries.Remove(entry) || newEntries.Remove(entry);
break;
}
if (!removed)
return false;
entry.ChildId = 0;
return true;
}
/// <summary>
/// Removes all entries.
/// </summary>
public void ClearEntries()
{
foreach (var entry in newEntries)
{
entry.RequestLifetimeUpdate -= requestLifetimeUpdate;
entry.ChildId = 0;
}
foreach (var entry in pastEntries)
{
entry.RequestLifetimeUpdate -= requestLifetimeUpdate;
entry.ChildId = 0;
}
foreach (var entry in activeEntries)
{
entry.RequestLifetimeUpdate -= requestLifetimeUpdate;
EntryBecameDead?.Invoke(entry);
entry.ChildId = 0;
}
foreach (var entry in futureEntries)
{
entry.RequestLifetimeUpdate -= requestLifetimeUpdate;
entry.ChildId = 0;
}
newEntries.Clear();
pastEntries.Clear();
activeEntries.Clear();
futureEntries.Clear();
}
/// <summary>
/// Invoked when the lifetime of an entry is going to changed.
/// </summary>
private void requestLifetimeUpdate(LifetimeEntry entry)
{
// Entries in the past/future sets need to be re-sorted to prevent the comparer from becoming unstable.
// To prevent, e.g. CompositeDrawable alive children changing during enumeration, the entry's state must not be updated immediately.
//
// In order to achieve the above, the entry is first removed from the past/future set (resolving the comparator stability issues)
// and then re-queued back onto the new entries list to be re-processed in the next Update().
//
// Note that this does not apply to entries that are in the current set, as they don't utilise a lifetime comparer.
var futureOrPastSet = futureOrPastEntries(entry.State);
if (futureOrPastSet?.Remove(entry) == true)
{
// Enqueue the entry to be processed in the next Update().
newEntries.Add(entry);
}
}
/// <summary>
/// Retrieves the sorted set for a <see cref="LifetimeEntryState"/>.
/// </summary>
/// <param name="state">The <see cref="LifetimeEntryState"/>.</param>
/// <returns>Either <see cref="futureEntries"/>, <see cref="pastEntries"/>, or null.</returns>
[CanBeNull]
private SortedSet<LifetimeEntry> futureOrPastEntries(LifetimeEntryState state)
{
switch (state)
{
case LifetimeEntryState.Future:
return futureEntries;
case LifetimeEntryState.Past:
return pastEntries;
default:
return null;
}
}
/// <summary>
/// Updates the lifetime of entries at a single time value.
/// </summary>
/// <param name="time">The time to update at.</param>
/// <returns>Whether the state of any entries changed.</returns>
public bool Update(double time) => Update(time, time);
/// <summary>
/// Updates the lifetime of entries within a given time range.
/// </summary>
/// <param name="startTime">The start of the time range.</param>
/// <param name="endTime">The end of the time range.</param>
/// <returns>Whether the state of any entries changed.</returns>
public bool Update(double startTime, double endTime)
{
endTime = Math.Max(endTime, startTime);
bool aliveChildrenChanged = false;
// Check for newly-added entries.
foreach (var entry in newEntries)
aliveChildrenChanged |= updateChildEntry(entry, startTime, endTime, true, true);
newEntries.Clear();
// Check for newly alive entries when time is increased.
while (futureEntries.Count > 0)
{
FrameStatistics.Increment(StatisticsCounterType.CCL);
var entry = futureEntries.Min.AsNonNull(); // guaranteed by the .Count > 0 guard.
Debug.Assert(entry.State == LifetimeEntryState.Future);
if (getState(entry, startTime, endTime) == LifetimeEntryState.Future)
break;
futureEntries.Remove(entry);
aliveChildrenChanged |= updateChildEntry(entry, startTime, endTime, false, true);
}
// Check for newly alive entries when time is decreased.
while (pastEntries.Count > 0)
{
FrameStatistics.Increment(StatisticsCounterType.CCL);
var entry = pastEntries.Max.AsNonNull(); // guaranteed by the .Count > 0 guard.
Debug.Assert(entry.State == LifetimeEntryState.Past);
if (getState(entry, startTime, endTime) == LifetimeEntryState.Past)
break;
pastEntries.Remove(entry);
aliveChildrenChanged |= updateChildEntry(entry, startTime, endTime, false, true);
}
// Checks for newly dead entries when time is increased/decreased.
foreach (var entry in activeEntries)
{
FrameStatistics.Increment(StatisticsCounterType.CCL);
aliveChildrenChanged |= updateChildEntry(entry, startTime, endTime, false, false);
}
// Remove all newly-dead entries.
activeEntries.RemoveAll(e => e.State != LifetimeEntryState.Current);
while (eventQueue.Count != 0)
{
var (entry, kind, direction) = eventQueue.Dequeue();
EntryCrossedBoundary?.Invoke(entry, kind, direction);
}
return aliveChildrenChanged;
}
/// <summary>
/// Updates the state of a single <see cref="LifetimeEntry"/>.
/// </summary>
/// <param name="entry">The <see cref="LifetimeEntry"/> to update.</param>
/// <param name="startTime">The start of the time range.</param>
/// <param name="endTime">The end of the time range.</param>
/// <param name="isNewEntry">Whether <paramref name="entry"/> is part of the new entries set.
/// The state may be "new" or "past"/"future", in which case it will undergo further processing to return it to the correct set.</param>
/// <param name="mutateActiveEntries">Whether <see cref="activeEntries"/> should be mutated by this invocation.
/// If <c>false</c>, the caller is expected to handle mutation of <see cref="activeEntries"/> based on any changes to the entry's state.</param>
/// <returns>Whether the state of <paramref name="entry"/> has changed.</returns>
private bool updateChildEntry(LifetimeEntry entry, double startTime, double endTime, bool isNewEntry, bool mutateActiveEntries)
{
LifetimeEntryState oldState = entry.State;
// Past/future sets don't call this function unless a state change is guaranteed.
Debug.Assert(!futureEntries.Contains(entry) && !pastEntries.Contains(entry));
// The entry can be in one of three states:
// 1. The entry was previously in the past/future sets but a lifetime change was requested. Its state is currently "past"/"future".
// 2. The entry is a completely new entry. Its state is currently "new".
// 3. The entry is currently-active. Its state is "current" but it's also in the active set.
Debug.Assert(oldState != LifetimeEntryState.Current || activeEntries.Contains(entry));
LifetimeEntryState newState = getState(entry, startTime, endTime);
Debug.Assert(newState != LifetimeEntryState.New);
if (newState == oldState)
{
// If the state hasn't changed, then there's two possibilities:
// 1. The entry was in the past/future sets and a lifetime change was requested. The entry needs to be added back to the past/future sets.
// 2. The entry is and continues to remain active.
if (isNewEntry)
futureOrPastEntries(newState)?.Add(entry);
else
Debug.Assert(newState == LifetimeEntryState.Current);
// In both cases, the entry doesn't need to be processed further as it's already in the correct state.
return false;
}
bool aliveEntriesChanged = false;
if (newState == LifetimeEntryState.Current)
{
if (mutateActiveEntries)
activeEntries.Add(entry);
EntryBecameAlive?.Invoke(entry);
aliveEntriesChanged = true;
}
else if (oldState == LifetimeEntryState.Current)
{
if (mutateActiveEntries)
activeEntries.Remove(entry);
EntryBecameDead?.Invoke(entry);
aliveEntriesChanged = true;
}
entry.State = newState;
futureOrPastEntries(newState)?.Add(entry);
enqueueEvents(entry, oldState, newState);
return aliveEntriesChanged;
}
/// <summary>
/// Retrieves the new state for an entry.
/// </summary>
/// <param name="entry">The <see cref="LifetimeEntry"/>.</param>
/// <param name="startTime">The start of the time range.</param>
/// <param name="endTime">The end of the time range.</param>
/// <returns>The state of <paramref name="entry"/>. Can be either <see cref="LifetimeEntryState.Past"/>, <see cref="LifetimeEntryState.Current"/>, or <see cref="LifetimeEntryState.Future"/>.</returns>
private LifetimeEntryState getState(LifetimeEntry entry, double startTime, double endTime)
{
// Consider a static entry and a moving time range:
// [-----------Entry-----------]
// [----Range----] | | (not alive)
// [----Range----] | (alive)
// | [----Range----] (alive)
// | [----Range----] (not alive)
// | | [----Range----] (not alive)
// | |
if (endTime < entry.LifetimeStart)
return LifetimeEntryState.Future;
if (startTime >= entry.LifetimeEnd)
return LifetimeEntryState.Past;
return LifetimeEntryState.Current;
}
private void enqueueEvents(LifetimeEntry entry, LifetimeEntryState oldState, LifetimeEntryState newState)
{
Debug.Assert(oldState != newState);
switch (oldState)
{
case LifetimeEntryState.Future:
eventQueue.Enqueue((entry, LifetimeBoundaryKind.Start, LifetimeBoundaryCrossingDirection.Forward));
if (newState == LifetimeEntryState.Past)
eventQueue.Enqueue((entry, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Forward));
break;
case LifetimeEntryState.Current:
eventQueue.Enqueue(newState == LifetimeEntryState.Past
? (entry, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Forward)
: (entry, LifetimeBoundaryKind.Start, LifetimeBoundaryCrossingDirection.Backward));
break;
case LifetimeEntryState.Past:
eventQueue.Enqueue((entry, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Backward));
if (newState == LifetimeEntryState.Future)
eventQueue.Enqueue((entry, LifetimeBoundaryKind.Start, LifetimeBoundaryCrossingDirection.Backward));
break;
}
}
/// <summary>
/// Compares by <see cref="LifetimeEntry.LifetimeStart"/>.
/// </summary>
private sealed class LifetimeStartComparator : IComparer<LifetimeEntry>
{
public int Compare(LifetimeEntry x, LifetimeEntry y)
{
if (x == null) throw new ArgumentNullException(nameof(x));
if (y == null) throw new ArgumentNullException(nameof(y));
int c = x.LifetimeStart.CompareTo(y.LifetimeStart);
return c != 0 ? c : x.ChildId.CompareTo(y.ChildId);
}
}
/// <summary>
/// Compares by <see cref="LifetimeEntry.LifetimeEnd"/>.
/// </summary>
private sealed class LifetimeEndComparator : IComparer<LifetimeEntry>
{
public int Compare(LifetimeEntry x, LifetimeEntry y)
{
if (x == null) throw new ArgumentNullException(nameof(x));
if (y == null) throw new ArgumentNullException(nameof(y));
int c = x.LifetimeEnd.CompareTo(y.LifetimeEnd);
return c != 0 ? c : x.ChildId.CompareTo(y.ChildId);
}
}
}
}
| |
using System;
namespace PalmeralGenNHibernate.EN.Default_
{
public partial class ProveedorEN
{
/**
*
*/
private string id;
/**
*
*/
private string nombre;
/**
*
*/
private string telefono;
/**
*
*/
private string direccion;
/**
*
*/
private string localidad;
/**
*
*/
private string provincia;
/**
*
*/
private string codigoPostal;
/**
*
*/
private string email;
/**
*
*/
private string pais;
/**
*
*/
private string descripcion;
/**
*
*/
private System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.PedidoEN> pedido;
public virtual string Id {
get { return id; } set { id = value; }
}
public virtual string Nombre {
get { return nombre; } set { nombre = value; }
}
public virtual string Telefono {
get { return telefono; } set { telefono = value; }
}
public virtual string Direccion {
get { return direccion; } set { direccion = value; }
}
public virtual string Localidad {
get { return localidad; } set { localidad = value; }
}
public virtual string Provincia {
get { return provincia; } set { provincia = value; }
}
public virtual string CodigoPostal {
get { return codigoPostal; } set { codigoPostal = value; }
}
public virtual string Email {
get { return email; } set { email = value; }
}
public virtual string Pais {
get { return pais; } set { pais = value; }
}
public virtual string Descripcion {
get { return descripcion; } set { descripcion = value; }
}
public virtual System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.PedidoEN> Pedido {
get { return pedido; } set { pedido = value; }
}
public ProveedorEN()
{
pedido = new System.Collections.Generic.List<PalmeralGenNHibernate.EN.Default_.PedidoEN>();
}
public ProveedorEN(string id, string nombre, string telefono, string direccion, string localidad, string provincia, string codigoPostal, string email, string pais, string descripcion, System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.PedidoEN> pedido)
{
this.init (id, nombre, telefono, direccion, localidad, provincia, codigoPostal, email, pais, descripcion, pedido);
}
public ProveedorEN(ProveedorEN proveedor)
{
this.init (proveedor.Id, proveedor.Nombre, proveedor.Telefono, proveedor.Direccion, proveedor.Localidad, proveedor.Provincia, proveedor.CodigoPostal, proveedor.Email, proveedor.Pais, proveedor.Descripcion, proveedor.Pedido);
}
private void init (string id, string nombre, string telefono, string direccion, string localidad, string provincia, string codigoPostal, string email, string pais, string descripcion, System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.PedidoEN> pedido)
{
this.Id = id;
this.Nombre = nombre;
this.Telefono = telefono;
this.Direccion = direccion;
this.Localidad = localidad;
this.Provincia = provincia;
this.CodigoPostal = codigoPostal;
this.Email = email;
this.Pais = pais;
this.Descripcion = descripcion;
this.Pedido = pedido;
}
public override bool Equals (object obj)
{
if (obj == null)
return false;
ProveedorEN t = obj as ProveedorEN;
if (t == null)
return false;
if (Id.Equals (t.Id))
return true;
else
return false;
}
public override int GetHashCode ()
{
int hash = 13;
hash += this.Id.GetHashCode ();
return hash;
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
namespace Effekseer
{
[Serializable]
internal abstract class Resource
{
public string path {get; protected set;}
public AssetBundle assetBundle {get; protected set;}
public abstract bool Load(string path, AssetBundle assetBundle);
public abstract void Unload();
protected T LoadAsset<T>(string path, bool removeExtension, AssetBundle assetBundle) where T : UnityEngine.Object {
this.path = path;
this.assetBundle = assetBundle;
if (assetBundle != null) {
return assetBundle.LoadAsset<T>(
Utility.ResourcePath(path, removeExtension));
} else {
return Resources.Load<T>(
Utility.ResourcePath(path, removeExtension));
}
}
protected void UnloadAsset(UnityEngine.Object asset) {
if (asset != null) {
if (assetBundle != null) {
} else {
Resources.UnloadAsset(asset);
}
}
}
}
[Serializable]
internal class TextureResource : Resource
{
public Texture2D texture;
public override bool Load(string path, AssetBundle assetBundle) {
texture = LoadAsset<Texture2D>(path, true, assetBundle);
if (texture == null) {
//Debug.LogError("[Effekseer] Failed to load Texture: " + path);
return false;
}
return true;
}
public override void Unload() {
UnloadAsset(texture);
texture = null;
}
public IntPtr GetNativePtr() {
return texture.GetNativeTexturePtr();
}
}
[Serializable]
internal class ModelResource : Resource
{
public TextAsset modelData;
public override bool Load(string path, AssetBundle assetBundle) {
modelData = LoadAsset<TextAsset>(path, false, assetBundle);
if (modelData == null) {
//Debug.LogError("[Effekseer] Failed to load Model: " + path);
return false;
}
return true;
}
public override void Unload() {
UnloadAsset(modelData);
modelData = null;
}
public bool Copy(IntPtr buffer, int bufferSize) {
if (modelData.bytes.Length < bufferSize) {
Marshal.Copy(modelData.bytes, 0, buffer, modelData.bytes.Length);
return true;
}
return false;
}
}
[Serializable]
internal class SoundResource : Resource
{
public AudioClip audio;
public override bool Load(string path, AssetBundle assetBundle) {
audio = LoadAsset<AudioClip>(path, true, assetBundle);
if (audio == null) {
Debug.LogError("[Effekseer] Failed to load Sound: " + path);
return false;
}
return true;
}
public override void Unload() {
UnloadAsset(audio);
audio = null;
}
}
internal static class Utility
{
public static float[] Matrix2Array(Matrix4x4 mat) {
float[] res = new float[16];
res[ 0] = mat.m00; res[ 1] = mat.m01; res[ 2] = mat.m02; res[ 3] = mat.m03;
res[ 4] = mat.m10; res[ 5] = mat.m11; res[ 6] = mat.m12; res[ 7] = mat.m13;
res[ 8] = mat.m20; res[ 9] = mat.m21; res[10] = mat.m22; res[11] = mat.m23;
res[12] = mat.m30; res[13] = mat.m31; res[14] = mat.m32; res[15] = mat.m33;
return res;
}
public static string StrPtr16ToString(IntPtr strptr16, int len) {
byte[] strarray = new byte[len * 2];
Marshal.Copy(strptr16, strarray, 0, len * 2);
return Encoding.Unicode.GetString(strarray);
}
public static string ResourcePath(string path, bool removeExtension) {
string dir = Path.GetDirectoryName(path);
string file = (removeExtension) ?
Path.GetFileNameWithoutExtension(path) :
Path.GetFileName(path);
return "Effekseer/" + ((dir == String.Empty) ? file : dir + "/" + file);
}
}
internal static class Plugin
{
#if !UNITY_EDITOR && (UNITY_IPHONE || UNITY_WEBGL)
public const string pluginName = "__Internal";
#else
public const string pluginName = "EffekseerUnity";
#endif
[DllImport(pluginName)]
public static extern void EffekseerInit(int maxInstances, int maxSquares, bool reversedDepth);
[DllImport(pluginName)]
public static extern void EffekseerTerm();
[DllImport(pluginName)]
public static extern void EffekseerUpdate(float deltaTime);
[DllImport(pluginName)]
public static extern IntPtr EffekseerGetRenderFunc();
[DllImport(pluginName)]
public static extern void EffekseerSetProjectionMatrix(int renderId, float[] matrix);
[DllImport(pluginName)]
public static extern void EffekseerSetCameraMatrix(int renderId, float[] matrix);
[DllImport(pluginName)]
public static extern void EffekseerSetRenderSettings(int renderId, bool renderIntoTexture);
[DllImport(pluginName)]
public static extern IntPtr EffekseerLoadEffect(IntPtr path);
[DllImport(pluginName)]
public static extern IntPtr EffekseerLoadEffectOnMemory(IntPtr data, int size);
[DllImport(pluginName)]
public static extern void EffekseerReleaseEffect(IntPtr effect);
[DllImport(pluginName)]
public static extern int EffekseerPlayEffect(IntPtr effect, float x, float y, float z);
[DllImport(pluginName)]
public static extern void EffekseerStopEffect(int handle);
[DllImport(pluginName)]
public static extern void EffekseerStopRoot(int handle);
[DllImport(pluginName)]
public static extern void EffekseerStopAllEffects();
[DllImport(pluginName)]
public static extern void EffekseerSetShown(int handle, bool shown);
[DllImport(pluginName)]
public static extern void EffekseerSetPaused(int handle, bool paused);
[DllImport(pluginName)]
public static extern bool EffekseerExists(int handle);
[DllImport(pluginName)]
public static extern void EffekseerSetLocation(int handle, float x, float y, float z);
[DllImport(pluginName)]
public static extern void EffekseerSetRotation(int handle, float x, float y, float z, float angle);
[DllImport(pluginName)]
public static extern void EffekseerSetScale(int handle, float x, float y, float z);
[DllImport(pluginName)]
public static extern void EffekseerSetTargetLocation(int handle, float x, float y, float z);
[DllImport(pluginName)]
public static extern void EffekseerSetTextureLoaderEvent(
EffekseerTextureLoaderLoad load,
EffekseerTextureLoaderUnload unload);
public delegate IntPtr EffekseerTextureLoaderLoad(IntPtr path);
public delegate void EffekseerTextureLoaderUnload(IntPtr path);
[DllImport(pluginName)]
public static extern void EffekseerSetModelLoaderEvent(
EffekseerModelLoaderLoad load,
EffekseerModelLoaderUnload unload);
public delegate int EffekseerModelLoaderLoad(IntPtr path, IntPtr buffer, int bufferSize);
public delegate void EffekseerModelLoaderUnload(IntPtr path);
[DllImport(pluginName)]
public static extern void EffekseerSetSoundLoaderEvent(
EffekseerSoundLoaderLoad load,
EffekseerSoundLoaderUnload unload);
public delegate int EffekseerSoundLoaderLoad(IntPtr path);
public delegate void EffekseerSoundLoaderUnload(IntPtr path);
[DllImport(pluginName)]
public static extern void EffekseerSetSoundPlayerEvent(
EffekseerSoundPlayerPlay play,
EffekseerSoundPlayerStopTag stopTag,
EffekseerSoundPlayerPauseTag pauseTag,
EffekseerSoundPlayerCheckPlayingTag checkPlayingTag,
EffekseerSoundPlayerStopAll atopAll);
public delegate void EffekseerSoundPlayerPlay(IntPtr tag,
int data, float volume, float pan, float pitch,
bool mode3D, float x, float y, float z, float distance);
public delegate void EffekseerSoundPlayerStopTag(IntPtr tag);
public delegate void EffekseerSoundPlayerPauseTag(IntPtr tag, bool pause);
public delegate bool EffekseerSoundPlayerCheckPlayingTag(IntPtr tag);
public delegate void EffekseerSoundPlayerStopAll();
}
public class SoundInstance : MonoBehaviour {
new private AudioSource audio;
public string AudioTag;
void Awake() {
audio = gameObject.AddComponent<AudioSource>();
audio.playOnAwake = false;
}
void Update() {
if (audio.clip && !audio.isPlaying) {
audio.clip = null;
}
}
public void Play(string tag, AudioClip clip,
float volume, float pan, float pitch,
bool mode3D, float x, float y, float z, float distance)
{
this.AudioTag = tag;
transform.position = new Vector3(x, y, z);
audio.spatialBlend = (mode3D) ? 1.0f : 0.0f;
audio.volume = volume;
audio.pitch = Mathf.Pow(2.0f, pitch);
audio.panStereo = pan;
audio.minDistance = distance;
audio.maxDistance = distance * 2;
audio.clip = clip;
audio.Play();
}
public void Stop() {
audio.Stop();
}
public void Pause(bool paused) {
if (paused) audio.Pause();
else audio.UnPause();
}
public bool CheckPlaying() {
return audio.isPlaying;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Research.Naiad;
using Microsoft.Research.Naiad.Dataflow;
using Microsoft.Research.Naiad.Dataflow.Channels;
using Microsoft.Research.Naiad.DataStructures;
using Microsoft.Research.Naiad.Frameworks.Lindi;
using Microsoft.Research.Naiad.Frameworks.Reduction;
using Microsoft.Research.Naiad.Frameworks.DifferentialDataflow;
using Microsoft.Research.Naiad.Input;
namespace Microsoft.Research.Naiad.Examples.PageRank
{
public class PageRank : Example {
public struct IntInt : IEquatable<IntInt> {
public int first;
public int second;
public bool Equals(IntInt that) {
return first == that.first && second == that.second;
}
public int CompareTo(IntInt that) {
if (this.first != that.first)
return this.first - that.first;
return this.second - that.second;
}
public override int GetHashCode() {
return 47 * first + 36425232 * second;
}
public override string ToString() {
return String.Format("{0} {1}", first, second);
}
public IntInt(int ss, int tt) {
first = ss;
second = tt;
}
}
public struct IntDouble : IEquatable<IntDouble> {
public int first;
public double second;
public bool Equals(IntDouble that) {
return first == that.first && second == that.second;
}
public int CompareTo(IntDouble that) {
if (first != that.first)
return first - that.first;
if (second < that.second) {
return -1;
} else if (second > that.second) {
return 1;
} else {
return 0;
}
}
public override int GetHashCode() {
return 47 * first + 36425232 * second.GetHashCode();
}
public override string ToString() {
return String.Format("{0} {1}", first, second);
}
public IntDouble(int x, double y) {
first = x;
second = y;
}
}
public IEnumerable<IntInt> read_edges(string filename)
{
StreamReader reader = File.OpenText(filename);
for (; !reader.EndOfStream; )
{
var elements = reader.ReadLine().Split(' ');
yield return new IntInt(Convert.ToInt32(elements[0]),Convert.ToInt32(elements[1]));
}
}
public IEnumerable<IntDouble> read_pr(string filename) {
StreamReader reader = File.OpenText(filename);
for (; !reader.EndOfStream; ) {
var elements = reader.ReadLine().Split(' ');
yield return new IntDouble(Convert.ToInt32(elements[0]),Convert.ToDouble(elements[1]));
}
}
public struct Reducernode_cnt : IAddable<Reducernode_cnt>
{
public int value0;
public Reducernode_cnt(int value0)
{
this.value0 = value0;
}
public Reducernode_cnt Add(Reducernode_cnt other)
{
value0 += other.value0;
return this;
}
}
public struct Reducerpr1 : IAddable<Reducerpr1>
{
public double value0;
public Reducerpr1(double value0)
{
this.value0 = value0;
}
public Reducerpr1 Add(Reducerpr1 other)
{
value0 += other.value0;
return this;
}
}
public struct IntIntInt : IEquatable<IntIntInt>
{
public int first;
public int second;
public int third;
public bool Equals(IntIntInt that)
{
return first == that.first && second == that.second && third == that.third;
}
public int CompareTo(IntIntInt that)
{
if (this.first != that.first)
return this.first - that.first;
if (this.second != that.second)
return this.second - that.second;
return this.third - that.third;
}
// Embarassing hashcodes
public override int GetHashCode()
{
return first + 1234347 * second + 4311 * third;
}
public override string ToString()
{
return String.Format("{0} {1} {2}", first, second, third);
}
public IntIntInt(int x, int y, int z)
{
first = x;
second = y;
third = z;
}
}
public struct IntIntIntDouble : IEquatable<IntIntIntDouble> {
public int first;
public int second;
public int third;
public double fourth;
public bool Equals(IntIntIntDouble that) {
return first == that.first && second == that.second &&
third == that.third && Math.Abs(fourth - that.fourth) < 0.0000001;
}
public int CompareTo(IntIntIntDouble that) {
if (this.first != that.first)
return this.first - that.first;
if (this.second != that.second)
return this.second - that.second;
if (this.third != that.third)
return this.third - that.third;
return this.fourth - that.fourth < 0 ? -1 : 1;
}
// Embarassing hashcodes
public override int GetHashCode() {
return first + 1234347 * second + 4311 * third + fourth.GetHashCode();
}
public override string ToString() {
return String.Format("{0} {1} {2} {3}", first, second, third, fourth);
}
public IntIntIntDouble(int x, int y, int z, double zz) {
first = x;
second = y;
third = z;
fourth = zz;
}
}
public string Usage {get {return "<graph> <local path prefix>";} }
public void Execute(string[] args) {
using (var computation = NewComputation.FromArgs(ref args)) {
var edges_input = new BatchedDataSource<string>();
var pr_input = new BatchedDataSource<string>();
var edges = computation.NewInput(edges_input).SelectMany(line => read_edges(line));
var pr = computation.NewInput(pr_input).SelectMany(line => read_pr(line));
var node_cnt_tmp =
edges.GenericAggregator(row => row.first,
row => new Reducernode_cnt(1));
var node_cnt = node_cnt_tmp.Select(row => { Reducernode_cnt aggVal = (Reducernode_cnt)row.Second ; return new IntInt(row.First, aggVal.value0); });
var edgescnt = edges.Join(node_cnt,
(IntInt left) => left.first,
(IntInt right) => right.first,
(IntInt left, IntInt right) => new IntIntInt(left.first, left.second , right.second));
for (int i = 0; i < 5; ++i) {
var edgespr = edgescnt.Join(pr,
(IntIntInt left) => left.first,
(IntDouble right) => right.first,
(IntIntInt left, IntDouble right) => new IntIntIntDouble(left.first, left.second, left.third , right.second));
var rankcnt = edgespr.Select(row => new IntIntIntDouble(row.first,row.second,row.third,row.fourth / row.third));
var links = rankcnt.Select(row => new IntDouble(row.second,row.fourth));
var pr1_tmp = links.GenericAggregator(row => row.first,
row => new Reducerpr1(row.second));
var pr1 = pr1_tmp.Select(row => { Reducerpr1 aggVal = (Reducerpr1)row.Second ; return new IntDouble(row.First, aggVal.value0); });
var pr2 = pr1.Select(row => new IntDouble(row.first,0.85 * row.second));
pr = pr2.Select(row => new IntDouble(row.first,0.15 + row.second));
}
int minThreadId = computation.Configuration.ProcessID * computation.Configuration.WorkerCount;
StreamWriter[] file_pr = new StreamWriter[computation.Configuration.WorkerCount];
for (int i = 0; i < computation.Configuration.WorkerCount; ++i) {
int j = minThreadId + i;
file_pr[i] = new StreamWriter(args[2] + "/pagerank_" + args[1] + j + ".out");
}
pr.Subscribe((i, l) => { foreach (var element in l) file_pr[i - minThreadId].WriteLine(element); });
computation.Activate();
edges_input.OnCompleted(args[2] + "/pagerank_" + args[1] + "_edges" + computation.Configuration.ProcessID + ".in");
pr_input.OnCompleted(args[2] + "/pagerank_" + args[1] + "_vertices" + computation.Configuration.ProcessID + ".in");
computation.Join();
for (int i = 0; i < computation.Configuration.WorkerCount; ++i) {
file_pr[i].Close();
}
}
}
public string Help {
get {
return "PageRank <graph> <local path prefix>";
}
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using DevExpress.CodeRush.StructuralParser;
using System.Reflection;
namespace CR_ImportNamespace
{
public class AssemblyNamespace
{
private bool _IsProjectReference;
const string STR_AssemblyCacheFormat = "AssemblyCache{0}";
readonly static Dictionary<ExtendedFrameworkVersion, List<string>> assemblyCache = new Dictionary<ExtendedFrameworkVersion, List<string>>();
readonly static List<string> namespaceCache = new List<string>();
readonly ExtendedFrameworkVersion frameworkVersion;
int assemblyIndex;
int namespaceIndex;
ProjectElement referenceProject;
string _AssemblyFilePath;
public AssemblyNamespace()
{
}
public AssemblyNamespace(string assemblyName, string @namespace, ExtendedFrameworkVersion frameworkVersion)
{
this.frameworkVersion = frameworkVersion;
Assembly = assemblyName;
Namespace = @namespace;
}
public AssemblyNamespace(ExtendedFrameworkVersion frameworkVersion, int assemblyIndex, int namespaceIndex)
{
this.frameworkVersion = frameworkVersion;
this.assemblyIndex = assemblyIndex;
this.namespaceIndex = namespaceIndex;
}
// private methods...
static void WriteStrings(BinaryWriter writer, string[] strings)
{
writer.Write(strings.Length);
foreach (string s in strings)
writer.Write(s);
}
static string[] ReadStrings(BinaryReader reader)
{
int count = reader.ReadInt32();
string[] result = new string[count];
for (int i = 0; i < count; i++)
result[i] = reader.ReadString();
return result;
}
static string GetFileName(ExtendedFrameworkVersion frameworkVersion)
{
return String.Format(STR_AssemblyCacheFormat, frameworkVersion);
}
// public static methods...
public static void InitializeCache(ExtendedFrameworkVersion frameworkVersion)
{
if (!assemblyCache.ContainsKey(frameworkVersion))
assemblyCache.Add(frameworkVersion, new List<string>());
}
public static void SaveCache(CacheFileSystem fileSystem, ExtendedFrameworkVersion frameworkVersion)
{
string fileName = GetFileName(frameworkVersion);
using (MemoryStream stream = new MemoryStream())
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
bool hasAssemblyCache = assemblyCache.ContainsKey(frameworkVersion);
writer.Write(hasAssemblyCache);
if (hasAssemblyCache)
WriteStrings(writer, assemblyCache[frameworkVersion].ToArray());
WriteStrings(writer, namespaceCache.ToArray());
writer.Flush();
stream.Position = 0;
fileSystem.Write(fileName, stream);
}
}
}
public static void LoadCache(CacheFileSystem fileSystem, ExtendedFrameworkVersion frameworkVersion)
{
if (assemblyCache.ContainsKey(frameworkVersion))
assemblyCache[frameworkVersion].Clear();
else
assemblyCache.Add(frameworkVersion, new List<string>());
string fileName = GetFileName(frameworkVersion);
Stream stream = fileSystem.Read(fileName);
if (stream == null)
return;
using (BinaryReader reader = new BinaryReader(stream))
{
bool hasAssemblyCache = reader.ReadBoolean();
if (hasAssemblyCache)
assemblyCache[frameworkVersion].AddRange(ReadStrings(reader));
namespaceCache.Clear();
namespaceCache.AddRange(ReadStrings(reader));
}
}
public string GetReferenceName()
{
string referenceName = String.Empty;
if (IsProjectReference)
return ReferenceProject.Name;
else if (!String.IsNullOrEmpty(AssemblyFilePath))
return AssemblyFilePath;
else
return Assembly;
}
public string GetFullAssemblyName()
{
string referenceName = String.Empty;
try
{
if (IsProjectReference)
return ReferenceProject.Name;
else if (!String.IsNullOrEmpty(AssemblyFilePath))
{
AssemblyName name = AssemblyName.GetAssemblyName(AssemblyFilePath);
return name.FullName;
}
else
return Assembly;
}
catch (Exception ex)
{
return String.Empty;
}
}
// public properties...
public string Assembly
{
get { return assemblyCache[frameworkVersion][AssemblyIndex]; }
set
{
List<string> thisFrameworkAssemblyCache = assemblyCache[frameworkVersion];
assemblyIndex = thisFrameworkAssemblyCache.IndexOf(value);
if (assemblyIndex >= 0)
return;
assemblyIndex = thisFrameworkAssemblyCache.Count;
thisFrameworkAssemblyCache.Add(value);
}
}
public int AssemblyIndex
{
get { return assemblyIndex; }
}
public int NamespaceIndex
{
get { return namespaceIndex; }
}
public string Namespace
{
get { return namespaceCache[NamespaceIndex]; }
set
{
namespaceIndex = namespaceCache.IndexOf(value);
if (NamespaceIndex == -1)
{
namespaceIndex = namespaceCache.Count;
namespaceCache.Add(value);
}
}
}
public string AssemblyFilePath
{
get { return _AssemblyFilePath; }
set { _AssemblyFilePath = value; }
}
public bool IsProjectReference
{
get { return ReferenceProject != null; }
}
public ProjectElement ReferenceProject
{
get { return referenceProject; }
set { referenceProject = value; }
}
}
}
| |
/*
*
* (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.Data;
using System.Linq;
using System.Security;
using ASC.Common.Logging;
using ASC.Mail.Core.Entities;
using ASC.Mail.Data.Contracts;
using ASC.Mail.Server.Core.Entities;
using ASC.Mail.Utils;
using ASC.Web.Core;
using SecurityContext = ASC.Core.SecurityContext;
namespace ASC.Mail.Core.Engine
{
public class ServerMailgroupEngine
{
public int Tenant { get; private set; }
public string User { get; private set; }
public ILog Log { get; private set; }
public ServerMailgroupEngine(int tenant, string user, ILog log = null)
{
Tenant = tenant;
User = user;
Log = log ?? LogManager.GetLogger("ASC.Mail.ServerMailgroupEngine");
}
public List<ServerDomainGroupData> GetMailGroups()
{
if (!IsAdmin)
throw new SecurityException("Need admin privileges.");
var list = new List<ServerDomainGroupData>();
using (var daoFactory = new DaoFactory())
{
var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);
var domains = serverDomainDao.GetDomains();
var serverGroupDao = daoFactory.CreateServerGroupDao(Tenant);
var groups = serverGroupDao.GetList();
var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);
list.AddRange(from serverGroup in groups
let address = serverAddressDao.Get(serverGroup.AddressId)
let domain = domains.FirstOrDefault(d => d.Id == address.DomainId)
where domain != null
let serverGroupAddress = ServerMailboxEngine.ToServerDomainAddressData(address, domain)
let serverGroupAddresses =
serverAddressDao.GetGroupAddresses(serverGroup.Id)
.ConvertAll(a => ServerMailboxEngine.ToServerDomainAddressData(a, domain))
select ToServerDomainGroupData(serverGroup.Id, serverGroupAddress, serverGroupAddresses));
}
return list;
}
public ServerDomainGroupData CreateMailGroup(string name, int domainId, List<int> addressIds)
{
if (!IsAdmin)
throw new SecurityException("Need admin privileges.");
if (string.IsNullOrEmpty(name))
throw new ArgumentException(@"Invalid mailgroup name.", "name");
if (domainId < 0)
throw new ArgumentException(@"Invalid domain id.", "domainId");
if (name.Length > 64)
throw new ArgumentException(@"Local part of mailgroup exceed limitation of 64 characters.", "name");
if (!Parser.IsEmailLocalPartValid(name))
throw new ArgumentException(@"Incorrect group name.", "name");
if (!addressIds.Any())
throw new ArgumentException(@"Empty collection of address_ids.", "addressIds");
var mailgroupName = name.ToLowerInvariant();
using (var daoFactory = new DaoFactory())
{
var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);
var serverDomain = serverDomainDao.GetDomain(domainId);
if (serverDomain.Tenant == Defines.SHARED_TENANT_ID)
throw new InvalidOperationException("Creating mail group is not allowed for shared domain.");
var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);
if (serverAddressDao.IsAddressAlreadyRegistered(mailgroupName, serverDomain.Name))
{
throw new DuplicateNameException("You want to create a group with already existing address.");
}
var utcNow = DateTime.UtcNow;
var address = new ServerAddress
{
Id = 0,
Tenant = Tenant,
MailboxId = -1,
DomainId = serverDomain.Id,
AddressName = mailgroupName,
IsAlias = false,
IsMailGroup = true,
DateCreated = utcNow
};
var groupEmail = string.Format("{0}@{1}", mailgroupName, serverDomain.Name);
var groupAddressData = ServerMailboxEngine.ToServerDomainAddressData(address, groupEmail);
var newGroupMembers = serverAddressDao.GetList(addressIds);
var newGroupMemberIds = newGroupMembers.ConvertAll(m => m.Id);
var newGroupMemberDataList =
newGroupMembers.ConvertAll(m =>
ServerMailboxEngine.ToServerDomainAddressData(m,
string.Format("{0}@{1}", m.AddressName, serverDomain.Name)));
var goTo = string.Join(",",
newGroupMembers.Select(m => string.Format("{0}@{1}", m.AddressName, serverDomain.Name)));
var serverDao = daoFactory.CreateServerDao();
var server = serverDao.Get(Tenant);
var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);
var group = new ServerGroup
{
Id = 0,
Tenant = Tenant,
Address = groupEmail,
AddressId = 0,
DateCreated = utcNow
};
using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
{
address.Id = serverAddressDao.Save(address);
group.AddressId = address.Id;
var serverGroupDao = daoFactory.CreateServerGroupDao(Tenant);
group.Id = serverGroupDao.Save(group);
serverAddressDao.AddAddressesToMailGroup(group.Id, newGroupMemberIds);
var serverAddress = new Alias
{
Name = "",
Address = groupEmail,
GoTo = goTo,
Domain = serverDomain.Name,
IsActive = true,
IsGroup = true,
Modified = utcNow,
Created = utcNow
};
engine.SaveAlias(serverAddress);
tx.Commit();
}
CacheEngine.ClearAll();
return ToServerDomainGroupData(group.Id, groupAddressData, newGroupMemberDataList);
}
}
public ServerDomainGroupData AddMailGroupMember(int mailgroupId, int addressId)
{
if (!IsAdmin)
throw new SecurityException("Need admin privileges.");
if (addressId < 0)
throw new ArgumentException(@"Invalid address id.", "addressId");
if (mailgroupId < 0)
throw new ArgumentException(@"Invalid mailgroup id.", "mailgroupId");
using (var daoFactory = new DaoFactory())
{
var serverGroupDao = daoFactory.CreateServerGroupDao(Tenant);
var group = serverGroupDao.Get(mailgroupId);
if (group == null)
throw new Exception("Group not found");
var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);
var groupMembers = serverAddressDao.GetGroupAddresses(mailgroupId);
if (groupMembers.Exists(a => a.Id == addressId))
throw new DuplicateNameException("Member already exists");
var newMemberAddress = serverAddressDao.Get(addressId);
if (newMemberAddress == null)
throw new Exception("Member not found");
var serverDao = daoFactory.CreateServerDao();
var server = serverDao.Get(Tenant);
var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);
var utcNow = DateTime.UtcNow;
ServerAddress groupAddress;
string groupEmail;
List<ServerDomainAddressData> newGroupMemberDataList;
using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
{
serverAddressDao.AddAddressesToMailGroup(mailgroupId, new List<int> { addressId });
groupMembers.Add(newMemberAddress);
groupAddress = serverAddressDao.Get(group.AddressId);
var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);
var serverDomain = serverDomainDao.GetDomain(groupAddress.DomainId);
var goTo = string.Join(",",
groupMembers.Select(m => string.Format("{0}@{1}", m.AddressName, serverDomain.Name)));
groupEmail = string.Format("{0}@{1}", groupAddress.AddressName, serverDomain.Name);
newGroupMemberDataList =
groupMembers.ConvertAll(m =>
ServerMailboxEngine.ToServerDomainAddressData(m,
string.Format("{0}@{1}", m.AddressName, serverDomain.Name)));
var serverAddress = new Alias
{
Name = "",
Address = groupEmail,
GoTo = goTo,
Domain = serverDomain.Name,
IsActive = true,
IsGroup = true,
Modified = utcNow,
Created = utcNow
};
engine.SaveAlias(serverAddress);
tx.Commit();
}
var groupAddressData = ServerMailboxEngine.ToServerDomainAddressData(groupAddress, groupEmail);
CacheEngine.ClearAll();
return ToServerDomainGroupData(group.Id, groupAddressData, newGroupMemberDataList);
}
}
public void RemoveMailGroupMember(int mailgroupId, int addressId)
{
if (!IsAdmin)
throw new SecurityException("Need admin privileges.");
if (addressId < 0)
throw new ArgumentException(@"Invalid address id.", "addressId");
if (mailgroupId < 0)
throw new ArgumentException(@"Invalid mailgroup id.", "mailgroupId");
using (var daoFactory = new DaoFactory())
{
var serverGroupDao = daoFactory.CreateServerGroupDao(Tenant);
var group = serverGroupDao.Get(mailgroupId);
if (group == null)
throw new Exception("Group not found");
var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);
var groupMembers = serverAddressDao.GetGroupAddresses(mailgroupId);
var removeMember = groupMembers.FirstOrDefault(a => a.Id == addressId);
if (removeMember == null)
throw new ArgumentException("Member not found");
groupMembers.Remove(removeMember);
if (groupMembers.Count == 0)
throw new Exception("Can't remove last member; Remove group.");
var serverDao = daoFactory.CreateServerDao();
var server = serverDao.Get(Tenant);
var groupAddress = serverAddressDao.Get(group.AddressId);
var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);
var serverDomain = serverDomainDao.GetDomain(groupAddress.DomainId);
var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);
var utcNow = DateTime.UtcNow;
using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
{
serverAddressDao.DeleteAddressFromMailGroup(mailgroupId, addressId);
var goTo = string.Join(",",
groupMembers.Select(m => string.Format("{0}@{1}", m.AddressName, serverDomain.Name)));
var groupEmail = string.Format("{0}@{1}", groupAddress.AddressName, serverDomain.Name);
var serverAddress = new Alias
{
Name = "",
Address = groupEmail,
GoTo = goTo,
Domain = serverDomain.Name,
IsActive = true,
IsGroup = true,
Modified = utcNow,
Created = group.DateCreated
};
engine.SaveAlias(serverAddress);
tx.Commit();
}
}
CacheEngine.ClearAll();
}
public void RemoveMailGroup(int id)
{
if (!IsAdmin)
throw new SecurityException("Need admin privileges.");
if (id < 0)
throw new ArgumentException(@"Invalid mailgroup id.", "id");
using (var daoFactory = new DaoFactory())
{
var serverGroupDao = daoFactory.CreateServerGroupDao(Tenant);
var group = serverGroupDao.Get(id);
if (group == null)
throw new Exception("Group not found");
var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);
var serverDao = daoFactory.CreateServerDao();
var server = serverDao.Get(Tenant);
var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);
using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
{
serverGroupDao.Delete(id);
serverAddressDao.DeleteAddressesFromMailGroup(id);
serverAddressDao.Delete(group.AddressId);
engine.RemoveAlias(group.Address);
tx.Commit();
}
}
CacheEngine.ClearAll();
}
public static ServerDomainGroupData ToServerDomainGroupData(int groupId, ServerDomainAddressData address, List<ServerDomainAddressData> addresses)
{
var group = new ServerDomainGroupData
{
Id = groupId,
Address = address,
Addresses = addresses
};
return group;
}
private static bool IsAdmin
{
get
{
return WebItemSecurity.IsProductAdministrator(WebItemManager.MailProductID, SecurityContext.CurrentAccount.ID);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Xml;
using System.Diagnostics;
using System.Collections;
using System.Globalization;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace System.Xml
{
internal sealed partial class XmlSubtreeReader : XmlWrappingReader, IXmlLineInfo, IXmlNamespaceResolver
{
public override Task<string> GetValueAsync()
{
if (_useCurNode)
{
return Task.FromResult(_curNode.value);
}
else
{
return reader.GetValueAsync();
}
}
public override async Task<bool> ReadAsync()
{
switch (_state)
{
case State.Initial:
_useCurNode = false;
_state = State.Interactive;
ProcessNamespaces();
return true;
case State.Interactive:
_curNsAttr = -1;
_useCurNode = false;
reader.MoveToElement();
Debug.Assert(reader.Depth >= _initialDepth);
if (reader.Depth == _initialDepth)
{
if (reader.NodeType == XmlNodeType.EndElement ||
(reader.NodeType == XmlNodeType.Element && reader.IsEmptyElement))
{
_state = State.EndOfFile;
SetEmptyNode();
return false;
}
Debug.Assert(reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement);
}
if (await reader.ReadAsync().ConfigureAwait(false))
{
ProcessNamespaces();
return true;
}
else
{
SetEmptyNode();
return false;
}
case State.EndOfFile:
case State.Closed:
case State.Error:
return false;
case State.PopNamespaceScope:
_nsManager.PopScope();
goto case State.ClearNsAttributes;
case State.ClearNsAttributes:
_nsAttrCount = 0;
_state = State.Interactive;
goto case State.Interactive;
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
if (!await FinishReadElementContentAsBinaryAsync().ConfigureAwait(false))
{
return false;
}
return await ReadAsync().ConfigureAwait(false);
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
if (!await FinishReadContentAsBinaryAsync().ConfigureAwait(false))
{
return false;
}
return await ReadAsync().ConfigureAwait(false);
default:
Debug.Fail($"Unexpected state {_state}");
return false;
}
}
public override async Task SkipAsync()
{
switch (_state)
{
case State.Initial:
await ReadAsync().ConfigureAwait(false);
return;
case State.Interactive:
_curNsAttr = -1;
_useCurNode = false;
reader.MoveToElement();
Debug.Assert(reader.Depth >= _initialDepth);
if (reader.Depth == _initialDepth)
{
if (reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement)
{
// we are on root of the subtree -> skip to the end element and set to Eof state
if (await reader.ReadAsync().ConfigureAwait(false))
{
while (reader.NodeType != XmlNodeType.EndElement && reader.Depth > _initialDepth)
{
await reader.SkipAsync().ConfigureAwait(false);
}
}
}
Debug.Assert(reader.NodeType == XmlNodeType.EndElement ||
reader.NodeType == XmlNodeType.Element && reader.IsEmptyElement ||
reader.ReadState != ReadState.Interactive);
_state = State.EndOfFile;
SetEmptyNode();
return;
}
if (reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement)
{
_nsManager.PopScope();
}
await reader.SkipAsync().ConfigureAwait(false);
ProcessNamespaces();
Debug.Assert(reader.Depth >= _initialDepth);
return;
case State.Closed:
case State.EndOfFile:
return;
case State.PopNamespaceScope:
_nsManager.PopScope();
goto case State.ClearNsAttributes;
case State.ClearNsAttributes:
_nsAttrCount = 0;
_state = State.Interactive;
goto case State.Interactive;
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
if (await FinishReadElementContentAsBinaryAsync().ConfigureAwait(false))
{
await SkipAsync().ConfigureAwait(false);
}
break;
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
if (await FinishReadContentAsBinaryAsync().ConfigureAwait(false))
{
await SkipAsync().ConfigureAwait(false);
}
break;
case State.Error:
return;
default:
Debug.Fail($"Unexpected state {_state}");
return;
}
}
public override async Task<object> ReadContentAsObjectAsync()
{
try
{
InitReadContentAsType("ReadContentAsObject");
object value = await reader.ReadContentAsObjectAsync().ConfigureAwait(false);
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override async Task<string> ReadContentAsStringAsync()
{
try
{
InitReadContentAsType("ReadContentAsString");
string value = await reader.ReadContentAsStringAsync().ConfigureAwait(false);
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override async Task<object> ReadContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver)
{
try
{
InitReadContentAsType("ReadContentAs");
object value = await reader.ReadContentAsAsync(returnType, namespaceResolver).ConfigureAwait(false);
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override async Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return 0;
case State.ClearNsAttributes:
case State.PopNamespaceScope:
switch (NodeType)
{
case XmlNodeType.Element:
throw CreateReadContentAsException(nameof(ReadContentAsBase64));
case XmlNodeType.EndElement:
return 0;
case XmlNodeType.Attribute:
if (_curNsAttr != -1 && reader.CanReadBinaryContent)
{
CheckBuffer(buffer, index, count);
if (count == 0)
{
return 0;
}
if (_nsIncReadOffset == 0)
{
// called first time on this ns attribute
if (_binDecoder != null && _binDecoder is Base64Decoder)
{
_binDecoder.Reset();
}
else
{
_binDecoder = new Base64Decoder();
}
}
if (_nsIncReadOffset == _curNode.value.Length)
{
return 0;
}
_binDecoder.SetNextOutputBuffer(buffer, index, count);
_nsIncReadOffset += _binDecoder.Decode(_curNode.value, _nsIncReadOffset, _curNode.value.Length - _nsIncReadOffset);
return _binDecoder.DecodedCount;
}
goto case XmlNodeType.Text;
case XmlNodeType.Text:
Debug.Assert(AttributeCount > 0);
return await reader.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
default:
Debug.Fail($"Unexpected state {_state}");
return 0;
}
case State.Interactive:
_state = State.ReadContentAsBase64;
goto case State.ReadContentAsBase64;
case State.ReadContentAsBase64:
int read = await reader.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
if (read == 0)
{
_state = State.Interactive;
ProcessNamespaces();
}
return read;
case State.ReadContentAsBinHex:
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
public override async Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return 0;
case State.Interactive:
case State.PopNamespaceScope:
case State.ClearNsAttributes:
if (!await InitReadElementContentAsBinaryAsync(State.ReadElementContentAsBase64).ConfigureAwait(false))
{
return 0;
}
goto case State.ReadElementContentAsBase64;
case State.ReadElementContentAsBase64:
int read = await reader.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
if (read > 0 || count == 0)
{
return read;
}
if (NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
}
// pop namespace scope
_state = State.Interactive;
ProcessNamespaces();
// set eof state or move off the end element
if (reader.Depth == _initialDepth)
{
_state = State.EndOfFile;
SetEmptyNode();
}
else
{
await ReadAsync().ConfigureAwait(false);
}
return 0;
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
case State.ReadElementContentAsBinHex:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
public override async Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return 0;
case State.ClearNsAttributes:
case State.PopNamespaceScope:
switch (NodeType)
{
case XmlNodeType.Element:
throw CreateReadContentAsException(nameof(ReadContentAsBinHex));
case XmlNodeType.EndElement:
return 0;
case XmlNodeType.Attribute:
if (_curNsAttr != -1 && reader.CanReadBinaryContent)
{
CheckBuffer(buffer, index, count);
if (count == 0)
{
return 0;
}
if (_nsIncReadOffset == 0)
{
// called first time on this ns attribute
if (_binDecoder != null && _binDecoder is BinHexDecoder)
{
_binDecoder.Reset();
}
else
{
_binDecoder = new BinHexDecoder();
}
}
if (_nsIncReadOffset == _curNode.value.Length)
{
return 0;
}
_binDecoder.SetNextOutputBuffer(buffer, index, count);
_nsIncReadOffset += _binDecoder.Decode(_curNode.value, _nsIncReadOffset, _curNode.value.Length - _nsIncReadOffset);
return _binDecoder.DecodedCount;
}
goto case XmlNodeType.Text;
case XmlNodeType.Text:
Debug.Assert(AttributeCount > 0);
return await reader.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
default:
Debug.Fail($"Unexpected state {_state}");
return 0;
}
case State.Interactive:
_state = State.ReadContentAsBinHex;
goto case State.ReadContentAsBinHex;
case State.ReadContentAsBinHex:
int read = await reader.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
if (read == 0)
{
_state = State.Interactive;
ProcessNamespaces();
}
return read;
case State.ReadContentAsBase64:
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
public override async Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return 0;
case State.Interactive:
case State.PopNamespaceScope:
case State.ClearNsAttributes:
if (!await InitReadElementContentAsBinaryAsync(State.ReadElementContentAsBinHex).ConfigureAwait(false))
{
return 0;
}
goto case State.ReadElementContentAsBinHex;
case State.ReadElementContentAsBinHex:
int read = await reader.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
if (read > 0 || count == 0)
{
return read;
}
if (NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
}
// pop namespace scope
_state = State.Interactive;
ProcessNamespaces();
// set eof state or move off the end element
if (reader.Depth == _initialDepth)
{
_state = State.EndOfFile;
SetEmptyNode();
}
else
{
await ReadAsync().ConfigureAwait(false);
}
return 0;
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
case State.ReadElementContentAsBase64:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
public override Task<int> ReadValueChunkAsync(char[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return AsyncHelper.DoneTaskZero;
case State.ClearNsAttributes:
case State.PopNamespaceScope:
// ReadValueChunk implementation on added xmlns attributes
if (_curNsAttr != -1 && reader.CanReadValueChunk)
{
CheckBuffer(buffer, index, count);
int copyCount = _curNode.value.Length - _nsIncReadOffset;
if (copyCount > count)
{
copyCount = count;
}
if (copyCount > 0)
{
_curNode.value.CopyTo(_nsIncReadOffset, buffer, index, copyCount);
}
_nsIncReadOffset += copyCount;
return Task.FromResult(copyCount);
}
// Otherwise fall back to the case State.Interactive.
// No need to clean ns attributes or pop scope because the reader when ReadValueChunk is called
// - on Element errors
// - on EndElement errors
// - on Attribute does not move
// and that's all where State.ClearNsAttributes or State.PopnamespaceScope can be set
goto case State.Interactive;
case State.Interactive:
return reader.ReadValueChunkAsync(buffer, index, count);
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
throw new InvalidOperationException(SR.Xml_MixingReadValueChunkWithBinary);
default:
Debug.Fail($"Unexpected state {_state}");
return AsyncHelper.DoneTaskZero;
}
}
private async Task<bool> InitReadElementContentAsBinaryAsync(State binaryState)
{
if (NodeType != XmlNodeType.Element)
{
throw reader.CreateReadElementContentAsException(nameof(ReadElementContentAsBase64));
}
bool isEmpty = IsEmptyElement;
// move to content or off the empty element
if (!await ReadAsync().ConfigureAwait(false) || isEmpty)
{
return false;
}
// special-case child element and end element
switch (NodeType)
{
case XmlNodeType.Element:
throw new XmlException(SR.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
case XmlNodeType.EndElement:
// pop scope & move off end element
ProcessNamespaces();
await ReadAsync().ConfigureAwait(false);
return false;
}
Debug.Assert(_state == State.Interactive);
_state = binaryState;
return true;
}
private async Task<bool> FinishReadElementContentAsBinaryAsync()
{
Debug.Assert(_state == State.ReadElementContentAsBase64 || _state == State.ReadElementContentAsBinHex);
byte[] bytes = new byte[256];
if (_state == State.ReadElementContentAsBase64)
{
while (await reader.ReadContentAsBase64Async(bytes, 0, 256).ConfigureAwait(false) > 0) ;
}
else
{
while (await reader.ReadContentAsBinHexAsync(bytes, 0, 256).ConfigureAwait(false) > 0) ;
}
if (NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
}
// pop namespace scope
_state = State.Interactive;
ProcessNamespaces();
// check eof
if (reader.Depth == _initialDepth)
{
_state = State.EndOfFile;
SetEmptyNode();
return false;
}
// move off end element
return await ReadAsync().ConfigureAwait(false);
}
private async Task<bool> FinishReadContentAsBinaryAsync()
{
Debug.Assert(_state == State.ReadContentAsBase64 || _state == State.ReadContentAsBinHex);
byte[] bytes = new byte[256];
if (_state == State.ReadContentAsBase64)
{
while (await reader.ReadContentAsBase64Async(bytes, 0, 256).ConfigureAwait(false) > 0) ;
}
else
{
while (await reader.ReadContentAsBinHexAsync(bytes, 0, 256).ConfigureAwait(false) > 0) ;
}
_state = State.Interactive;
ProcessNamespaces();
// check eof
if (reader.Depth == _initialDepth)
{
_state = State.EndOfFile;
SetEmptyNode();
return false;
}
return true;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using hw.Helper;
using JetBrains.Annotations;
// ReSharper disable CheckNamespace
namespace hw.DebugFormatter
{
/// <summary> Summary description for Tracer. </summary>
[PublicAPI]
public static class Tracer
{
sealed class AssertionFailedException : Exception
{
public AssertionFailedException(string result)
: base(result) { }
}
sealed class BreakException : Exception { }
public const string VisualStudioLineFormat =
"{fileName}({lineNumber},{columnNumber},{lineNumberEnd},{columnNumberEnd}): {tagText}: ";
public static readonly Dumper Dumper = new Dumper();
public static bool IsBreakDisabled;
static readonly Writer Writer = new Writer();
[Obsolete("Use FilePosition")]
// ReSharper disable once IdentifierTypo
public static string FilePosn(this StackFrame sf, FilePositionTag tag)
=> FilePosition(sf, tag);
[Obsolete("Use FilePosition")]
// ReSharper disable once IdentifierTypo
public static string FilePosn(string fileName, int lineNumber, int columnNumber, FilePositionTag tag)
=> FilePosition(fileName, new TextPart
{
Start = new TextPosition
{
LineNumber = lineNumber, ColumnNumber = columnNumber
}
}, tag);
[Obsolete("Use FilePosition")]
// ReSharper disable once IdentifierTypo
public static string FilePosn
(
string fileName, int lineNumber, int columnNumber, int lineNumberEnd, int columnNumberEnd
, FilePositionTag tag
)
=> FilePosition(fileName, new TextPart
{
Start = new TextPosition
{
LineNumber = lineNumber, ColumnNumber = columnNumber
}
, End = new TextPosition
{
LineNumber = lineNumberEnd, ColumnNumber = columnNumberEnd
}
}, tag);
[Obsolete("Use FilePosition")]
// ReSharper disable once IdentifierTypo
public static string FilePosn
(
string fileName,
int lineNumber,
int columnNumber,
int lineNumberEnd,
int columnNumberEnd,
string tagText
)
=> FilePosition(fileName, new TextPart
{
Start = new TextPosition
{
LineNumber = lineNumber, ColumnNumber = columnNumber
}
, End = new TextPosition
{
LineNumber = lineNumberEnd, ColumnNumber = columnNumberEnd
}
}
, tagText);
/// <summary>
/// creates the file(line,col) string to be used with "Edit.GotoNextLocation" command of IDE
/// </summary>
/// <param name="stackFrame"> the stack frame where the location is stored </param>
/// <param name="tag"> </param>
/// <returns> the "FileName(lineNumber,ColNr): tag: " string </returns>
public static string FilePosition(StackFrame stackFrame, FilePositionTag tag)
{
// ReSharper disable once StringLiteralTypo
if(stackFrame.GetFileLineNumber() == 0)
return "<nofile> " + tag;
return FilePosition
(
stackFrame.GetFileName(),
new TextPart
{
Start = new TextPosition
{
LineNumber = stackFrame.GetFileLineNumber() - 1, ColumnNumber = stackFrame.GetFileColumnNumber()
}
}
,
tag
);
}
/// <summary>
/// creates the file(line,col) string to be used with "Edit.GotoNextLocation" command of IDE
/// </summary>
public static string FilePosition
(
string fileName,
int lineNumber,
int columnNumber,
FilePositionTag tag
)
=> FilePosition(fileName
, new TextPart
{
Start = new TextPosition
{
LineNumber = lineNumber, ColumnNumber = columnNumber
}
}
, tag);
/// <summary>
/// creates the file(line,col) string to be used with "Edit.GotoNextLocation" command of IDE
/// </summary>
public static string FilePosition
(
string fileName,
int lineNumber,
int columnNumber,
int lineNumberEnd,
int columnNumberEnd,
FilePositionTag tag
)
=> FilePosition(fileName
, new TextPart
{
Start = new TextPosition
{
LineNumber = lineNumber, ColumnNumber = columnNumber
}
, End = new TextPosition
{
LineNumber = lineNumberEnd, ColumnNumber = columnNumberEnd
}
}
, tag);
/// <summary>
/// creates the file(line,col) string to be used with "Edit.GotoNextLocation" command of IDE
/// </summary>
public static string FilePosition
(
string fileName,
int lineNumber,
int columnNumber,
int lineNumberEnd,
int columnNumberEnd,
string tagText
)
=> FilePosition(fileName
, new TextPart
{
Start = new TextPosition {LineNumber = lineNumber, ColumnNumber = columnNumber}
, End = new TextPosition {LineNumber = lineNumberEnd, ColumnNumber = columnNumberEnd}
}
, tagText);
public static string FilePosition(string fileName, TextPart textPart, FilePositionTag tag)
=> FilePosition(fileName, textPart, tag.ToString());
public static string FilePosition(string fileName, TextPart textPart, string tagText)
{
var start = textPart?.Start ?? new TextPosition {LineNumber = 1, ColumnNumber = 1};
var end = textPart?.End ?? start;
return VisualStudioLineFormat
.Replace("{fileName}", fileName)
.Replace("{lineNumber}", (start.LineNumber + 1).ToString())
.Replace("{columnNumber}", start.ColumnNumber.ToString())
.Replace("{lineNumberEnd}", (end.LineNumber + 1).ToString())
.Replace("{columnNumberEnd}", end.ColumnNumber.ToString())
.Replace("{tagText}", tagText);
}
/// <summary>
/// creates a string to inspect a method
/// </summary>
/// <param name="methodBase"> the method </param>
/// <param name="showParam"> controls if parameter list is appended </param>
/// <returns> string to inspect a method </returns>
public static string DumpMethod(this MethodBase methodBase, bool showParam)
{
var result = methodBase.DeclaringType.PrettyName() + ".";
result += methodBase.Name;
if(!showParam)
return result;
if(methodBase.IsGenericMethod)
{
result += "<";
result += methodBase.GetGenericArguments().Select(t => t.PrettyName()).Stringify(", ");
result += ">";
}
result += "(";
for(int parameterIndex = 0, n = methodBase.GetParameters().Length; parameterIndex < n; parameterIndex++)
{
if(parameterIndex != 0)
result += ", ";
var parameterInfo = methodBase.GetParameters()[parameterIndex];
result += parameterInfo.ParameterType.PrettyName();
result += " ";
result += parameterInfo.Name;
}
result += ")";
return result;
}
/// <summary>
/// creates a string to inspect the method call contained in current call stack
/// </summary>
/// <param name="stackFrameDepth"> the index of stack frame </param>
/// <param name="tag"> </param>
/// <param name="showParam"> controls if parameter list is appended </param>
/// <returns> string to inspect the method call </returns>
public static string MethodHeader
(
FilePositionTag tag = FilePositionTag.Debug,
bool showParam = false,
int stackFrameDepth = 0
)
{
var stackFrame = new StackTrace(true).GetFrame(stackFrameDepth + 1);
return FilePosition(stackFrame, tag) + DumpMethod(stackFrame.GetMethod(), showParam);
}
public static string CallingMethodName(int stackFrameDepth = 0)
{
var stackFrame = new StackTrace(true).GetFrame(stackFrameDepth + 1);
return DumpMethod(stackFrame.GetMethod(), false);
}
public static string StackTrace(FilePositionTag tag, int stackFrameDepth = 0)
{
var stackTrace = new StackTrace(true);
var result = "";
for(var frameDepth = stackFrameDepth + 1; frameDepth < stackTrace.FrameCount; frameDepth++)
{
var stackFrame = stackTrace.GetFrame(frameDepth);
var filePosition = FilePosition(stackFrame, tag) + DumpMethod(stackFrame.GetMethod(), false);
result += "\n" + filePosition;
}
return result;
}
/// <summary>
/// write a line to debug output
/// </summary>
/// <param name="text"> the text </param>
[Obsolete("Use Log")]
public static void Line(string text) => Writer.ThreadSafeWrite(text, true);
/// <summary>
/// write a line to debug output
/// </summary>
/// <param name="text"> the text </param>
[Obsolete("Use LogLinePart")]
public static void LinePart(string text) => Writer.ThreadSafeWrite(text, false);
/// <summary>
/// write a line to debug output, flagged with FileName(lineNumber,ColNr): Method (without parameter list)
/// </summary>
/// <param name="text"> the text </param>
/// <param name="flagText"> </param>
/// <param name="showParam"></param>
/// <param name="stackFrameDepth"> The stack frame depth. </param>
[IsLoggingFunction]
public static void FlaggedLine
(
this string text,
FilePositionTag flagText = FilePositionTag.Debug,
bool showParam = false,
int stackFrameDepth = 0
)
{
var methodHeader = MethodHeader
(
flagText,
stackFrameDepth: stackFrameDepth + 1,
showParam: showParam);
Log(methodHeader + " " + text);
}
[IsLoggingFunction]
public static void Log
(
this string text,
FilePositionTag flagText,
bool showParam = false,
int stackFrameDepth = 0
)
{
var methodHeader = MethodHeader
(
flagText,
stackFrameDepth: stackFrameDepth + 1,
showParam: showParam);
Log(methodHeader + " " + text);
}
/// <summary>
/// generic dump function by use of reflection
/// </summary>
/// <param name="target"> the object to dump </param>
/// <returns> </returns>
public static string Dump(object target) => Dumper.Dump(target);
/// <summary>
/// generic dump function by use of reflection
/// </summary>
/// <param name="target"> the object to dump </param>
/// <returns> </returns>
public static string DumpData(object target) => target == null? "" : Dumper.DumpData(target);
/// <summary>
/// Generic dump function by use of reflection.
/// </summary>
/// <param name="name">Identifies the the value in result. Recommended use is nameof($value$), but any string is possible.</param>
/// <param name="value">The object, that will be dumped, by use of <see cref="DumpData(object)" />.</param>
/// <returns>A string according to pattern $name$ = $value$</returns>
[DebuggerHidden]
public static string DumpValue(this string name, object value)
=> DumpData("", new[] {name, value}, 1);
/// <summary>
/// creates a string to inspect the method call contained in stack. Runtime parameters are dumped too.
/// </summary>
/// <param name="parameter"> parameter objects list for the frame </param>
public static void DumpStaticMethodWithData(params object[] parameter)
{
var result = DumpMethodWithData("", null, parameter, 1);
Log(result);
}
/// <summary>
/// Dumps the data.
/// </summary>
/// <param name="text"> The text. </param>
/// <param name="data"> The data, as name/value pair. </param>
/// <param name="stackFrameDepth"> The stack stackFrameDepth. </param>
/// <returns> </returns>
public static string DumpData(string text, object[] data, int stackFrameDepth = 0)
{
var stackFrame = new StackTrace(true).GetFrame(stackFrameDepth + 1);
return FilePosition
(stackFrame, FilePositionTag.Debug) +
DumpMethod(stackFrame.GetMethod(), true) +
text +
DumpMethodWithData(null, data).Indent();
}
public static string IsSetTo(this string name, object value) => name + "=" + Dump(value);
/// <summary>
/// Function used for condition al break
/// </summary>
/// <param name="cond"> The cond. </param>
/// <param name="getText"> The data. </param>
/// <param name="stackFrameDepth"> The stack frame depth. </param>
/// <returns> </returns>
[DebuggerHidden]
[IsLoggingFunction]
public static void ConditionalBreak(string cond, Func<string> getText = null, int stackFrameDepth = 0)
{
var result = "Conditional break: " + cond + "\nData: " + (getText == null? "" : getText());
FlaggedLine(result, stackFrameDepth: stackFrameDepth + 1);
TraceBreak();
}
/// <summary>
/// Check boolean expression
/// </summary>
/// <param name="b">
/// if set to <c>true</c> [b].
/// </param>
/// <param name="getText"> The text. </param>
/// <param name="stackFrameDepth"> The stack frame depth. </param>
[DebuggerHidden]
public static void ConditionalBreak(bool b, Func<string> getText = null, int stackFrameDepth = 0)
{
if(b)
ConditionalBreak("", getText, stackFrameDepth + 1);
}
/// <summary>
/// Throws the assertion failed.
/// </summary>
/// <param name="cond"> The cond. </param>
/// <param name="getText"> The data. </param>
/// <param name="stackFrameDepth"> The stack frame depth. </param>
/// created 15.10.2006 18:04
[DebuggerHidden]
public static void ThrowAssertionFailed(string cond, Func<string> getText = null, int stackFrameDepth = 0)
{
var result = AssertionFailed(cond, getText, stackFrameDepth + 1);
throw new AssertionFailedException(result);
}
/// <summary>
/// Function used in assertions
/// </summary>
/// <param name="cond"> The cond. </param>
/// <param name="getText"> The data. </param>
/// <param name="stackFrameDepth"> The stack frame depth. </param>
/// <returns> </returns>
[DebuggerHidden]
[IsLoggingFunction]
public static string AssertionFailed(string cond, Func<string> getText = null, int stackFrameDepth = 0)
{
var result = "Assertion Failed: " + cond + "\nData: " + (getText == null? "" : getText());
FlaggedLine(result, stackFrameDepth: stackFrameDepth + 1);
AssertionBreak(result);
return result;
}
/// <summary>
/// Check boolean expression
/// </summary>
/// <param name="b">
/// if set to <c>true</c> [b].
/// </param>
/// <param name="getText"> The text. </param>
/// <param name="stackFrameDepth"> The stack frame depth. </param>
[DebuggerHidden]
[ContractAnnotation("b: false => halt")]
public static void Assert(this bool b, Func<string> getText = null, int stackFrameDepth = 0)
{
if(b)
return;
AssertionFailed("", getText, stackFrameDepth + 1);
}
[DebuggerHidden]
[ContractAnnotation("b: false => halt")]
public static void Assert(this bool b, string s) => Assert(b, () => s, 1);
[DebuggerHidden]
public static void TraceBreak()
{
if(!Debugger.IsAttached)
return;
if(IsBreakDisabled)
throw new BreakException();
Debugger.Break();
}
/// <summary>
/// Check expression
/// </summary>
/// <param name="b">
/// if not null.
/// </param>
/// <param name="getText"> Message in case of fail. </param>
/// <param name="stackFrameDepth"> The stack frame depth. </param>
[DebuggerHidden]
[ContractAnnotation("b: null => halt")]
public static void AssertIsNotNull(this object b, Func<string> getText = null, int stackFrameDepth = 0)
{
if(b!= null)
return;
AssertionFailed("", getText, stackFrameDepth + 1);
}
/// <summary>
/// Check expression
/// </summary>
/// <param name="b">
/// if null.
/// </param>
/// <param name="getText"> Message in case of fail. </param>
/// <param name="stackFrameDepth"> The stack frame depth. </param>
[DebuggerHidden]
[ContractAnnotation("b: notnull => halt")]
public static void AssertIsNull(this object b, Func<string> getText = null, int stackFrameDepth = 0)
{
if(b== null)
return;
AssertionFailed("", getText, stackFrameDepth + 1);
}
public static int CurrentFrameCount(int stackFrameDepth) => new StackTrace(true).FrameCount - stackFrameDepth;
[DebuggerHidden]
public static void LaunchDebugger() => Debugger.Launch();
public static void IndentStart() => Writer.IndentStart();
public static void IndentEnd() => Writer.IndentEnd();
[Obsolete("Use Log")]
public static void WriteLine(this string value) => Log(value);
[Obsolete("Use LogLinePart")]
public static void WriteLinePart(this string value) => LogLinePart(value);
[IsLoggingFunction]
public static void Log(this string value) => Writer.ThreadSafeWrite(value, true);
[IsLoggingFunction]
public static void LogLinePart(this string value) => Writer.ThreadSafeWrite(value, false);
public static string DumpMethodWithData
(string text, object thisObject, object[] parameter, int stackFrameDepth = 0)
{
var stackFrame = new StackTrace(true).GetFrame(stackFrameDepth + 1);
return FilePosition
(stackFrame, FilePositionTag.Debug) +
DumpMethod(stackFrame.GetMethod(), true) +
text +
DumpMethodWithData(stackFrame.GetMethod(), thisObject, parameter).Indent();
}
static string DumpMethodWithData(MethodBase methodBase, object target, object[] parameters)
{
var result = "\n";
result += IsSetTo("this", target);
result += "\n";
result += DumpMethodWithData(methodBase.GetParameters(), parameters);
return result;
}
static string DumpMethodWithData(ParameterInfo[] parameterInfos, object[] parameters)
{
var result = "";
var parameterCount = parameterInfos?.Length ?? 0;
for(var index = 0; index < parameterCount; index++)
{
if(index > 0)
result += "\n";
Assert(parameterInfos != null);
Assert(parameterInfos[index] != null);
result += IsSetTo(parameterInfos[index].Name, parameters[index]);
}
for(var index = parameterCount; index < parameters.Length; index += 2)
{
result += "\n";
result += IsSetTo((string)parameters[index], parameters[index + 1]);
}
return result;
}
[DebuggerHidden]
static void AssertionBreak(string result)
{
if(!Debugger.IsAttached || IsBreakDisabled)
throw new AssertionFailedException(result);
Debugger.Break();
}
}
[PublicAPI]
public enum FilePositionTag
{
Debug
, Output
, Query
, Test
, Profiler
}
interface IDumpExceptAttribute
{
bool IsException(object target);
}
public abstract class DumpAttributeBase : Attribute { }
public class IsLoggingFunction : Attribute { }
}
| |
// 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,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.Interpreter {
class DerivedInterpreterFactory : PythonInterpreterFactoryWithDatabase {
readonly PythonInterpreterFactoryWithDatabase _base;
bool _deferRefreshIsCurrent;
string _description;
PythonTypeDatabase _baseDb;
bool _baseHasRefreshed;
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",
Justification = "call to RefreshIsCurrent is required for back compat")]
public DerivedInterpreterFactory(
PythonInterpreterFactoryWithDatabase baseFactory,
InterpreterFactoryCreationOptions options
) : base(
options.Id,
options.Description,
new InterpreterConfiguration(
options.PrefixPath,
options.InterpreterPath,
options.WindowInterpreterPath,
options.LibraryPath,
options.PathEnvironmentVariableName,
options.Architecture,
options.LanguageVersion,
InterpreterUIMode.CannotBeDefault | InterpreterUIMode.CannotBeConfigured
),
options.WatchLibraryForNewModules
) {
if (baseFactory.Configuration.Version != options.LanguageVersion) {
throw new ArgumentException("Language versions do not match", "options");
}
_base = baseFactory;
_base.IsCurrentChanged += Base_IsCurrentChanged;
_base.NewDatabaseAvailable += Base_NewDatabaseAvailable;
_description = options.Description;
if (Volatile.Read(ref _deferRefreshIsCurrent)) {
// This rare race condition is due to a design flaw that is in
// shipped public API and cannot be fixed without breaking
// compatibility with 3rd parties.
RefreshIsCurrent();
}
}
private void Base_NewDatabaseAvailable(object sender, EventArgs e) {
if (_baseDb != null) {
_baseDb = null;
_baseHasRefreshed = true;
}
OnNewDatabaseAvailable();
OnIsCurrentChanged();
}
protected override void Dispose(bool disposing) {
_base.IsCurrentChanged -= Base_IsCurrentChanged;
_base.NewDatabaseAvailable -= Base_NewDatabaseAvailable;
base.Dispose(disposing);
}
public IPythonInterpreterFactory BaseInterpreter {
get {
return _base;
}
}
public override string Description {
get {
return _description;
}
}
public void SetDescription(string value) {
_description = value;
}
public override IPythonInterpreter MakeInterpreter(PythonInterpreterFactoryWithDatabase factory) {
return _base.MakeInterpreter(factory);
}
private static bool ShouldIncludeGlobalSitePackages(string prefixPath, string libPath) {
var cfgFile = Path.Combine(prefixPath, "pyvenv.cfg");
if (File.Exists(cfgFile)) {
try {
var lines = File.ReadAllLines(cfgFile);
return !lines
.Select(line => Regex.Match(
line,
"^include-system-site-packages\\s*=\\s*false",
RegexOptions.IgnoreCase
))
.Any(m => m != null && m.Success);
} catch (IOException) {
} catch (UnauthorizedAccessException) {
} catch (System.Security.SecurityException) {
}
return false;
}
var prefixFile = Path.Combine(libPath, "orig-prefix.txt");
var markerFile = Path.Combine(libPath, "no-global-site-packages.txt");
if (File.Exists(prefixFile)) {
return !File.Exists(markerFile);
}
return false;
}
public override PythonTypeDatabase MakeTypeDatabase(string databasePath, bool includeSitePackages = true) {
if (_baseDb == null && _base.IsCurrent) {
var includeBaseSitePackages = ShouldIncludeGlobalSitePackages(
Configuration.PrefixPath,
Configuration.LibraryPath
);
_baseDb = _base.GetCurrentDatabase(includeBaseSitePackages);
}
if (!IsCurrent || !Directory.Exists(databasePath)) {
return _baseDb;
}
var paths = new List<string> { databasePath };
if (includeSitePackages) {
try {
paths.AddRange(Directory.EnumerateDirectories(databasePath));
} catch (IOException) {
} catch (UnauthorizedAccessException) {
}
}
return new PythonTypeDatabase(this, paths, _baseDb);
}
public override void GenerateDatabase(GenerateDatabaseOptions options, Action<int> onExit = null) {
if (!Directory.Exists(Configuration.LibraryPath)) {
return;
}
// Create and mark the DB directory as hidden
try {
var dbDir = Directory.CreateDirectory(DatabasePath);
dbDir.Attributes |= FileAttributes.Hidden;
} catch (ArgumentException) {
} catch (IOException) {
} catch (UnauthorizedAccessException) {
}
var req = new PythonTypeDatabaseCreationRequest {
Factory = this,
OutputPath = DatabasePath,
SkipUnchanged = options.HasFlag(GenerateDatabaseOptions.SkipUnchanged),
DetectLibraryPath = !AssumeSimpleLibraryLayout
};
req.ExtraInputDatabases.Add(_base.DatabasePath);
_baseHasRefreshed = false;
if (_base.IsCurrent) {
base.GenerateDatabase(req, onExit);
} else {
req.WaitFor = _base;
req.SkipUnchanged = false;
// Clear out the existing base database, since we're going to
// need to reload it again. This also means that when
// NewDatabaseAvailable is raised, we are expecting it and won't
// incorrectly set _baseHasRefreshed to true again.
_baseDb = null;
// Start our analyzer first, since we will wait up to a minute
// for our base analyzer to start (which may cause a one minute
// delay if it completes before we start, but that is unlikely).
base.GenerateDatabase(req, onExit);
_base.GenerateDatabase(GenerateDatabaseOptions.SkipUnchanged);
}
}
public override string DatabasePath {
get {
return Path.Combine(
Configuration.PrefixPath,
".ptvs"
);
}
}
public override bool IsCurrent {
get {
return !_baseHasRefreshed && _base.IsCurrent && base.IsCurrent;
}
}
public override bool IsCheckingDatabase {
get {
return base.IsCheckingDatabase || _base.IsCheckingDatabase;
}
}
private void Base_IsCurrentChanged(object sender, EventArgs e) {
base.OnIsCurrentChanged();
}
public override void RefreshIsCurrent() {
if (_base == null) {
// This rare race condition is due to a design flaw that is in
// shipped public API and cannot be fixed without breaking
// compatibility with 3rd parties.
Volatile.Write(ref _deferRefreshIsCurrent, true);
return;
}
_base.RefreshIsCurrent();
base.RefreshIsCurrent();
}
public override string GetFriendlyIsCurrentReason(IFormatProvider culture) {
if (_baseHasRefreshed) {
return "Base interpreter has been refreshed";
} else if (!_base.IsCurrent) {
return string.Format(culture,
"Base interpreter {0} is out of date{1}{1}{2}",
_base.Description,
Environment.NewLine,
_base.GetFriendlyIsCurrentReason(culture));
}
return base.GetFriendlyIsCurrentReason(culture);
}
public override string GetIsCurrentReason(IFormatProvider culture) {
if (_baseHasRefreshed) {
return "Base interpreter has been refreshed";
} else if (!_base.IsCurrent) {
return string.Format(culture,
"Base interpreter {0} is out of date{1}{1}{2}",
_base.Description,
Environment.NewLine,
_base.GetIsCurrentReason(culture));
}
return base.GetIsCurrentReason(culture);
}
public static IPythonInterpreterFactory FindBaseInterpreterFromVirtualEnv(
string prefixPath,
string libPath,
IInterpreterOptionsService service
) {
string basePath = GetOrigPrefixPath(prefixPath, libPath);
if (Directory.Exists(basePath)) {
return service.Interpreters.FirstOrDefault(interp =>
CommonUtils.IsSamePath(interp.Configuration.PrefixPath, basePath)
);
}
return null;
}
public static string GetOrigPrefixPath(string prefixPath, string libPath = null) {
string basePath = null;
if (!Directory.Exists(prefixPath)) {
return null;
}
var cfgFile = Path.Combine(prefixPath, "pyvenv.cfg");
if (File.Exists(cfgFile)) {
try {
var lines = File.ReadAllLines(cfgFile);
basePath = lines
.Select(line => Regex.Match(line, @"^home\s*=\s*(?<path>.+)$", RegexOptions.IgnoreCase))
.Where(m => m != null && m.Success)
.Select(m => m.Groups["path"])
.Where(g => g != null && g.Success)
.Select(g => g.Value)
.FirstOrDefault(CommonUtils.IsValidPath);
} catch (IOException) {
} catch (UnauthorizedAccessException) {
} catch (System.Security.SecurityException) {
}
}
if (string.IsNullOrEmpty(libPath)) {
libPath = FindLibPath(prefixPath);
}
if (!Directory.Exists(libPath)) {
return null;
}
var prefixFile = Path.Combine(libPath, "orig-prefix.txt");
if (basePath == null && File.Exists(prefixFile)) {
try {
var lines = File.ReadAllLines(prefixFile);
basePath = lines.FirstOrDefault(CommonUtils.IsValidPath);
} catch (IOException) {
} catch (UnauthorizedAccessException) {
} catch (System.Security.SecurityException) {
}
}
return basePath;
}
public static string FindLibPath(string prefixPath) {
// Find site.py to find the library
var libPath = CommonUtils.FindFile(prefixPath, "site.py", firstCheck: new[] { "Lib" });
if (!File.Exists(libPath)) {
// Python 3.3 venv does not add site.py, but always puts the
// library in prefixPath\Lib
libPath = Path.Combine(prefixPath, "Lib");
if (!Directory.Exists(libPath)) {
return null;
}
} else {
libPath = Path.GetDirectoryName(libPath);
}
return libPath;
}
}
}
| |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.
//***************************************************************************
// HOW TO USE THIS FILE
//
// If you need access to a Win32 API that is not exposed, simply uncomment
// it in one of the following files:
//
// NativeMethods.cs
// UnsafeNativeMethods.cs
// SafeNativeMethods.cs
//
// Only uncomment what you need to avoid code bloat.
//
// DO NOT adjust the visibility of anything in these files. They are marked
// internal on pupose.
//***************************************************************************
using System;
using System.Runtime.InteropServices;
namespace MS.Win32
{
internal class NativeMethods
{
internal const int WM_USER = 0x0400;
internal const int SMTO_BLOCK = 0x0001;
// ListView rectangle related constants
internal const int LVIR_BOUNDS = 0;
internal const int LVIR_ICON = 1;
internal const int LVIR_LABEL = 2;
internal const int LVIR_SELECTBOUNDS = 3;
// List-view messages
internal const int LVM_FIRST = 0x1000;
internal const int LVM_GETITEMCOUNT = LVM_FIRST + 4;
internal const int LVM_GETNEXTITEM = LVM_FIRST + 12;
internal const int LVM_GETITEMRECT = LVM_FIRST + 14;
internal const int LVM_GETITEMPOSITION = LVM_FIRST + 16;
internal const int LVM_ENSUREVISIBLE = LVM_FIRST + 19;
internal const int LVM_SCROLL = LVM_FIRST + 20;
internal const int LVM_GETHEADER = LVM_FIRST + 31;
internal const int LVM_GETITEMSTATE = LVM_FIRST + 44;
internal const int LVM_SETITEMSTATE = LVM_FIRST + 43;
internal const int LVM_GETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 55;
internal const int LVM_GETSUBITEMRECT = LVM_FIRST + 56;
internal const int LVM_SUBITEMHITTEST = LVM_FIRST + 57;
internal const int LVM_APPROXIMATEVIEWRECT = LVM_FIRST + 64;
internal const int LVM_GETITEMW = LVM_FIRST + 75;
internal const int LVM_GETTOOLTIPS = LVM_FIRST + 78;
internal const int LVM_EDITLABEL = LVM_FIRST + 118;
internal const int LVM_GETVIEW = LVM_FIRST + 143;
internal const int LVM_SETVIEW = LVM_FIRST + 142;
internal const int LVM_GETGROUPINFO = LVM_FIRST + 149;
internal const int LVM_GETGROUPMETRICS = LVM_FIRST + 156;
internal const int LVM_HASGROUP = LVM_FIRST + 161;
internal const int LVM_ISGROUPVIEWENABLED = LVM_FIRST + 175;
// Listbox messages
internal const int LB_ERR = -1;
internal const int LB_SETSEL = 0x0185;
internal const int LB_SETCURSEL = 0x0186;
internal const int LB_GETSEL = 0x0187;
internal const int LB_GETCURSEL = 0x0188;
internal const int LB_GETTEXT = 0x0189;
internal const int LB_GETTEXTLEN = 0x018A;
internal const int LB_GETCOUNT = 0x018B;
internal const int LB_GETSELCOUNT = 0x0190;
internal const int LB_SETTOPINDEX = 0x0197;
internal const int LB_GETITEMRECT = 0x0198;
internal const int LB_GETITEMDATA = 0x0199;
internal const int LB_SETCARETINDEX = 0x019E;
internal const int LB_GETCARETINDEX = 0x019F;
internal const int LB_ITEMFROMPOINT = 0x01A9;
// SpinControl
internal const int UDM_GETRANGE = (WM_USER + 102);
internal const int UDM_SETPOS = (WM_USER + 103);
internal const int UDM_GETPOS = (WM_USER + 104);
internal const int UDM_GETBUDDY = (WM_USER + 106);
// System Metrics
internal const int SM_CXSCREEN = 0;
internal const int SM_CYSCREEN = 1;
internal const int SM_CXVSCROLL = 2;
internal const int SM_CYHSCROLL = 3;
internal const int SM_CYCAPTION = 4;
internal const int SM_CXBORDER = 5;
internal const int SM_CYBORDER = 6;
internal const int SM_CYVTHUMB = 9;
internal const int SM_CXHTHUMB = 10;
internal const int SM_CXICON = 11;
internal const int SM_CYICON = 12;
internal const int SM_CXCURSOR = 13;
internal const int SM_CYCURSOR = 14;
internal const int SM_CYMENU = 15;
internal const int SM_CYKANJIWINDOW = 18;
internal const int SM_MOUSEPRESENT = 19;
internal const int SM_CYVSCROLL = 20;
internal const int SM_CXHSCROLL = 21;
internal const int SM_DEBUG = 22;
internal const int SM_SWAPBUTTON = 23;
internal const int SM_CXMIN = 28;
internal const int SM_CYMIN = 29;
internal const int SM_CXSIZE = 30;
internal const int SM_CYSIZE = 31;
internal const int SM_CXFRAME = 32;
internal const int SM_CYFRAME = 33;
internal const int SM_CXMINTRACK = 34;
internal const int SM_CYMINTRACK = 35;
internal const int SM_CXDOUBLECLK = 36;
internal const int SM_CYDOUBLECLK = 37;
internal const int SM_CXICONSPACING = 38;
internal const int SM_CYICONSPACING = 39;
internal const int SM_MENUDROPALIGNMENT = 40;
internal const int SM_PENWINDOWS = 41;
internal const int SM_DBCSENABLED = 42;
internal const int SM_CMOUSEBUTTONS = 43;
internal const int SM_CXFIXEDFRAME = 7;
internal const int SM_CYFIXEDFRAME = 8;
internal const int SM_SECURE = 44;
internal const int SM_CXEDGE = 45;
internal const int SM_CYEDGE = 46;
internal const int SM_CXMINSPACING = 47;
internal const int SM_CYMINSPACING = 48;
internal const int SM_CXSMICON = 49;
internal const int SM_CYSMICON = 50;
internal const int SM_CYSMCAPTION = 51;
internal const int SM_CXSMSIZE = 52;
internal const int SM_CYSMSIZE = 53;
internal const int SM_CXMENUSIZE = 54;
internal const int SM_CYMENUSIZE = 55;
internal const int SM_ARRANGE = 56;
internal const int SM_CXMINIMIZED = 57;
internal const int SM_CYMINIMIZED = 58;
internal const int SM_CXMAXTRACK = 59;
internal const int SM_CYMAXTRACK = 60;
internal const int SM_CXMAXIMIZED = 61;
internal const int SM_CYMAXIMIZED = 62;
internal const int SM_NETWORK = 63;
internal const int SM_CLEANBOOT = 67;
internal const int SM_CXDRAG = 68;
internal const int SM_CYDRAG = 69;
internal const int SM_SHOWSOUNDS = 70;
internal const int SM_CXMENUCHECK = 71;
internal const int SM_CYMENUCHECK = 72;
internal const int SM_MIDEASTENABLED = 74;
internal const int SM_MOUSEWHEELPRESENT = 75;
internal const int SM_XVIRTUALSCREEN = 76;
internal const int SM_YVIRTUALSCREEN = 77;
internal const int SM_CXVIRTUALSCREEN = 78;
internal const int SM_CYVIRTUALSCREEN = 79;
internal const int S_OK = 0x00000000;
internal const int S_FALSE = 0x00000001;
// Editbox styles
internal const int ES_READONLY = 0x0800;
internal const int ES_NUMBER = 0x2000;
// Editbox messages
internal const int WM_SETTEXT = 0x000C;
internal const int EM_GETLIMITTEXT = 0x00D5;
internal const int WM_GETTEXTLENGTH = 0x000E;
internal const int EM_LIMITTEXT = 0x00C5;
[DllImport("User32.dll", CharSet = CharSet.Unicode)]
internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);
internal const int GWL_EXSTYLE = (-20);
internal const int WS_EX_LAYOUTRTL = 0x00400000; // Right to left mirroring
public struct Point
{
internal double _x;
internal double _y;
/// <summary>
/// Constructor which accepts the X and Y values
/// </summary>
/// <param name="x">The value for the X coordinate of the new Point</param>
/// <param name="y">The value for the Y coordinate of the new Point</param>
public Point(double x, double y)
{
_x = x;
_y = y;
}
/// <summary>
/// X - Default value is 0.
/// </summary>
public double X
{
get{return _x;}
set{_x = value;}
}
/// <summary>
/// Y - Default value is 0.
/// </summary>
public double Y
{
get{return _y;}
set{_y = value;}
}
}
[StructLayout(LayoutKind.Sequential)]
public struct HWND
{
public IntPtr h;
public static HWND Cast(IntPtr h)
{
HWND hTemp = new HWND();
hTemp.h = h;
return hTemp;
}
public static implicit operator IntPtr(HWND h)
{
return h.h;
}
public static HWND NULL
{
get
{
HWND hTemp = new HWND();
hTemp.h = IntPtr.Zero;
return hTemp;
}
}
public static bool operator ==(HWND hl, HWND hr)
{
return hl.h == hr.h;
}
public static bool operator !=(HWND hl, HWND hr)
{
return hl.h != hr.h;
}
override public bool Equals(object oCompare)
{
HWND hr = Cast((HWND)oCompare);
return h == hr.h;
}
public override int GetHashCode()
{
return (int)h;
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct SIZE
{
internal int cx;
internal int cy;
internal SIZE(int cx, int cy)
{
this.cx = cx;
this.cy = cy;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
public RECT(int left, int top, int right, int bottom)
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
public bool IsEmpty
{
get
{
return left >= right || top >= bottom;
}
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Rect
{
internal int left;
internal int top;
internal int right;
internal int bottom;
internal Win32Rect(int left, int top, int right, int bottom)
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
internal Win32Rect(Win32Rect rcSrc)
{
this.left = rcSrc.left;
this.top = rcSrc.top;
this.right = rcSrc.right;
this.bottom = rcSrc.bottom;
}
internal bool IsEmpty
{
get
{
return left >= right || top >= bottom;
}
}
static internal Win32Rect Empty
{
get
{
return new Win32Rect(0, 0, 0, 0);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct HWND
{
public IntPtr h;
public static HWND Cast(IntPtr h)
{
HWND hTemp = new HWND();
hTemp.h = h;
return hTemp;
}
public static implicit operator IntPtr(HWND h)
{
return h.h;
}
public static HWND NULL
{
get
{
HWND hTemp = new HWND();
hTemp.h = IntPtr.Zero;
return hTemp;
}
}
public static bool operator ==(HWND hl, HWND hr)
{
return hl.h == hr.h;
}
public static bool operator !=(HWND hl, HWND hr)
{
return hl.h != hr.h;
}
override public bool Equals(object oCompare)
{
HWND hr = Cast((HWND)oCompare);
return h == hr.h;
}
public override int GetHashCode()
{
return (int)h;
}
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal sealed class OSVERSIONINFOEX
{
public OSVERSIONINFOEX()
{
osVersionInfoSize = (int)Marshal.SizeOf(this);
}
// The OSVersionInfoSize field must be set to SecurityHelper.SizeOf(this)
public int osVersionInfoSize = 0;
public int majorVersion = 0;
public int minorVersion = 0;
public int buildNumber = 0;
public int platformId = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string csdVersion = null;
public short servicePackMajor = 0;
public short servicePackMinor = 0;
public short suiteMask = 0;
public byte productType = 0;
public byte reserved = 0;
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Gallio.Properties;
namespace Gallio.Model.Filters
{
internal sealed class FilterLexer
{
private readonly static Dictionary<char, FilterTokenType> singleCharacterTokens = new Dictionary<char, FilterTokenType>();
private readonly static List<char> escapableCharacters = new List<char>();
private readonly static List<char> wordDelimiters = new List<char>();
private readonly List<FilterToken> tokens = new List<FilterToken>();
private readonly StringReader input = null;
private readonly char escapeCharacter = '\\';
private int inputPosition = -1;
private int tokenStreamPosition = -1;
static FilterLexer()
{
AddSingleCharacterTokens();
AddEscapableCharacters();
AddWordDelimiters();
}
private static void AddSingleCharacterTokens()
{
singleCharacterTokens.Add(':', FilterTokenType.Colon);
singleCharacterTokens.Add('(', FilterTokenType.LeftBracket);
singleCharacterTokens.Add(')', FilterTokenType.RightBracket);
singleCharacterTokens.Add(',', FilterTokenType.Comma);
singleCharacterTokens.Add('*', FilterTokenType.Star);
}
private static void AddEscapableCharacters()
{
escapableCharacters.Add('"');
escapableCharacters.Add('\'');
escapableCharacters.Add('/');
escapableCharacters.Add(',');
escapableCharacters.Add('\\');
}
private static void AddWordDelimiters()
{
wordDelimiters.Add('"');
wordDelimiters.Add('\'');
wordDelimiters.Add('/');
}
internal FilterLexer(string filter)
{
if (filter == null)
{
filter = String.Empty;
}
input = new StringReader(filter);
Scan();
}
internal List<FilterToken> Tokens
{
get { return tokens; }
}
internal FilterToken GetNextToken()
{
if (tokens.Count > tokenStreamPosition + 1)
{
return tokens[++tokenStreamPosition];
}
++tokenStreamPosition;
return null;
}
internal FilterToken LookAhead(int index)
{
int position = tokenStreamPosition + index;
if (tokens.Count > position && position >= 0)
{
return tokens[tokenStreamPosition + index];
}
else
{
return null;
}
}
private void Scan()
{
while (input.Peek() != -1)
{
char c = (char)input.Peek();
if (char.IsWhiteSpace(c))
{
input.Read();
}
else if (singleCharacterTokens.ContainsKey(c))
{
Match(c.ToString(), singleCharacterTokens[c]);
}
else if (IsWordDelimiter(c))
{
MatchDelimitedWord(c);
if (c == '/')
{
MatchCaseInsensitiveModifier();
}
}
else if (IsWordChar(c))
{
MatchUndelimitedWord();
}
else
{
ConsumeNextChar();
tokens.Add(new FilterToken(FilterTokenType.Error,
String.Format(Resources.FilterParser_UnexpectedCharacterFound, GetCharacterMessage(c)),
inputPosition));
}
}
}
private void MatchUndelimitedWord()
{
var chars = new StringBuilder();
bool errorFound = false;
int startPosition = inputPosition + 1;
char previousChar = ConsumeNextChar();
if (previousChar != escapeCharacter)
{
chars.Append(previousChar);
}
int nextCharCode = input.Peek();
while (nextCharCode != -1)
{
char nextChar = (char)nextCharCode;
if (previousChar == escapeCharacter)
{
if (escapableCharacters.Contains(nextChar))
{
chars.Append(ConsumeNextChar());
// Avoid the case when the last slash in an expression like //'
// makes the following character to be escaped
previousChar = (char)0;
}
else
{
tokens.Add(new FilterToken(FilterTokenType.Error,
String.Format(Resources.FilterParser_CannotEscapeCharacter, GetCharacterMessage(nextChar)),
inputPosition));
ConsumeNextChar();
errorFound = true;
break;
}
}
else if (IsWordChar(nextChar))
{
previousChar = ConsumeNextChar();
chars.Append(previousChar);
}
else
{
break;
}
nextCharCode = input.Peek();
}
if (!errorFound)
{
if (previousChar == escapeCharacter)
{
// The escape character was not followed by another character
tokens.Add(new FilterToken(FilterTokenType.Error, Resources.FilterParser_MissingEscapedCharacter, inputPosition));
}
else
{
string tokenText = chars.ToString();
FilterTokenType filterTokenType = GetReservedWord(tokenText);
if (filterTokenType != FilterTokenType.None)
{
tokens.Add(new FilterToken(filterTokenType, null, startPosition));
}
else
{
tokens.Add(new FilterToken(FilterTokenType.Word, tokenText, startPosition));
}
}
}
}
private void MatchDelimitedWord(char delimiter)
{
var chars = new StringBuilder();
bool errorFound = false;
int startPosition = inputPosition + 1;
char previousChar = (char)0;
bool finalDelimiterFound = false;
ConsumeNextChar();
while (input.Peek() != -1)
{
char nextChar = (char)input.Peek();
if (previousChar == escapeCharacter)
{
if (escapableCharacters.Contains(nextChar))
{
chars.Append(nextChar);
// Avoid the case when the last slash in an expression like //'
// makes the following character to be escaped
nextChar = (char)0;
}
else
{
tokens.Add(new FilterToken(FilterTokenType.Error,
String.Format(Resources.FilterParser_CannotEscapeCharacter, GetCharacterMessage(nextChar)),
inputPosition));
errorFound = true;
ConsumeNextChar();
break;
}
}
else if (nextChar == delimiter)
{
ConsumeNextChar();
finalDelimiterFound = true;
break;
}
// If current char is the escape character then hold it
else if (nextChar != escapeCharacter)
{
chars.Append(nextChar);
}
ConsumeNextChar();
previousChar = nextChar;
}
if (!errorFound)
{
if (previousChar == escapeCharacter)
{
// The escape character was not followed by another character
tokens.Add(new FilterToken(FilterTokenType.Error, Resources.FilterParser_MissingEscapedCharacter, inputPosition));
}
else if (!finalDelimiterFound)
{
tokens.Add(new FilterToken(FilterTokenType.Error,
String.Format(Resources.FilterParser_MissingEndDelimiter, delimiter),
inputPosition));
}
else
{
tokens.Add(new FilterToken(GetTokenTypeForDelimiter(delimiter), chars.ToString(), startPosition));
}
}
}
private void MatchCaseInsensitiveModifier()
{
if (input.Peek() != -1)
{
char nextChar = (char)input.Peek();
if (nextChar == 'i')
{
ConsumeNextChar();
tokens.Add(new FilterToken(FilterTokenType.CaseInsensitiveModifier, null, inputPosition));
}
}
}
private static FilterTokenType GetTokenTypeForDelimiter(char c)
{
if (c == '/')
return FilterTokenType.RegexWord;
return FilterTokenType.Word;
}
private char ConsumeNextChar()
{
inputPosition++;
return (char)input.Read();
}
private static FilterTokenType GetReservedWord(string token)
{
var reservedWord = FilterTokenType.None;
string loweredToken = token.ToLower();
if (loweredToken.CompareTo("and") == 0)
{
reservedWord = FilterTokenType.And;
}
else if (loweredToken.CompareTo("or") == 0)
{
reservedWord = FilterTokenType.Or;
}
else if (loweredToken.CompareTo("not") == 0)
{
reservedWord = FilterTokenType.Not;
}
else if (loweredToken.CompareTo("include") == 0)
{
reservedWord = FilterTokenType.Include;
}
else if (loweredToken.CompareTo("exclude") == 0)
{
reservedWord = FilterTokenType.Exclude;
}
return reservedWord;
}
private bool IsEndOfStream()
{
return (input.Peek() == -1);
}
private void Match(IEnumerable<char> token, FilterTokenType filterTokenType)
{
int startPosition = inputPosition + 1;
foreach (char c in token)
{
if (IsEndOfStream())
{
tokens.Add(new FilterToken(FilterTokenType.Error, Resources.FilterParser_UnexpectedEndOfInput, inputPosition));
break;
}
char inputChar = (char)input.Peek();
if (char.ToLower(inputChar) == c)
{
ConsumeNextChar();
}
else
{
tokens.Add(new FilterToken(FilterTokenType.Error, GetCharacterMessage(inputChar), inputPosition));
}
}
tokens.Add(new FilterToken(filterTokenType, null, startPosition));
}
private static bool IsWordDelimiter(char c)
{
return wordDelimiters.Contains(c);
}
internal static bool IsWordChar(char c)
{
return (!singleCharacterTokens.ContainsKey(c))
&& (!char.IsWhiteSpace(c));
}
private static string GetCharacterMessage(char c)
{
string message = String.Empty;
if (!char.IsControl(c))
{
message += c + " ";
}
message += String.Format(Resources.FilterParser_CharCode, (int)c);
return message;
}
}
}
| |
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace Alphaleonis.EventSourceClassGenerator
{
/// <summary>
/// Base class for a single file code generator.
/// </summary>
public abstract class BaseCodeGenerator : IVsSingleFileGenerator
{
private IVsGeneratorProgress m_progress;
private string m_codeFileNamespace = String.Empty;
private string m_codeFilePath = String.Empty;
#region IVsSingleFileGenerator Members
/// <summary>
/// Implements the IVsSingleFileGenerator.DefaultExtension method.
/// Returns the extension of the generated file
/// </summary>
/// <param name="pbstrDefaultExtension">Out parameter, will hold the extension that is to be given to the output file name. The returned extension must include a leading period</param>
/// <returns>S_OK if successful, E_FAIL if not</returns>
int IVsSingleFileGenerator.DefaultExtension(out string pbstrDefaultExtension)
{
try
{
pbstrDefaultExtension = GetDefaultExtension();
return VSConstants.S_OK;
}
catch (Exception)
{
pbstrDefaultExtension = string.Empty;
return VSConstants.E_FAIL;
}
}
/// <summary>
/// Implements the IVsSingleFileGenerator.Generate method.
/// Executes the transformation and returns the newly generated output file, whenever a custom tool is loaded, or the input file is saved
/// </summary>
/// <param name="wszInputFilePath">The full path of the input file. May be a null reference (Nothing in Visual Basic) in future releases of Visual Studio, so generators should not rely on this value</param>
/// <param name="bstrInputFileContents">The contents of the input file. This is either a UNICODE BSTR (if the input file is text) or a binary BSTR (if the input file is binary). If the input file is a text file, the project system automatically converts the BSTR to UNICODE</param>
/// <param name="wszDefaultNamespace">This parameter is meaningful only for custom tools that generate code. It represents the namespace into which the generated code will be placed. If the parameter is not a null reference (Nothing in Visual Basic) and not empty, the custom tool can use the following syntax to enclose the generated code</param>
/// <param name="rgbOutputFileContents">[out] Returns an array of bytes to be written to the generated file. You must include UNICODE or UTF-8 signature bytes in the returned byte array, as this is a raw stream. The memory for rgbOutputFileContents must be allocated using the .NET Framework call, System.Runtime.InteropServices.AllocCoTaskMem, or the equivalent Win32 system call, CoTaskMemAlloc. The project system is responsible for freeing this memory</param>
/// <param name="pcbOutput">[out] Returns the count of bytes in the rgbOutputFileContent array</param>
/// <param name="pGenerateProgress">A reference to the IVsGeneratorProgress interface through which the generator can report its progress to the project system</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns E_FAIL</returns>
int IVsSingleFileGenerator.Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
{
if (bstrInputFileContents == null)
{
throw new ArgumentNullException(bstrInputFileContents);
}
m_codeFilePath = wszInputFilePath;
m_codeFileNamespace = wszDefaultNamespace;
m_progress = pGenerateProgress;
byte[] bytes = GenerateCode(wszInputFilePath, bstrInputFileContents);
if (bytes == null)
{
// This signals that GenerateCode() has failed. Tasklist items have been put up in GenerateCode()
rgbOutputFileContents = null;
pcbOutput = 0;
// Return E_FAIL to inform Visual Studio that the generator has failed (so that no file gets generated)
return VSConstants.E_FAIL;
}
else
{
// The contract between IVsSingleFileGenerator implementors and consumers is that
// any output returned from IVsSingleFileGenerator.Generate() is returned through
// memory allocated via CoTaskMemAlloc(). Therefore, we have to convert the
// byte[] array returned from GenerateCode() into an unmanaged blob.
int outputLength = bytes.Length;
rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
Marshal.Copy(bytes, 0, rgbOutputFileContents[0], outputLength);
pcbOutput = (uint)outputLength;
return VSConstants.S_OK;
}
}
#endregion
#region Properties
/// <summary>
/// Namespace for the file
/// </summary>
protected string FileNameSpace
{
get
{
return m_codeFileNamespace;
}
}
/// <summary>
/// File-path for the input file
/// </summary>
protected string InputFilePath
{
get
{
return m_codeFilePath;
}
}
/// <summary>
/// Interface to the VS shell object we use to tell our progress while we are generating
/// </summary>
internal IVsGeneratorProgress Progress
{
get
{
return m_progress;
}
}
#endregion
#region Abstract Methods
/// <summary>
/// Gets the default extension for this generator
/// </summary>
/// <returns>String with the default extension for this generator</returns>
protected abstract string GetDefaultExtension();
/// <summary>
/// The method that does the actual work of generating code given the input file
/// </summary>
/// <param name="inputFileContent">File contents as a string</param>
/// <returns>The generated code file as a byte-array</returns>
protected abstract byte[] GenerateCode(string inputFilePath, string inputFileContent);
#endregion
#region Protected Methods
/// <summary>Method that will communicate an error via the shell callback mechanism.</summary>
/// <param name="message">Text displayed to the user.</param>
/// <param name="line">Line number of error.</param>
/// <param name="column">Column number of error.</param>
protected virtual void ReportError(string message, int line, int column)
{
IVsGeneratorProgress progress = Progress;
if (progress != null)
{
progress.GeneratorError(0, 0, message, (uint)line, (uint)column);
}
}
protected virtual void ReportError(string message, object location)
{
IVsGeneratorProgress progress = Progress;
EnvDTE.CodeElement codeElement = location as EnvDTE.CodeElement;
if (progress != null)
{
var startPoint = codeElement == null ? null : ((EnvDTE.CodeElement)location).StartPoint;
progress.GeneratorError(0, 0, message, startPoint == null ? (uint)0xFFFFFFFF : (uint)startPoint.Line, startPoint == null ? (uint)0xFFFFFFFF : (uint)startPoint.DisplayColumn);
}
}
protected virtual void ReportWarning(string message, object location)
{
IVsGeneratorProgress progress = Progress;
EnvDTE.CodeElement codeElement = location as EnvDTE.CodeElement;
if (progress != null)
{
var startPoint = codeElement == null ? null : ((EnvDTE.CodeElement)location).StartPoint;
progress.GeneratorError(1, 0, message, startPoint == null ? (uint)0xFFFFFFFF : (uint)startPoint.Line, startPoint == null ? (uint)0xFFFFFFFF : (uint)startPoint.DisplayColumn);
}
}
/// <summary>Method that will communicate a warning via the shell callback mechanism.</summary>
/// <param name="message">Text displayed to the user.</param>
/// <param name="line">Line number of warning.</param>
/// <param name="column">Column number of warning.</param>
protected virtual void ReportWarning(string message, int line, int column)
{
IVsGeneratorProgress progress = Progress;
if (progress != null)
{
progress.GeneratorError(1, 0, message, (uint)line, (uint)column);
}
}
/// <summary>Sets an index that specifies how much of the generation has been completed.</summary>
/// <param name="current">Index that specifies how much of the generation has been completed. This value can range from zero to <paramref name="total"/>.</param>
/// <param name="total">The maximum value for <paramref name="current"/>.</param>
protected virtual void ReportProgress(int current, int total)
{
IVsGeneratorProgress progress = Progress;
if (progress != null)
{
progress.Progress((uint)current, (uint)total);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NetFusion.Common.Extensions.Collections;
using NetFusion.Common.Extensions.Types;
using NetFusion.Rest.Common;
using NetFusion.Rest.Docs.Core.Descriptions;
using NetFusion.Rest.Docs.Models;
using NetFusion.Rest.Docs.Plugin;
using NetFusion.Rest.Resources;
using NetFusion.Common.Extensions.Reflection;
using NetFusion.Rest.Server.Linking;
using NetFusion.Rest.Server.Mappings;
using NetFusion.Rest.Server.Plugin;
using NetFusion.Web.Mvc.Metadata;
namespace NetFusion.Rest.Docs.Core.Services
{
/// <summary>
/// Service responsible for constructing an action documentation model based on its associated metadata.
/// The model is then augmented with additional documentation such as code comments by invoking associated
/// IDocDescription classes.
/// </summary>
public class DocBuilder : IDocBuilder
{
private readonly IResourceMediaModule _resourceMediaModule;
private readonly IApiMetadataService _apiMetadata;
private readonly IDocDescription[] _docDescriptions;
private readonly ITypeCommentService _typeComments;
public DocBuilder(IDocModule docModule,
IResourceMediaModule resourceMediaModule,
IApiMetadataService apiMetadata,
IEnumerable<IDocDescription> docDescriptions,
ITypeCommentService typeComments)
{
if (docModule == null) throw new ArgumentNullException(nameof(docModule));
if (docDescriptions == null) throw new ArgumentNullException(nameof(docDescriptions));
_resourceMediaModule = resourceMediaModule ?? throw new ArgumentNullException(nameof(resourceMediaModule));
_apiMetadata = apiMetadata ?? throw new ArgumentNullException(nameof(apiMetadata));
_typeComments = typeComments ?? throw new ArgumentNullException(nameof(typeComments));
// Instances of the IDocDescription implementations are to be executed
// based on the order of their types registered within RestDocConfig.
// These classes are what add the documentation to the APIs metadata.
_docDescriptions = docDescriptions.OrderByMatchingType (
docModule.RestDocConfig.DescriptionTypes
).ToArray();
}
public ApiActionDoc BuildActionDoc(ApiActionMeta actionMeta)
{
if (actionMeta == null) throw new ArgumentNullException(nameof(actionMeta));
// Create the root document associated with the action metadata.
var actionDoc = CreateActionDoc(actionMeta);
SetEmbeddedResourceMeta(actionDoc, actionMeta);
// Add the associated action related documentation.
AddParameterDocs(actionDoc, actionMeta);
AddResponseDocs(actionDoc, actionMeta);
AddEmbeddedDocs(actionDoc);
AddRelationDocs(actionDoc);
return actionDoc;
}
private ApiActionDoc CreateActionDoc(ApiActionMeta actionMeta)
{
var actionDoc = new ApiActionDoc(actionMeta.RelativePath, actionMeta.HttpMethod);
ApplyDescriptions<IActionDescription>(desc => desc.Describe(actionDoc, actionMeta));
return actionDoc;
}
private static void SetEmbeddedResourceMeta(ApiActionDoc actionDoc, ApiActionMeta actionMeta)
{
var attributes = actionMeta.GetFilterMetadata<EmbeddedResourceAttribute>();
actionDoc.EmbeddedResourceAttribs = attributes.ToArray();
}
private void AddParameterDocs(ApiActionDoc actionDoc, ApiActionMeta actionMeta)
{
AddParameterDocs(actionDoc.RouteParams, actionMeta, actionMeta.RouteParameters);
AddParameterDocs(actionDoc.BodyParams, actionMeta, actionMeta.BodyParameters);
AddParameterDocs(actionDoc.HeaderParams, actionMeta, actionMeta.HeaderParameters);
AddParameterDocs(actionDoc.QueryParams, actionMeta, actionMeta.QueryParameters);
}
private void AddParameterDocs(ICollection<ApiParameterDoc> paramDocs,
ApiActionMeta actionMeta,
IEnumerable<ApiParameterMeta> paramsMetaItems)
{
foreach (ApiParameterMeta paramMeta in paramsMetaItems)
{
var paramDoc = new ApiParameterDoc
{
Name = paramMeta.ParameterName,
IsOptional = paramMeta.IsOptional,
DefaultValue = paramMeta.DefaultValue?.ToString(),
Type = paramMeta.ParameterType.GetJsTypeName()
};
if (paramMeta.ParameterType.IsClass && !paramMeta.ParameterType.IsBasicType())
{
paramDoc.ResourceDoc = _typeComments.GetResourceDoc(paramMeta.ParameterType);
}
ApplyDescriptions<IParameterDescription>(desc => desc.Describe(paramDoc, actionMeta, paramMeta));
paramDocs.Add(paramDoc);
}
}
private void AddResponseDocs(ApiActionDoc actionDoc, ApiActionMeta actionMeta)
{
foreach(ApiResponseMeta responseMeta in actionMeta.ResponseMeta)
{
var responseDoc = new ApiResponseDoc
{
Status = responseMeta.Status,
};
// If there is a response resource associated with the response status
// code, add documentation for the resource type.
if (responseMeta.ModelType != null && !responseMeta.ModelType.IsBasicType())
{
responseDoc.ResourceDoc = _typeComments.GetResourceDoc(responseMeta.ModelType);
}
ApplyDescriptions<IResponseDescription>(desc => desc.Describe(responseDoc, responseMeta));
actionDoc.ResponseDocs.Add(responseDoc);
}
}
private void AddEmbeddedDocs(ApiActionDoc actionDoc)
{
// Process all resource documents across all response documents
// having an associated resource.
foreach (ApiResourceDoc resourceDoc in actionDoc.ResponseDocs
.Where(d => d.ResourceDoc != null)
.Select(d => d.ResourceDoc))
{
ApplyEmbeddedResourceDocs(resourceDoc, actionDoc.EmbeddedResourceAttribs);
}
}
private void ApplyEmbeddedResourceDocs(ApiResourceDoc resourceDoc,
EmbeddedResourceAttribute[] embeddedResources)
{
resourceDoc.EmbeddedResourceDocs = GetEmbeddedResourceDocs(resourceDoc, embeddedResources).ToArray();
// Next recursively process any embedded documents to determine if they
// have any embedded children resources.
foreach(ApiResourceDoc embeddedResourceDoc in resourceDoc.EmbeddedResourceDocs
.Select(er => er.ResourceDoc))
{
ApplyEmbeddedResourceDocs(embeddedResourceDoc, embeddedResources);
}
}
private IEnumerable<ApiEmbeddedDoc> GetEmbeddedResourceDocs(ApiResourceDoc parentResourceDoc,
EmbeddedResourceAttribute[] embeddedResources)
{
// Find any embedded types specified for the resource type.
var embeddedAttributes = embeddedResources.Where(et =>
et.ParentResourceType.GetResourceName() == parentResourceDoc.ResourceName);
// For each embedded resource type, create an embedded resource document
// with the documentation for each child embedded resource.
foreach (EmbeddedResourceAttribute embeddedAttribute in embeddedAttributes)
{
var embeddedResourceDoc = new ApiEmbeddedDoc
{
EmbeddedName = embeddedAttribute.EmbeddedName,
IsCollection = embeddedAttribute.IsCollection,
ResourceDoc = _typeComments.GetResourceDoc(embeddedAttribute.ChildResourceType)
};
embeddedResourceDoc.ResourceDoc.ResourceName = embeddedAttribute
.ChildResourceType.GetResourceName();
ApplyDescriptions<IEmbeddedDescription>(desc => desc.Describe(embeddedResourceDoc, embeddedAttribute));
yield return embeddedResourceDoc;
}
}
private void AddRelationDocs(ApiActionDoc actionDoc)
{
var (entry, ok) = _resourceMediaModule.GetMediaTypeEntry(InternetMediaTypes.HalJson);
if (!ok)
{
return;
}
foreach(ApiResourceDoc resourceDoc in actionDoc.ResponseDocs
.Where(rd => rd.ResourceDoc != null)
.Select(rd => rd.ResourceDoc))
{
AddRelationDoc(resourceDoc, entry);
}
}
private void AddRelationDoc(ApiResourceDoc resourceDoc, MediaTypeEntry mediaTypeEntry)
{
var (meta, ok) = mediaTypeEntry.GetResourceTypeMeta(resourceDoc.ResourceType);
if (ok)
{
foreach(ResourceLink resourceLink in meta.Links)
{
var relationDoc = new ApiRelationDoc
{
Name = resourceLink.RelationName,
Method = resourceLink.Method,
};
SetLinkDetails(relationDoc, (dynamic)resourceLink);
ApplyDescriptions<IRelationDescription>(desc => desc.Describe(resourceDoc, relationDoc, resourceLink));
resourceDoc.RelationDocs.Add(relationDoc);
}
}
// Next check any embedded resources:
foreach (ApiResourceDoc embeddedResourceDoc in resourceDoc.EmbeddedResourceDocs
.Select(er => er.ResourceDoc))
{
AddRelationDoc(embeddedResourceDoc, mediaTypeEntry);
}
}
private static void SetLinkDetails(ApiRelationDoc relationDoc, ResourceLink resourceLink)
{
relationDoc.HRef = resourceLink.Href;
}
private void SetLinkDetails(ApiRelationDoc relationDoc, ControllerActionLink resourceLink)
{
relationDoc.HRef = _apiMetadata.GetActionMeta(resourceLink.ActionMethodInfo).RelativePath;
}
private void SetLinkDetails(ApiRelationDoc relationDoc, TemplateUrlLink resourceLink)
{
relationDoc.HRef = _apiMetadata.GetActionMeta(resourceLink.ActionMethodInfo).RelativePath;
}
private void ApplyDescriptions<T>(Action<T> description)
where T : class, IDocDescription
{
foreach(T instance in _docDescriptions.OfType<T>())
{
description.Invoke(instance);
}
}
}
}
| |
using System;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Modes
{
/// <summary>
/// Implements the Galois/Counter mode (GCM) detailed in
/// NIST Special Publication 800-38D.
/// </summary>
public class GcmBlockCipher
: IAeadBlockCipher
{
private const int BlockSize = 16;
private static readonly byte[] Zeroes = new byte[BlockSize];
private static readonly BigInteger R = new BigInteger("11100001", 2).ShiftLeft(120);
private readonly IBlockCipher cipher;
// These fields are set by Init and not modified by processing
private bool forEncryption;
private int macSize;
private byte[] nonce;
private byte[] A;
private KeyParameter keyParam;
// private int tagLength;
private BigInteger H;
private BigInteger initS;
private byte[] J0;
// These fields are modified during processing
private byte[] bufBlock;
private byte[] macBlock;
private BigInteger S;
private byte[] counter;
private int bufOff;
private long totalLength;
// Debug variables
// private int nCount, xCount, yCount;
public GcmBlockCipher(
IBlockCipher c)
{
if (c.GetBlockSize() != BlockSize)
throw new ArgumentException("cipher required with a block size of " + BlockSize + ".");
this.cipher = c;
}
public virtual string AlgorithmName
{
get { return cipher.AlgorithmName + "/GCM"; }
}
public virtual int GetBlockSize()
{
return BlockSize;
}
public virtual void Init(
bool forEncryption,
ICipherParameters parameters)
{
this.forEncryption = forEncryption;
this.macSize = 16; // TODO Make configurable?
this.macBlock = null;
// TODO If macSize limitation is removed, be very careful about bufBlock
int bufLength = forEncryption ? BlockSize : (BlockSize + macSize);
this.bufBlock = new byte[bufLength];
if (parameters is AeadParameters)
{
AeadParameters param = (AeadParameters)parameters;
nonce = param.GetNonce();
A = param.GetAssociatedText();
// macSize = param.getMacSize() / 8;
if (param.MacSize != 128)
{
// TODO Make configurable?
throw new ArgumentException("only 128-bit MAC supported currently");
}
keyParam = param.Key;
}
else if (parameters is ParametersWithIV)
{
ParametersWithIV param = (ParametersWithIV)parameters;
nonce = param.GetIV();
A = null;
keyParam = (KeyParameter)param.Parameters;
}
else
{
throw new ArgumentException("invalid parameters passed to GCM");
}
if (nonce == null || nonce.Length < 1)
{
throw new ArgumentException("IV must be at least 1 byte");
}
if (A == null)
{
// Avoid lots of null checks
A = new byte[0];
}
// Cipher always used input forward mode
cipher.Init(true, keyParam);
// TODO This should be configurable by Init parameters
// (but must be 16 if nonce length not 12) (BlockSize?)
// this.tagLength = 16;
byte[] h = new byte[BlockSize];
cipher.ProcessBlock(Zeroes, 0, h, 0);
//trace("H: " + new string(Hex.encode(h)));
this.H = new BigInteger(1, h);
this.initS = gHASH(A, false);
if (nonce.Length == 12)
{
this.J0 = new byte[16];
Array.Copy(nonce, 0, J0, 0, nonce.Length);
this.J0[15] = 0x01;
}
else
{
BigInteger N = gHASH(nonce, true);
BigInteger X = BigInteger.ValueOf(nonce.Length * 8);
//trace("len({})||len(IV): " + dumpBigInt(X));
N = multiply(N.Xor(X), H);
//trace("GHASH(H,{},IV): " + dumpBigInt(N));
this.J0 = asBlock(N);
}
this.S = initS;
this.counter = Arrays.Clone(J0);
//trace("Y" + yCount + ": " + new string(Hex.encode(counter)));
this.bufOff = 0;
this.totalLength = 0;
}
public virtual byte[] GetMac()
{
return Arrays.Clone(macBlock);
}
public virtual int GetOutputSize(
int len)
{
if (forEncryption)
{
return len + bufOff + macSize;
}
return len + bufOff - macSize;
}
public virtual int GetUpdateOutputSize(
int len)
{
return ((len + bufOff) / BlockSize) * BlockSize;
}
public virtual int ProcessByte(
byte input,
byte[] output,
int outOff)
{
return Process(input, output, outOff);
}
public virtual int ProcessBytes(
byte[] input,
int inOff,
int len,
byte[] output,
int outOff)
{
int resultLen = 0;
for (int i = 0; i != len; i++)
{
resultLen += Process(input[inOff + i], output, outOff + resultLen);
}
return resultLen;
}
private int Process(
byte input,
byte[] output,
int outOff)
{
bufBlock[bufOff++] = input;
if (bufOff == bufBlock.Length)
{
gCTRBlock(bufBlock, BlockSize, output, outOff);
if (!forEncryption)
{
Array.Copy(bufBlock, BlockSize, bufBlock, 0, BlockSize);
}
// bufOff = 0;
bufOff = bufBlock.Length - BlockSize;
// return bufBlock.Length;
return BlockSize;
}
return 0;
}
public int DoFinal(byte[] output, int outOff)
{
int extra = bufOff;
if (!forEncryption)
{
if (extra < macSize)
throw new InvalidCipherTextException("data too short");
extra -= macSize;
}
if (extra > 0)
{
byte[] tmp = new byte[BlockSize];
Array.Copy(bufBlock, 0, tmp, 0, extra);
gCTRBlock(tmp, extra, output, outOff);
}
// Final gHASH
BigInteger X = BigInteger.ValueOf(A.Length * 8).ShiftLeft(64).Add(
BigInteger.ValueOf(totalLength * 8));
//trace("len(A)||len(C): " + dumpBigInt(X));
S = multiply(S.Xor(X), H);
//trace("GHASH(H,A,C): " + dumpBigInt(S));
// T = MSBt(GCTRk(J0,S))
byte[] tBytes = new byte[BlockSize];
cipher.ProcessBlock(J0, 0, tBytes, 0);
//trace("E(K,Y0): " + new string(Hex.encode(tmp)));
BigInteger T = S.Xor(new BigInteger(1, tBytes));
// TODO Fix this if tagLength becomes configurable
byte[] tag = asBlock(T);
//trace("T: " + new string(Hex.encode(tag)));
int resultLen = extra;
if (forEncryption)
{
this.macBlock = tag;
Array.Copy(tag, 0, output, outOff + bufOff, tag.Length);
resultLen += tag.Length;
}
else
{
this.macBlock = new byte[macSize];
Array.Copy(bufBlock, extra, macBlock, 0, macSize);
if (!Arrays.AreEqual(tag, this.macBlock))
throw new InvalidCipherTextException("mac check input GCM failed");
}
Reset(false);
return resultLen;
}
public virtual void Reset()
{
Reset(true);
}
private void Reset(
bool clearMac)
{
// Debug
// nCount = xCount = yCount = 0;
S = initS;
counter = Arrays.Clone(J0);
bufOff = 0;
totalLength = 0;
if (bufBlock != null)
{
Array.Clear(bufBlock, 0, bufBlock.Length);
}
if (clearMac)
{
macBlock = null;
}
cipher.Reset();
}
private void gCTRBlock(byte[] buf, int bufCount, byte[] output, int outOff)
{
inc(counter);
//trace("Y" + ++yCount + ": " + new string(Hex.encode(counter)));
byte[] tmp = new byte[BlockSize];
cipher.ProcessBlock(counter, 0, tmp, 0);
//trace("E(K,Y" + yCount + "): " + new string(Hex.encode(tmp)));
if (forEncryption)
{
Array.Copy(Zeroes, bufCount, tmp, bufCount, BlockSize - bufCount);
for (int i = bufCount - 1; i >= 0; --i)
{
tmp[i] ^= buf[i];
output[outOff + i] = tmp[i];
}
gHASHBlock(tmp);
}
else
{
for (int i = bufCount - 1; i >= 0; --i)
{
tmp[i] ^= buf[i];
output[outOff + i] = tmp[i];
}
gHASHBlock(buf);
}
totalLength += bufCount;
}
private BigInteger gHASH(byte[] b, bool nonce)
{
//trace("" + b.Length);
BigInteger Y = BigInteger.Zero;
for (int pos = 0; pos < b.Length; pos += 16)
{
byte[] x = new byte[16];
int num = System.Math.Min(b.Length - pos, 16);
Array.Copy(b, pos, x, 0, num);
BigInteger X = new BigInteger(1, x);
Y = multiply(Y.Xor(X), H);
// if (nonce)
// {
// trace("N" + ++nCount + ": " + dumpBigInt(Y));
// }
// else
// {
// trace("X" + ++xCount + ": " + dumpBigInt(Y) + " (gHASH)");
// }
}
return Y;
}
private void gHASHBlock(byte[] block)
{
if (block.Length > BlockSize)
{
byte[] tmp = new byte[BlockSize];
Array.Copy(block, 0, tmp, 0, BlockSize);
block = tmp;
}
BigInteger X = new BigInteger(1, block);
S = multiply(S.Xor(X), H);
//trace("X" + ++xCount + ": " + dumpBigInt(S) + " (gHASHBlock)");
}
private static void inc(byte[] block)
{
// assert block.Length == 16;
for (int i = 15; i >= 12; --i)
{
byte b = (byte)((block[i] + 1) & 0xff);
block[i] = b;
if (b != 0)
{
break;
}
}
}
private BigInteger multiply(
BigInteger X,
BigInteger Y)
{
BigInteger Z = BigInteger.Zero;
BigInteger V = X;
for (int i = 0; i < 128; ++i)
{
if (Y.TestBit(127 - i))
{
Z = Z.Xor(V);
}
bool lsb = V.TestBit(0);
V = V.ShiftRight(1);
if (lsb)
{
V = V.Xor(R);
}
}
return Z;
}
private byte[] asBlock(
BigInteger bi)
{
byte[] b = BigIntegers.AsUnsignedByteArray(bi);
if (b.Length < 16)
{
byte[] tmp = new byte[16];
Array.Copy(b, 0, tmp, tmp.Length - b.Length, b.Length);
b = tmp;
}
return b;
}
// private string dumpBigInt(BigInteger bi)
// {
// byte[] b = asBlock(bi);
//
// return new string(Hex.encode(b));
// }
//
// private void trace(string msg)
// {
// System.err.println(msg);
// }
}
}
| |
//
// 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 Hyak.Common;
using Microsoft.Azure.Management.Batch;
using Microsoft.Azure.Management.Batch.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Batch
{
/// <summary>
/// Operations for managing Batch service properties at the subscription
/// level.
/// </summary>
internal partial class SubscriptionOperations : IServiceOperations<BatchManagementClient>, ISubscriptionOperations
{
/// <summary>
/// Initializes a new instance of the SubscriptionOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal SubscriptionOperations(BatchManagementClient client)
{
this._client = client;
}
private BatchManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Batch.BatchManagementClient.
/// </summary>
public BatchManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Get Subscription Quotas operation returns the quotas of the
/// subscription in the Batch service.
/// </summary>
/// <param name='locationName'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Values returned by the Get Subscription Quotas operation.
/// </returns>
public async Task<SubscriptionQuotasGetResponse> GetSubscriptionQuotasAsync(string locationName, CancellationToken cancellationToken)
{
// Validate
if (locationName == null)
{
throw new ArgumentNullException("locationName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("locationName", locationName);
TracingAdapter.Enter(invocationId, this, "GetSubscriptionQuotasAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/";
url = url + "Microsoft.Batch";
url = url + "/locations/";
url = url + Uri.EscapeDataString(locationName);
url = url + "/quotas";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-12-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-12-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
SubscriptionQuotasGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new SubscriptionQuotasGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken accountQuotaValue = responseDoc["accountQuota"];
if (accountQuotaValue != null && accountQuotaValue.Type != JTokenType.Null)
{
int accountQuotaInstance = ((int)accountQuotaValue);
result.AccountQuota = accountQuotaInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.SpanTests
{
public static partial class ReadOnlySpanTests
{
[Fact]
public static void IndexOfSequenceMatchAtStart()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 5, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 5, 1, 77 });
int index = span.IndexOf(value);
Assert.Equal(0, index);
}
[Fact]
public static void IndexOfSequenceMultipleMatch()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 1, 2, 3, 1, 2, 3, 1, 2, 3 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 2, 3 });
int index = span.IndexOf(value);
Assert.Equal(1, index);
}
[Fact]
public static void IndexOfSequenceRestart()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 77, 77, 88 });
int index = span.IndexOf(value);
Assert.Equal(10, index);
}
[Fact]
public static void IndexOfSequenceNoMatch()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 77, 77, 88, 99 });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void IndexOfSequenceNotEvenAHeadMatch()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 100, 77, 88, 99 });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void IndexOfSequenceMatchAtVeryEnd()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 3, 4, 5 });
int index = span.IndexOf(value);
Assert.Equal(3, index);
}
[Fact]
public static void IndexOfSequenceJustPastVeryEnd()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 }, 0, 5);
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 3, 4, 5 });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void IndexOfSequenceZeroLengthValue()
{
// A zero-length value is always "found" at the start of the span.
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(Array.Empty<int>());
int index = span.IndexOf(value);
Assert.Equal(0, index);
}
[Fact]
public static void IndexOfSequenceZeroLengthSpan()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(Array.Empty<int>());
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 1, 2, 3 });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void IndexOfSequenceLengthOneValue()
{
// A zero-length value is always "found" at the start of the span.
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 2 });
int index = span.IndexOf(value);
Assert.Equal(2, index);
}
[Fact]
public static void IndexOfSequenceLengthOneValueAtVeryEnd()
{
// A zero-length value is always "found" at the start of the span.
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 5 });
int index = span.IndexOf(value);
Assert.Equal(5, index);
}
[Fact]
public static void IndexOfSequenceLengthOneValueJustPasttVeryEnd()
{
// A zero-length value is always "found" at the start of the span.
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 }, 0, 5);
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 5 });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void IndexOfSequenceMatchAtStart_String()
{
ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "5", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "88", "9" });
ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "5", "1", "77" });
int index = span.IndexOf(value);
Assert.Equal(0, index);
}
[Fact]
public static void IndexOfSequenceMultipleMatch_String()
{
ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "1", "2", "3", "1", "2", "3", "1", "2", "3" });
ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "2", "3" });
int index = span.IndexOf(value);
Assert.Equal(1, index);
}
[Fact]
public static void IndexOfSequenceRestart_String()
{
ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "88", "9" });
ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "77", "77", "88" });
int index = span.IndexOf(value);
Assert.Equal(10, index);
}
[Fact]
public static void IndexOfSequenceNoMatch_String()
{
ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "88", "9" });
ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "77", "77", "88", "99" });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void IndexOfSequenceNotEvenAHeadMatch_String()
{
ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "88", "9" });
ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "100", "77", "88", "99" });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void IndexOfSequenceMatchAtVeryEnd_String()
{
ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "2", "3", "4", "5" });
ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "3", "4", "5" });
int index = span.IndexOf(value);
Assert.Equal(3, index);
}
[Fact]
public static void IndexOfSequenceJustPastVeryEnd_String()
{
ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "2", "3", "4", "5" }, 0, 5);
ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "3", "4", "5" });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void IndexOfSequenceZeroLengthValue_String()
{
// A zero-length value is always "found" at the start of the span.
ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "88", "9" });
ReadOnlySpan<string> value = new ReadOnlySpan<string>(Array.Empty<string>());
int index = span.IndexOf(value);
Assert.Equal(0, index);
}
[Fact]
public static void IndexOfSequenceZeroLengthSpan_String()
{
ReadOnlySpan<string> span = new ReadOnlySpan<string>(Array.Empty<string>());
ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "1", "2", "3" });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void IndexOfSequenceLengthOneValue_String()
{
// A zero-length value is always "found" at the start of the span.
ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "2", "3", "4", "5" });
ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "2" });
int index = span.IndexOf(value);
Assert.Equal(2, index);
}
[Fact]
public static void IndexOfSequenceLengthOneValueAtVeryEnd_String()
{
// A zero-length value is always "found" at the start of the span.
ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "2", "3", "4", "5" });
ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "5" });
int index = span.IndexOf(value);
Assert.Equal(5, index);
}
[Fact]
public static void IndexOfSequenceLengthOneValueJustPasttVeryEnd_String()
{
// A zero-length value is always "found" at the start of the span.
ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "2", "3", "4", "5" }, 0, 5);
ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "5" });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Carousel;
using osu.Game.Screens.Select.Filter;
using osu.Game.Tests.Resources;
using osuTK.Input;
namespace osu.Game.Tests.Visual.SongSelect
{
[TestFixture]
public class TestSceneBeatmapCarousel : OsuManualInputManagerTestScene
{
private TestBeatmapCarousel carousel;
private RulesetStore rulesets;
private readonly Stack<BeatmapSetInfo> selectedSets = new Stack<BeatmapSetInfo>();
private readonly HashSet<Guid> eagerSelectedIDs = new HashSet<Guid>();
private BeatmapInfo currentSelection => carousel.SelectedBeatmapInfo;
private const int set_count = 5;
[BackgroundDependencyLoader]
private void load(RulesetStore rulesets)
{
this.rulesets = rulesets;
}
[Test]
public void TestExternalRulesetChange()
{
createCarousel(new List<BeatmapSetInfo>());
AddStep("filter to ruleset 0", () => carousel.Filter(new FilterCriteria
{
Ruleset = rulesets.AvailableRulesets.ElementAt(0),
AllowConvertedBeatmaps = true,
}, false));
AddStep("add mixed ruleset beatmapset", () =>
{
var testMixed = TestResources.CreateTestBeatmapSetInfo(3);
for (int i = 0; i <= 2; i++)
{
testMixed.Beatmaps[i].Ruleset = rulesets.AvailableRulesets.ElementAt(i);
}
carousel.UpdateBeatmapSet(testMixed);
});
AddUntilStep("wait for filtered difficulties", () =>
{
var visibleBeatmapPanels = carousel.Items.OfType<DrawableCarouselBeatmap>().Where(p => p.IsPresent).ToArray();
return visibleBeatmapPanels.Length == 1
&& visibleBeatmapPanels.Count(p => ((CarouselBeatmap)p.Item).BeatmapInfo.Ruleset.OnlineID == 0) == 1;
});
AddStep("filter to ruleset 1", () => carousel.Filter(new FilterCriteria
{
Ruleset = rulesets.AvailableRulesets.ElementAt(1),
AllowConvertedBeatmaps = true,
}, false));
AddUntilStep("wait for filtered difficulties", () =>
{
var visibleBeatmapPanels = carousel.Items.OfType<DrawableCarouselBeatmap>().Where(p => p.IsPresent).ToArray();
return visibleBeatmapPanels.Length == 2
&& visibleBeatmapPanels.Count(p => ((CarouselBeatmap)p.Item).BeatmapInfo.Ruleset.OnlineID == 0) == 1
&& visibleBeatmapPanels.Count(p => ((CarouselBeatmap)p.Item).BeatmapInfo.Ruleset.OnlineID == 1) == 1;
});
AddStep("filter to ruleset 2", () => carousel.Filter(new FilterCriteria
{
Ruleset = rulesets.AvailableRulesets.ElementAt(2),
AllowConvertedBeatmaps = true,
}, false));
AddUntilStep("wait for filtered difficulties", () =>
{
var visibleBeatmapPanels = carousel.Items.OfType<DrawableCarouselBeatmap>().Where(p => p.IsPresent).ToArray();
return visibleBeatmapPanels.Length == 2
&& visibleBeatmapPanels.Count(p => ((CarouselBeatmap)p.Item).BeatmapInfo.Ruleset.OnlineID == 0) == 1
&& visibleBeatmapPanels.Count(p => ((CarouselBeatmap)p.Item).BeatmapInfo.Ruleset.OnlineID == 2) == 1;
});
}
[Test]
public void TestScrollPositionMaintainedOnAdd()
{
loadBeatmaps(count: 1, randomDifficulties: false);
for (int i = 0; i < 10; i++)
{
AddRepeatStep("Add some sets", () => carousel.UpdateBeatmapSet(TestResources.CreateTestBeatmapSetInfo()), 4);
checkSelectionIsCentered();
}
}
[Test]
public void TestScrollPositionMaintainedOnDelete()
{
loadBeatmaps(count: 50, randomDifficulties: false);
for (int i = 0; i < 10; i++)
{
AddRepeatStep("Remove some sets", () =>
carousel.RemoveBeatmapSet(carousel.Items.Select(item => item.Item)
.OfType<CarouselBeatmapSet>()
.OrderBy(item => item.GetHashCode())
.First(item => item.State.Value != CarouselItemState.Selected && item.Visible).BeatmapSet), 4);
checkSelectionIsCentered();
}
}
[Test]
public void TestManyPanels()
{
loadBeatmaps(count: 5000, randomDifficulties: true);
}
[Test]
public void TestKeyRepeat()
{
loadBeatmaps();
advanceSelection(false);
AddStep("press down arrow", () => InputManager.PressKey(Key.Down));
BeatmapInfo selection = null;
checkSelectionIterating(true);
AddStep("press up arrow", () => InputManager.PressKey(Key.Up));
checkSelectionIterating(true);
AddStep("release down arrow", () => InputManager.ReleaseKey(Key.Down));
checkSelectionIterating(true);
AddStep("release up arrow", () => InputManager.ReleaseKey(Key.Up));
checkSelectionIterating(false);
void checkSelectionIterating(bool isIterating)
{
for (int i = 0; i < 3; i++)
{
AddStep("store selection", () => selection = carousel.SelectedBeatmapInfo);
if (isIterating)
AddUntilStep("selection changed", () => !carousel.SelectedBeatmapInfo?.Equals(selection) == true);
else
AddUntilStep("selection not changed", () => carousel.SelectedBeatmapInfo.Equals(selection));
}
}
}
[Test]
public void TestRecommendedSelection()
{
loadBeatmaps(carouselAdjust: carousel => carousel.GetRecommendedBeatmap = beatmaps => beatmaps.LastOrDefault());
AddStep("select last", () => carousel.SelectBeatmap(carousel.BeatmapSets.Last().Beatmaps.Last()));
// check recommended was selected
advanceSelection(direction: 1, diff: false);
waitForSelection(1, 3);
// change away from recommended
advanceSelection(direction: -1, diff: true);
waitForSelection(1, 2);
// next set, check recommended
advanceSelection(direction: 1, diff: false);
waitForSelection(2, 3);
// next set, check recommended
advanceSelection(direction: 1, diff: false);
waitForSelection(3, 3);
// go back to first set and ensure user selection was retained
advanceSelection(direction: -1, diff: false);
advanceSelection(direction: -1, diff: false);
waitForSelection(1, 2);
}
/// <summary>
/// Test keyboard traversal
/// </summary>
[Test]
public void TestTraversal()
{
loadBeatmaps();
AddStep("select first", () => carousel.SelectBeatmap(carousel.BeatmapSets.First().Beatmaps.First()));
waitForSelection(1, 1);
advanceSelection(direction: 1, diff: true);
waitForSelection(1, 2);
advanceSelection(direction: -1, diff: false);
waitForSelection(set_count, 1);
advanceSelection(direction: -1, diff: true);
waitForSelection(set_count - 1, 3);
advanceSelection(diff: false);
advanceSelection(diff: false);
waitForSelection(1, 2);
advanceSelection(direction: -1, diff: true);
advanceSelection(direction: -1, diff: true);
waitForSelection(set_count, 3);
}
[TestCase(true)]
[TestCase(false)]
public void TestTraversalBeyondVisible(bool forwards)
{
var sets = new List<BeatmapSetInfo>();
const int total_set_count = 200;
for (int i = 0; i < total_set_count; i++)
sets.Add(TestResources.CreateTestBeatmapSetInfo());
loadBeatmaps(sets);
for (int i = 1; i < total_set_count; i += i)
selectNextAndAssert(i);
void selectNextAndAssert(int amount)
{
setSelected(forwards ? 1 : total_set_count, 1);
AddStep($"{(forwards ? "Next" : "Previous")} beatmap {amount} times", () =>
{
for (int i = 0; i < amount; i++)
{
carousel.SelectNext(forwards ? 1 : -1);
}
});
waitForSelection(forwards ? amount + 1 : total_set_count - amount);
}
}
[Test]
public void TestTraversalBeyondVisibleDifficulties()
{
var sets = new List<BeatmapSetInfo>();
const int total_set_count = 20;
for (int i = 0; i < total_set_count; i++)
sets.Add(TestResources.CreateTestBeatmapSetInfo(3));
loadBeatmaps(sets);
// Selects next set once, difficulty index doesn't change
selectNextAndAssert(3, true, 2, 1);
// Selects next set 16 times (50 \ 3 == 16), difficulty index changes twice (50 % 3 == 2)
selectNextAndAssert(50, true, 17, 3);
// Travels around the carousel thrice (200 \ 60 == 3)
// continues to select 20 times (200 \ 60 == 20)
// selects next set 6 times (20 \ 3 == 6)
// difficulty index changes twice (20 % 3 == 2)
selectNextAndAssert(200, true, 7, 3);
// All same but in reverse
selectNextAndAssert(3, false, 19, 3);
selectNextAndAssert(50, false, 4, 1);
selectNextAndAssert(200, false, 14, 1);
void selectNextAndAssert(int amount, bool forwards, int expectedSet, int expectedDiff)
{
// Select very first or very last difficulty
setSelected(forwards ? 1 : 20, forwards ? 1 : 3);
AddStep($"{(forwards ? "Next" : "Previous")} difficulty {amount} times", () =>
{
for (int i = 0; i < amount; i++)
carousel.SelectNext(forwards ? 1 : -1, false);
});
waitForSelection(expectedSet, expectedDiff);
}
}
/// <summary>
/// Test filtering
/// </summary>
[Test]
public void TestFiltering()
{
loadBeatmaps();
// basic filtering
setSelected(1, 1);
AddStep("Filter", () => carousel.Filter(new FilterCriteria { SearchText = carousel.BeatmapSets.ElementAt(2).Metadata.Title }, false));
checkVisibleItemCount(diff: false, count: 1);
checkVisibleItemCount(diff: true, count: 3);
waitForSelection(3, 1);
advanceSelection(diff: true, count: 4);
waitForSelection(3, 2);
AddStep("Un-filter (debounce)", () => carousel.Filter(new FilterCriteria()));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(diff: false, count: set_count);
checkVisibleItemCount(diff: true, count: 3);
// test filtering some difficulties (and keeping current beatmap set selected).
setSelected(1, 2);
AddStep("Filter some difficulties", () => carousel.Filter(new FilterCriteria { SearchText = "Normal" }, false));
waitForSelection(1, 1);
AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false));
waitForSelection(1, 1);
AddStep("Filter all", () => carousel.Filter(new FilterCriteria { SearchText = "Dingo" }, false));
checkVisibleItemCount(false, 0);
checkVisibleItemCount(true, 0);
AddAssert("Selection is null", () => currentSelection == null);
advanceSelection(true);
AddAssert("Selection is null", () => currentSelection == null);
advanceSelection(false);
AddAssert("Selection is null", () => currentSelection == null);
AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false));
AddAssert("Selection is non-null", () => currentSelection != null);
setSelected(1, 3);
}
[Test]
public void TestFilterRange()
{
string searchText = null;
loadBeatmaps();
// buffer the selection
setSelected(3, 2);
AddStep("get search text", () => searchText = carousel.SelectedBeatmapSet.Metadata.Title);
setSelected(1, 3);
AddStep("Apply a range filter", () => carousel.Filter(new FilterCriteria
{
SearchText = searchText,
StarDifficulty = new FilterCriteria.OptionalRange<double>
{
Min = 2,
Max = 5.5,
IsLowerInclusive = true
}
}, false));
// should reselect the buffered selection.
waitForSelection(3, 2);
}
/// <summary>
/// Test random non-repeating algorithm
/// </summary>
[Test]
public void TestRandom()
{
loadBeatmaps();
setSelected(1, 1);
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
ensureRandomDidntRepeat();
prevRandom();
ensureRandomFetchSuccess();
prevRandom();
ensureRandomFetchSuccess();
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
AddAssert("ensure repeat", () => selectedSets.Contains(carousel.SelectedBeatmapSet));
AddStep("Add set with 100 difficulties", () => carousel.UpdateBeatmapSet(TestResources.CreateTestBeatmapSetInfo(100, rulesets.AvailableRulesets.ToArray())));
AddStep("Filter Extra", () => carousel.Filter(new FilterCriteria { SearchText = "Extra 10" }, false));
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false));
}
/// <summary>
/// Test adding and removing beatmap sets
/// </summary>
[Test]
public void TestAddRemove()
{
loadBeatmaps();
var firstAdded = TestResources.CreateTestBeatmapSetInfo();
var secondAdded = TestResources.CreateTestBeatmapSetInfo();
AddStep("Add new set", () => carousel.UpdateBeatmapSet(firstAdded));
AddStep("Add new set", () => carousel.UpdateBeatmapSet(secondAdded));
checkVisibleItemCount(false, set_count + 2);
AddStep("Remove set", () => carousel.RemoveBeatmapSet(firstAdded));
checkVisibleItemCount(false, set_count + 1);
setSelected(set_count + 1, 1);
AddStep("Remove set", () => carousel.RemoveBeatmapSet(secondAdded));
checkVisibleItemCount(false, set_count);
waitForSelection(set_count);
}
[Test]
public void TestSelectionEnteringFromEmptyRuleset()
{
var sets = new List<BeatmapSetInfo>();
AddStep("Create beatmaps for taiko only", () =>
{
sets.Clear();
var rulesetBeatmapSet = TestResources.CreateTestBeatmapSetInfo(1);
var taikoRuleset = rulesets.AvailableRulesets.ElementAt(1);
rulesetBeatmapSet.Beatmaps.ForEach(b => b.Ruleset = taikoRuleset);
sets.Add(rulesetBeatmapSet);
});
loadBeatmaps(sets, () => new FilterCriteria { Ruleset = rulesets.AvailableRulesets.ElementAt(0) });
AddStep("Set non-empty mode filter", () =>
carousel.Filter(new FilterCriteria { Ruleset = rulesets.AvailableRulesets.ElementAt(1) }, false));
AddAssert("Something is selected", () => carousel.SelectedBeatmapInfo != null);
}
/// <summary>
/// Test sorting
/// </summary>
[Test]
public void TestSorting()
{
var sets = new List<BeatmapSetInfo>();
const string zzz_string = "zzzzz";
for (int i = 0; i < 20; i++)
{
var set = TestResources.CreateTestBeatmapSetInfo();
if (i == 4)
set.Beatmaps.ForEach(b => b.Metadata.Artist = zzz_string);
if (i == 16)
set.Beatmaps.ForEach(b => b.Metadata.Author.Username = zzz_string);
sets.Add(set);
}
loadBeatmaps(sets);
AddStep("Sort by author", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Author }, false));
AddAssert($"Check {zzz_string} is at bottom", () => carousel.BeatmapSets.Last().Metadata.Author.Username == zzz_string);
AddStep("Sort by artist", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Artist }, false));
AddAssert($"Check {zzz_string} is at bottom", () => carousel.BeatmapSets.Last().Metadata.Artist == zzz_string);
}
[Test]
public void TestSortingStability()
{
var sets = new List<BeatmapSetInfo>();
for (int i = 0; i < 20; i++)
{
var set = TestResources.CreateTestBeatmapSetInfo();
// only need to set the first as they are a shared reference.
var beatmap = set.Beatmaps.First();
beatmap.Metadata.Artist = "same artist";
beatmap.Metadata.Title = "same title";
sets.Add(set);
}
int idOffset = sets.First().OnlineID;
loadBeatmaps(sets);
AddStep("Sort by artist", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Artist }, false));
AddAssert("Items remain in original order", () => carousel.BeatmapSets.Select((set, index) => set.OnlineID == index + idOffset).All(b => b));
AddStep("Sort by title", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Title }, false));
AddAssert("Items remain in original order", () => carousel.BeatmapSets.Select((set, index) => set.OnlineID == index + idOffset).All(b => b));
}
[Test]
public void TestSortingWithFiltered()
{
List<BeatmapSetInfo> sets = new List<BeatmapSetInfo>();
for (int i = 0; i < 3; i++)
{
var set = TestResources.CreateTestBeatmapSetInfo(3);
set.Beatmaps[0].StarRating = 3 - i;
set.Beatmaps[2].StarRating = 6 + i;
sets.Add(set);
}
loadBeatmaps(sets);
AddStep("Filter to normal", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Difficulty, SearchText = "Normal" }, false));
AddAssert("Check first set at end", () => carousel.BeatmapSets.First().Equals(sets.Last()));
AddAssert("Check last set at start", () => carousel.BeatmapSets.Last().Equals(sets.First()));
AddStep("Filter to insane", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Difficulty, SearchText = "Insane" }, false));
AddAssert("Check first set at start", () => carousel.BeatmapSets.First().Equals(sets.First()));
AddAssert("Check last set at end", () => carousel.BeatmapSets.Last().Equals(sets.Last()));
}
[Test]
public void TestRemoveAll()
{
loadBeatmaps();
setSelected(2, 1);
AddAssert("Selection is non-null", () => currentSelection != null);
AddStep("Remove selected", () => carousel.RemoveBeatmapSet(carousel.SelectedBeatmapSet));
waitForSelection(2);
AddStep("Remove first", () => carousel.RemoveBeatmapSet(carousel.BeatmapSets.First()));
AddStep("Remove first", () => carousel.RemoveBeatmapSet(carousel.BeatmapSets.First()));
waitForSelection(1);
AddUntilStep("Remove all", () =>
{
if (!carousel.BeatmapSets.Any()) return true;
carousel.RemoveBeatmapSet(carousel.BeatmapSets.Last());
return false;
});
checkNoSelection();
}
[Test]
public void TestEmptyTraversal()
{
loadBeatmaps(new List<BeatmapSetInfo>());
advanceSelection(direction: 1, diff: false);
checkNoSelection();
advanceSelection(direction: 1, diff: true);
checkNoSelection();
advanceSelection(direction: -1, diff: false);
checkNoSelection();
advanceSelection(direction: -1, diff: true);
checkNoSelection();
}
[Test]
public void TestHiding()
{
BeatmapSetInfo hidingSet = null;
List<BeatmapSetInfo> hiddenList = new List<BeatmapSetInfo>();
AddStep("create hidden set", () =>
{
hidingSet = TestResources.CreateTestBeatmapSetInfo(3);
hidingSet.Beatmaps[1].Hidden = true;
hiddenList.Clear();
hiddenList.Add(hidingSet);
});
loadBeatmaps(hiddenList);
setSelected(1, 1);
checkVisibleItemCount(true, 2);
advanceSelection(true);
waitForSelection(1, 3);
setHidden(3);
waitForSelection(1, 1);
setHidden(2, false);
advanceSelection(true);
waitForSelection(1, 2);
setHidden(1);
waitForSelection(1, 2);
setHidden(2);
checkNoSelection();
void setHidden(int diff, bool hidden = true)
{
AddStep((hidden ? "" : "un") + $"hide diff {diff}", () =>
{
hidingSet.Beatmaps[diff - 1].Hidden = hidden;
carousel.UpdateBeatmapSet(hidingSet);
});
}
}
[Test]
public void TestSelectingFilteredRuleset()
{
BeatmapSetInfo testMixed = null;
createCarousel(new List<BeatmapSetInfo>());
AddStep("add mixed ruleset beatmapset", () =>
{
testMixed = TestResources.CreateTestBeatmapSetInfo(3);
for (int i = 0; i <= 2; i++)
{
testMixed.Beatmaps[i].Ruleset = rulesets.AvailableRulesets.ElementAt(i);
}
carousel.UpdateBeatmapSet(testMixed);
});
AddStep("filter to ruleset 0", () =>
carousel.Filter(new FilterCriteria { Ruleset = rulesets.AvailableRulesets.ElementAt(0) }, false));
AddStep("select filtered map skipping filtered", () => carousel.SelectBeatmap(testMixed.Beatmaps[1], false));
AddAssert("unfiltered beatmap not selected", () => carousel.SelectedBeatmapInfo.Ruleset.OnlineID == 0);
AddStep("remove mixed set", () =>
{
carousel.RemoveBeatmapSet(testMixed);
testMixed = null;
});
BeatmapSetInfo testSingle = null;
AddStep("add single ruleset beatmapset", () =>
{
testSingle = TestResources.CreateTestBeatmapSetInfo(3);
testSingle.Beatmaps.ForEach(b =>
{
b.Ruleset = rulesets.AvailableRulesets.ElementAt(1);
});
carousel.UpdateBeatmapSet(testSingle);
});
AddStep("select filtered map skipping filtered", () => carousel.SelectBeatmap(testSingle.Beatmaps[0], false));
checkNoSelection();
AddStep("remove single ruleset set", () => carousel.RemoveBeatmapSet(testSingle));
}
[Test]
public void TestCarouselRemembersSelection()
{
List<BeatmapSetInfo> manySets = new List<BeatmapSetInfo>();
for (int i = 1; i <= 50; i++)
manySets.Add(TestResources.CreateTestBeatmapSetInfo(3));
loadBeatmaps(manySets);
advanceSelection(direction: 1, diff: false);
for (int i = 0; i < 5; i++)
{
AddStep("Toggle non-matching filter", () =>
{
carousel.Filter(new FilterCriteria { SearchText = Guid.NewGuid().ToString() }, false);
});
AddStep("Restore no filter", () =>
{
carousel.Filter(new FilterCriteria(), false);
eagerSelectedIDs.Add(carousel.SelectedBeatmapSet.ID);
});
}
// always returns to same selection as long as it's available.
AddAssert("Selection was remembered", () => eagerSelectedIDs.Count == 1);
}
[Test]
public void TestRandomFallbackOnNonMatchingPrevious()
{
List<BeatmapSetInfo> manySets = new List<BeatmapSetInfo>();
AddStep("populate maps", () =>
{
for (int i = 0; i < 10; i++)
{
manySets.Add(TestResources.CreateTestBeatmapSetInfo(3, new[]
{
// all taiko except for first
rulesets.GetRuleset(i > 0 ? 1 : 0)
}));
}
});
loadBeatmaps(manySets);
for (int i = 0; i < 10; i++)
{
AddStep("Reset filter", () => carousel.Filter(new FilterCriteria(), false));
AddStep("select first beatmap", () => carousel.SelectBeatmap(manySets.First().Beatmaps.First()));
AddStep("Toggle non-matching filter", () =>
{
carousel.Filter(new FilterCriteria { SearchText = Guid.NewGuid().ToString() }, false);
});
AddAssert("selection lost", () => carousel.SelectedBeatmapInfo == null);
AddStep("Restore different ruleset filter", () =>
{
carousel.Filter(new FilterCriteria { Ruleset = rulesets.GetRuleset(1) }, false);
eagerSelectedIDs.Add(carousel.SelectedBeatmapSet.ID);
});
AddAssert("selection changed", () => !carousel.SelectedBeatmapInfo.Equals(manySets.First().Beatmaps.First()));
}
AddAssert("Selection was random", () => eagerSelectedIDs.Count > 2);
}
[Test]
public void TestFilteringByUserStarDifficulty()
{
BeatmapSetInfo set = null;
loadBeatmaps(new List<BeatmapSetInfo>());
AddStep("add mixed difficulty set", () =>
{
set = TestResources.CreateTestBeatmapSetInfo(1);
set.Beatmaps.Clear();
for (int i = 1; i <= 15; i++)
{
set.Beatmaps.Add(new BeatmapInfo(new OsuRuleset().RulesetInfo, new BeatmapDifficulty(), new BeatmapMetadata())
{
DifficultyName = $"Stars: {i}",
StarRating = i,
});
}
carousel.UpdateBeatmapSet(set);
});
AddStep("select added set", () => carousel.SelectBeatmap(set.Beatmaps[0], false));
AddStep("filter [5..]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 5 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 11);
AddStep("filter to [0..7]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Max = 7 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 7);
AddStep("filter to [5..7]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 5, Max = 7 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 3);
AddStep("filter [2..2]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 2, Max = 2 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 1);
AddStep("filter to [0..]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 0 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 15);
}
private void loadBeatmaps(List<BeatmapSetInfo> beatmapSets = null, Func<FilterCriteria> initialCriteria = null, Action<BeatmapCarousel> carouselAdjust = null, int? count = null, bool randomDifficulties = false)
{
bool changed = false;
if (beatmapSets == null)
{
beatmapSets = new List<BeatmapSetInfo>();
for (int i = 1; i <= (count ?? set_count); i++)
{
beatmapSets.Add(randomDifficulties
? TestResources.CreateTestBeatmapSetInfo()
: TestResources.CreateTestBeatmapSetInfo(3));
}
}
createCarousel(beatmapSets, c =>
{
carouselAdjust?.Invoke(c);
carousel.Filter(initialCriteria?.Invoke() ?? new FilterCriteria());
carousel.BeatmapSetsChanged = () => changed = true;
carousel.BeatmapSets = beatmapSets;
});
AddUntilStep("Wait for load", () => changed);
}
private void createCarousel(List<BeatmapSetInfo> beatmapSets, Action<BeatmapCarousel> carouselAdjust = null, Container target = null)
{
AddStep("Create carousel", () =>
{
selectedSets.Clear();
eagerSelectedIDs.Clear();
carousel = new TestBeatmapCarousel
{
RelativeSizeAxes = Axes.Both,
};
carouselAdjust?.Invoke(carousel);
carousel.BeatmapSets = beatmapSets;
(target ?? this).Child = carousel;
});
}
private void ensureRandomFetchSuccess() =>
AddAssert("ensure prev random fetch worked", () => selectedSets.Peek().Equals(carousel.SelectedBeatmapSet));
private void waitForSelection(int set, int? diff = null) =>
AddUntilStep($"selected is set{set}{(diff.HasValue ? $" diff{diff.Value}" : "")}", () =>
{
if (diff != null)
return carousel.SelectedBeatmapInfo?.Equals(carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Skip(diff.Value - 1).First()) == true;
return carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Contains(carousel.SelectedBeatmapInfo);
});
private void setSelected(int set, int diff) =>
AddStep($"select set{set} diff{diff}", () =>
carousel.SelectBeatmap(carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Skip(diff - 1).First()));
private void advanceSelection(bool diff, int direction = 1, int count = 1)
{
if (count == 1)
{
AddStep($"select {(direction > 0 ? "next" : "prev")} {(diff ? "diff" : "set")}", () =>
carousel.SelectNext(direction, !diff));
}
else
{
AddRepeatStep($"select {(direction > 0 ? "next" : "prev")} {(diff ? "diff" : "set")}", () =>
carousel.SelectNext(direction, !diff), count);
}
}
private void checkVisibleItemCount(bool diff, int count)
{
// until step required as we are querying against alive items, which are loaded asynchronously inside DrawableCarouselBeatmapSet.
AddUntilStep($"{count} {(diff ? "diffs" : "sets")} visible", () =>
carousel.Items.Count(s => (diff ? s.Item is CarouselBeatmap : s.Item is CarouselBeatmapSet) && s.Item.Visible) == count);
}
private void checkSelectionIsCentered()
{
AddAssert("Selected panel is centered", () =>
{
return Precision.AlmostEquals(
carousel.ScreenSpaceDrawQuad.Centre,
carousel.Items
.First(i => i.Item.State.Value == CarouselItemState.Selected)
.ScreenSpaceDrawQuad.Centre, 100);
});
}
private void checkNoSelection() => AddAssert("Selection is null", () => currentSelection == null);
private void nextRandom() =>
AddStep("select random next", () =>
{
carousel.RandomAlgorithm.Value = RandomSelectAlgorithm.RandomPermutation;
if (!selectedSets.Any() && carousel.SelectedBeatmapInfo != null)
selectedSets.Push(carousel.SelectedBeatmapSet);
carousel.SelectNextRandom();
selectedSets.Push(carousel.SelectedBeatmapSet);
});
private void ensureRandomDidntRepeat() =>
AddAssert("ensure no repeats", () => selectedSets.Distinct().Count() == selectedSets.Count);
private void prevRandom() => AddStep("select random last", () =>
{
carousel.SelectPreviousRandom();
selectedSets.Pop();
});
private bool selectedBeatmapVisible()
{
var currentlySelected = carousel.Items.FirstOrDefault(s => s.Item is CarouselBeatmap && s.Item.State.Value == CarouselItemState.Selected);
if (currentlySelected == null)
return true;
return currentlySelected.Item.Visible;
}
private void checkInvisibleDifficultiesUnselectable()
{
nextRandom();
AddAssert("Selection is visible", selectedBeatmapVisible);
}
private class TestBeatmapCarousel : BeatmapCarousel
{
public bool PendingFilterTask => PendingFilter != null;
public IEnumerable<DrawableCarouselItem> Items
{
get
{
foreach (var item in Scroll.Children)
{
yield return item;
if (item is DrawableCarouselBeatmapSet set)
{
foreach (var difficulty in set.DrawableBeatmaps)
yield return difficulty;
}
}
}
}
}
}
}
| |
using System;
using System.Web.Mvc;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core;
using Umbraco.Web.Security;
using System.Collections.Specialized;
namespace Umbraco.Web.Mvc
{
/// <summary>
/// The base controller that all Presentation Add-in controllers should inherit from
/// </summary>
[MergeModelStateToChildAction]
[MergeParentContextViewData]
public abstract class SurfaceController : PluginController
{
/// <summary>
/// Default constructor
/// </summary>
/// <param name="umbracoContext"></param>
protected SurfaceController(UmbracoContext umbracoContext)
: base(umbracoContext)
{
}
protected SurfaceController(UmbracoContext umbracoContext, UmbracoHelper umbracoHelper)
: base(umbracoContext, umbracoHelper)
{
}
/// <summary>
/// Empty constructor, uses Singleton to resolve the UmbracoContext
/// </summary>
protected SurfaceController()
: base(UmbracoContext.Current)
{
}
/// <summary>
/// Redirects to the Umbraco page with the given id
/// </summary>
/// <param name="pageId"></param>
/// <returns></returns>
protected RedirectToUmbracoPageResult RedirectToUmbracoPage(int pageId)
{
return new RedirectToUmbracoPageResult(pageId, UmbracoContext);
}
/// <summary>
/// Redirects to the Umbraco page with the given id and passes provided querystring
/// </summary>
/// <param name="pageId"></param>
/// <param name="queryStringValues"></param>
/// <returns></returns>
protected RedirectToUmbracoPageResult RedirectToUmbracoPage(int pageId, NameValueCollection queryStringValues)
{
return new RedirectToUmbracoPageResult(pageId, queryStringValues, UmbracoContext);
}
/// <summary>
/// Redirects to the Umbraco page with the given id and passes provided querystring
/// </summary>
/// <param name="pageId"></param>
/// <param name="queryString"></param>
/// <returns></returns>
protected RedirectToUmbracoPageResult RedirectToUmbracoPage(int pageId, string queryString)
{
return new RedirectToUmbracoPageResult(pageId, queryString, UmbracoContext);
}
/// <summary>
/// Redirects to the Umbraco page with the given id
/// </summary>
/// <param name="publishedContent"></param>
/// <returns></returns>
protected RedirectToUmbracoPageResult RedirectToUmbracoPage(IPublishedContent publishedContent)
{
return new RedirectToUmbracoPageResult(publishedContent, UmbracoContext);
}
/// <summary>
/// Redirects to the Umbraco page with the given id and passes provided querystring
/// </summary>
/// <param name="publishedContent"></param>
/// <param name="queryStringValues"></param>
/// <returns></returns>
protected RedirectToUmbracoPageResult RedirectToUmbracoPage(IPublishedContent publishedContent, NameValueCollection queryStringValues)
{
return new RedirectToUmbracoPageResult(publishedContent, queryStringValues, UmbracoContext);
}
/// <summary>
/// Redirects to the Umbraco page with the given id and passes provided querystring
/// </summary>
/// <param name="publishedContent"></param>
/// <param name="queryString"></param>
/// <returns></returns>
protected RedirectToUmbracoPageResult RedirectToUmbracoPage(IPublishedContent publishedContent, string queryString)
{
return new RedirectToUmbracoPageResult(publishedContent, queryString, UmbracoContext);
}
/// <summary>
/// Redirects to the currently rendered Umbraco page
/// </summary>
/// <returns></returns>
protected RedirectToUmbracoPageResult RedirectToCurrentUmbracoPage()
{
return new RedirectToUmbracoPageResult(CurrentPage, UmbracoContext);
}
/// <summary>
/// Redirects to the currently rendered Umbraco page and passes provided querystring
/// </summary>
/// <param name="queryStringValues"></param>
/// <returns></returns>
protected RedirectToUmbracoPageResult RedirectToCurrentUmbracoPage(NameValueCollection queryStringValues)
{
return new RedirectToUmbracoPageResult(CurrentPage, queryStringValues, UmbracoContext);
}
/// <summary>
/// Redirects to the currently rendered Umbraco page and passes provided querystring
/// </summary>
/// <param name="queryStringValues"></param>
/// <returns></returns>
protected RedirectToUmbracoPageResult RedirectToCurrentUmbracoPage(string queryString)
{
return new RedirectToUmbracoPageResult(CurrentPage, queryString, UmbracoContext);
}
/// <summary>
/// Redirects to the currently rendered Umbraco URL
/// </summary>
/// <returns></returns>
/// <remarks>
/// this is useful if you need to redirect
/// to the current page but the current page is actually a rewritten URL normally done with something like
/// Server.Transfer.
/// </remarks>
protected RedirectToUmbracoUrlResult RedirectToCurrentUmbracoUrl()
{
return new RedirectToUmbracoUrlResult(UmbracoContext);
}
/// <summary>
/// Returns the currently rendered Umbraco page
/// </summary>
/// <returns></returns>
protected UmbracoPageResult CurrentUmbracoPage()
{
return new UmbracoPageResult(ApplicationContext.ProfilingLogger);
}
/// <summary>
/// Gets the current page.
/// </summary>
protected virtual IPublishedContent CurrentPage
{
get
{
var routeDefAttempt = TryGetRouteDefinitionFromAncestorViewContexts();
if (!routeDefAttempt.Success)
{
throw routeDefAttempt.Exception;
}
var routeDef = routeDefAttempt.Result;
return routeDef.PublishedContentRequest.PublishedContent;
}
}
/// <summary>
/// we need to recursively find the route definition based on the parent view context
/// </summary>
/// <returns></returns>
/// <remarks>
/// We may have Child Actions within Child actions so we need to recursively look this up.
/// see: http://issues.umbraco.org/issue/U4-1844
/// </remarks>
private Attempt<RouteDefinition> TryGetRouteDefinitionFromAncestorViewContexts()
{
ControllerContext currentContext = ControllerContext;
while (currentContext != null)
{
var currentRouteData = currentContext.RouteData;
if (currentRouteData.DataTokens.ContainsKey(Core.Constants.Web.UmbracoRouteDefinitionDataToken))
{
return Attempt.Succeed((RouteDefinition)currentRouteData.DataTokens[Core.Constants.Web.UmbracoRouteDefinitionDataToken]);
}
if (currentContext.IsChildAction)
{
//assign current context to parent
currentContext = currentContext.ParentActionViewContext;
}
else
{
//exit the loop
currentContext = null;
}
}
return Attempt<RouteDefinition>.Fail(
new InvalidOperationException("Cannot find the Umbraco route definition in the route values, the request must be made in the context of an Umbraco request"));
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Spark.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable MemberCanBePrivate.Global
namespace Apache.Ignite.Core.Cache.Configuration
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Log;
/// <summary>
/// Query entity is a description of cache entry (composed of key and value)
/// in a way of how it must be indexed and can be queried.
/// </summary>
public sealed class QueryEntity : IQueryEntityInternal, IBinaryRawWriteAware
{
/** */
private Type _keyType;
/** */
private Type _valueType;
/** */
private string _valueTypeName;
/** */
private string _keyTypeName;
/** */
private Dictionary<string, string> _aliasMap;
/** */
private ICollection<QueryAlias> _aliases;
/// <summary>
/// Initializes a new instance of the <see cref="QueryEntity"/> class.
/// </summary>
public QueryEntity()
{
// No-op.
}
/// <summary>
/// Initializes a new instance of the <see cref="QueryEntity"/> class.
/// </summary>
/// <param name="valueType">Type of the cache entry value.</param>
public QueryEntity(Type valueType)
{
ValueType = valueType;
}
/// <summary>
/// Initializes a new instance of the <see cref="QueryEntity"/> class.
/// </summary>
/// <param name="keyType">Type of the key.</param>
/// <param name="valueType">Type of the value.</param>
public QueryEntity(Type keyType, Type valueType)
{
KeyType = keyType;
ValueType = valueType;
}
/// <summary>
/// Gets or sets key Java type name.
/// </summary>
public string KeyTypeName
{
get { return _keyTypeName; }
set
{
_keyTypeName = value;
_keyType = null;
}
}
/// <summary>
/// Gets or sets the type of the key.
/// <para />
/// This is a shortcut for <see cref="KeyTypeName"/>. Getter will return null for non-primitive types.
/// <para />
/// Setting this property will overwrite <see cref="Fields"/> and <see cref="Indexes"/> according to
/// <see cref="QuerySqlFieldAttribute"/>, if any.
/// </summary>
public Type KeyType
{
get { return _keyType ?? JavaTypes.GetDotNetType(KeyTypeName); }
set
{
RescanAttributes(value, _valueType); // Do this first because it can throw
KeyTypeName = value == null
? null
: (JavaTypes.GetJavaTypeName(value) ?? BinaryUtils.GetSqlTypeName(value));
_keyType = value;
}
}
/// <summary>
/// Gets or sets value Java type name.
/// </summary>
public string ValueTypeName
{
get { return _valueTypeName; }
set
{
_valueTypeName = value;
_valueType = null;
}
}
/// <summary>
/// Gets or sets the type of the value.
/// <para />
/// This is a shortcut for <see cref="ValueTypeName"/>. Getter will return null for non-primitive types.
/// <para />
/// Setting this property will overwrite <see cref="Fields"/> and <see cref="Indexes"/> according to
/// <see cref="QuerySqlFieldAttribute"/>, if any.
/// </summary>
public Type ValueType
{
get { return _valueType ?? JavaTypes.GetDotNetType(ValueTypeName); }
set
{
RescanAttributes(_keyType, value); // Do this first because it can throw
ValueTypeName = value == null
? null
: (JavaTypes.GetJavaTypeName(value) ?? BinaryUtils.GetSqlTypeName(value));
_valueType = value;
}
}
/// <summary>
/// Gets or sets the name of the field that is used to denote the entire key.
/// <para />
/// By default, entity key can be accessed with a special "_key" field name.
/// </summary>
public string KeyFieldName { get; set; }
/// <summary>
/// Gets or sets the name of the field that is used to denote the entire value.
/// <para />
/// By default, entity value can be accessed with a special "_val" field name.
/// </summary>
public string ValueFieldName { get; set; }
/// <summary>
/// Gets or sets the name of the SQL table.
/// When not set, value type name is used.
/// </summary>
public string TableName { get; set; }
/// <summary>
/// Gets or sets query fields, a map from field name to Java type name.
/// The order of fields defines the order of columns returned by the 'select *' queries.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<QueryField> Fields { get; set; }
/// <summary>
/// Gets or sets field name aliases: mapping from full name in dot notation to an alias
/// that will be used as SQL column name.
/// Example: {"parent.name" -> "parentName"}.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<QueryAlias> Aliases
{
get { return _aliases; }
set
{
_aliases = value;
_aliasMap = null;
}
}
/// <summary>
/// Gets or sets the query indexes.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<QueryIndex> Indexes { get; set; }
/// <summary>
/// Gets the alias by field name, or null when no match found.
/// This method constructs a dictionary lazily to perform lookups.
/// </summary>
string IQueryEntityInternal.GetAlias(string fieldName)
{
if (Aliases == null || Aliases.Count == 0)
{
return null;
}
// PERF: No ToDictionary.
if (_aliasMap == null)
{
_aliasMap = new Dictionary<string, string>(Aliases.Count, StringComparer.Ordinal);
foreach (var alias in Aliases)
{
_aliasMap[alias.FullName] = alias.Alias;
}
}
string res;
return _aliasMap.TryGetValue(fieldName, out res) ? res : null;
}
/// <summary>
/// Initializes a new instance of the <see cref="QueryEntity"/> class.
/// </summary>
/// <param name="reader">The reader.</param>
internal QueryEntity(IBinaryRawReader reader)
{
KeyTypeName = reader.ReadString();
ValueTypeName = reader.ReadString();
TableName = reader.ReadString();
KeyFieldName = reader.ReadString();
ValueFieldName = reader.ReadString();
var count = reader.ReadInt();
Fields = count == 0
? null
: Enumerable.Range(0, count).Select(x => new QueryField(reader)).ToList();
count = reader.ReadInt();
Aliases = count == 0 ? null : Enumerable.Range(0, count)
.Select(x=> new QueryAlias(reader.ReadString(), reader.ReadString())).ToList();
count = reader.ReadInt();
Indexes = count == 0 ? null : Enumerable.Range(0, count).Select(x => new QueryIndex(reader)).ToList();
}
/// <summary>
/// Writes this instance.
/// </summary>
void IBinaryRawWriteAware<IBinaryRawWriter>.Write(IBinaryRawWriter writer)
{
writer.WriteString(KeyTypeName);
writer.WriteString(ValueTypeName);
writer.WriteString(TableName);
writer.WriteString(KeyFieldName);
writer.WriteString(ValueFieldName);
if (Fields != null)
{
writer.WriteInt(Fields.Count);
foreach (var field in Fields)
{
field.Write(writer);
}
}
else
writer.WriteInt(0);
if (Aliases != null)
{
writer.WriteInt(Aliases.Count);
foreach (var queryAlias in Aliases)
{
writer.WriteString(queryAlias.FullName);
writer.WriteString(queryAlias.Alias);
}
}
else
writer.WriteInt(0);
if (Indexes != null)
{
writer.WriteInt(Indexes.Count);
foreach (var index in Indexes)
{
if (index == null)
throw new InvalidOperationException("Invalid cache configuration: QueryIndex can't be null.");
index.Write(writer);
}
}
else
writer.WriteInt(0);
}
/// <summary>
/// Validates this instance and outputs information to the log, if necessary.
/// </summary>
internal void Validate(ILogger log, string logInfo)
{
Debug.Assert(log != null);
Debug.Assert(logInfo != null);
logInfo += string.Format(", QueryEntity '{0}:{1}'", _keyTypeName ?? "", _valueTypeName ?? "");
JavaTypes.LogIndirectMappingWarning(_keyType, log, logInfo);
JavaTypes.LogIndirectMappingWarning(_valueType, log, logInfo);
var fields = Fields;
if (fields != null)
{
foreach (var field in fields)
field.Validate(log, logInfo);
}
}
/// <summary>
/// Copies the local properties (properties that are not written in Write method).
/// </summary>
internal void CopyLocalProperties(QueryEntity entity)
{
Debug.Assert(entity != null);
if (entity._keyType != null)
{
_keyType = entity._keyType;
}
if (entity._valueType != null)
{
_valueType = entity._valueType;
}
if (Fields != null && entity.Fields != null)
{
var fields = entity.Fields.Where(x => x != null).ToDictionary(x => "_" + x.Name, x => x);
foreach (var field in Fields)
{
QueryField src;
if (fields.TryGetValue("_" + field.Name, out src))
{
field.CopyLocalProperties(src);
}
}
}
}
/// <summary>
/// Rescans the attributes in <see cref="KeyType"/> and <see cref="ValueType"/>.
/// </summary>
private void RescanAttributes(Type keyType, Type valType)
{
if (keyType == null && valType == null)
return;
var fields = new List<QueryField>();
var indexes = new List<QueryIndexEx>();
if (keyType != null)
ScanAttributes(keyType, fields, indexes, null, new HashSet<Type>(), true);
if (valType != null)
ScanAttributes(valType, fields, indexes, null, new HashSet<Type>(), false);
if (fields.Any())
Fields = fields.OrderBy(x => x.Name).ToList();
if (indexes.Any())
Indexes = GetGroupIndexes(indexes).ToArray();
}
/// <summary>
/// Gets the group indexes.
/// </summary>
/// <param name="indexes">Ungrouped indexes with their group names.</param>
/// <returns></returns>
private static IEnumerable<QueryIndex> GetGroupIndexes(List<QueryIndexEx> indexes)
{
return indexes.Where(idx => idx.IndexGroups != null)
.SelectMany(idx => idx.IndexGroups.Select(g => new {Index = idx, GroupName = g}))
.GroupBy(x => x.GroupName)
.Select(g =>
{
var idxs = g.Select(pair => pair.Index).ToArray();
var first = idxs.First();
return new QueryIndex(idxs.SelectMany(i => i.Fields).ToArray())
{
IndexType = first.IndexType,
Name = first.Name
};
})
.Concat(indexes.Where(idx => idx.IndexGroups == null));
}
/// <summary>
/// Scans specified type for occurences of <see cref="QuerySqlFieldAttribute" />.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="fields">The fields.</param>
/// <param name="indexes">The indexes.</param>
/// <param name="parentPropName">Name of the parent property.</param>
/// <param name="visitedTypes">The visited types.</param>
/// <param name="isKey">Whether this is a key type.</param>
/// <exception cref="System.InvalidOperationException">Recursive Query Field definition detected: + type</exception>
private static void ScanAttributes(Type type, List<QueryField> fields, List<QueryIndexEx> indexes,
string parentPropName, ISet<Type> visitedTypes, bool isKey)
{
Debug.Assert(type != null);
Debug.Assert(fields != null);
Debug.Assert(indexes != null);
if (visitedTypes.Contains(type))
throw new InvalidOperationException("Recursive Query Field definition detected: " + type);
visitedTypes.Add(type);
foreach (var memberInfo in ReflectionUtils.GetFieldsAndProperties(type))
{
var customAttributes = memberInfo.Key.GetCustomAttributes(true);
foreach (var attr in customAttributes.OfType<QuerySqlFieldAttribute>())
{
var columnName = attr.Name ?? memberInfo.Key.Name;
// Dot notation is required for nested SQL fields.
if (parentPropName != null)
{
columnName = parentPropName + "." + columnName;
}
if (attr.IsIndexed)
{
indexes.Add(new QueryIndexEx(columnName, attr.IsDescending, QueryIndexType.Sorted,
attr.IndexGroups)
{
InlineSize = attr.IndexInlineSize,
});
}
fields.Add(new QueryField(columnName, memberInfo.Value)
{
IsKeyField = isKey,
NotNull = attr.NotNull,
DefaultValue = attr.DefaultValue,
Precision = attr.Precision,
Scale = attr.Scale
});
ScanAttributes(memberInfo.Value, fields, indexes, columnName, visitedTypes, isKey);
}
foreach (var attr in customAttributes.OfType<QueryTextFieldAttribute>())
{
var columnName = attr.Name ?? memberInfo.Key.Name;
if (parentPropName != null)
{
columnName = parentPropName + "." + columnName;
}
indexes.Add(new QueryIndexEx(columnName, false, QueryIndexType.FullText, null));
fields.Add(new QueryField(columnName, memberInfo.Value) {IsKeyField = isKey});
ScanAttributes(memberInfo.Value, fields, indexes, columnName, visitedTypes, isKey);
}
}
visitedTypes.Remove(type);
}
/// <summary>
/// Extended index with group names.
/// </summary>
private class QueryIndexEx : QueryIndex
{
/// <summary>
/// Initializes a new instance of the <see cref="QueryIndexEx"/> class.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="isDescending">if set to <c>true</c> [is descending].</param>
/// <param name="indexType">Type of the index.</param>
/// <param name="groups">The groups.</param>
public QueryIndexEx(string fieldName, bool isDescending, QueryIndexType indexType,
ICollection<string> groups)
: base(isDescending, indexType, fieldName)
{
IndexGroups = groups;
}
/// <summary>
/// Gets or sets the index groups.
/// </summary>
public ICollection<string> IndexGroups { get; set; }
}
}
}
| |
using System;
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.CSharp.Articles.CreatePivotTablesPivotCharts
{
public class CreatePivotTableWithFormatting
{
public static void Run()
{
//Output directory
string outputDir = RunExamples.Get_OutputDirectory();
// Instantiating an Workbook object
Workbook workbook = new Workbook();
// Obtaining the reference of the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Name the sheet
sheet.Name = "Data";
// Setting the values to the cells
Cells cells = sheet.Cells;
Cell cell = cells["A1"];
cell.PutValue("Employee");
cell = cells["B1"];
cell.PutValue("Quarter");
cell = cells["C1"];
cell.PutValue("Product");
cell = cells["D1"];
cell.PutValue("Continent");
cell = cells["E1"];
cell.PutValue("Country");
cell = cells["F1"];
cell.PutValue("Sale");
cell = cells["A2"];
cell.PutValue("David");
cell = cells["A3"];
cell.PutValue("David");
cell = cells["A4"];
cell.PutValue("David");
cell = cells["A5"];
cell.PutValue("David");
cell = cells["A6"];
cell.PutValue("James");
cell = cells["A7"];
cell.PutValue("James");
cell = cells["A8"];
cell.PutValue("James");
cell = cells["A9"];
cell.PutValue("James");
cell = cells["A10"];
cell.PutValue("James");
cell = cells["A11"];
cell.PutValue("Miya");
cell = cells["A12"];
cell.PutValue("Miya");
cell = cells["A13"];
cell.PutValue("Miya");
cell = cells["A14"];
cell.PutValue("Miya");
cell = cells["A15"];
cell.PutValue("Miya");
cell = cells["A16"];
cell.PutValue("Miya");
cell = cells["A17"];
cell.PutValue("Miya");
cell = cells["A18"];
cell.PutValue("Elvis");
cell = cells["A19"];
cell.PutValue("Elvis");
cell = cells["A20"];
cell.PutValue("Elvis");
cell = cells["A21"];
cell.PutValue("Elvis");
cell = cells["A22"];
cell.PutValue("Elvis");
cell = cells["A23"];
cell.PutValue("Elvis");
cell = cells["A24"];
cell.PutValue("Elvis");
cell = cells["A25"];
cell.PutValue("Jean");
cell = cells["A26"];
cell.PutValue("Jean");
cell = cells["A27"];
cell.PutValue("Jean");
cell = cells["A28"];
cell.PutValue("Ada");
cell = cells["A29"];
cell.PutValue("Ada");
cell = cells["A30"];
cell.PutValue("Ada");
cell = cells["B2"];
cell.PutValue("1");
cell = cells["B3"];
cell.PutValue("2");
cell = cells["B4"];
cell.PutValue("3");
cell = cells["B5"];
cell.PutValue("4");
cell = cells["B6"];
cell.PutValue("1");
cell = cells["B7"];
cell.PutValue("2");
cell = cells["B8"];
cell.PutValue("3");
cell = cells["B9"];
cell.PutValue("4");
cell = cells["B10"];
cell.PutValue("4");
cell = cells["B11"];
cell.PutValue("1");
cell = cells["B12"];
cell.PutValue("1");
cell = cells["B13"];
cell.PutValue("2");
cell = cells["B14"];
cell.PutValue("2");
cell = cells["B15"];
cell.PutValue("3");
cell = cells["B16"];
cell.PutValue("4");
cell = cells["B17"];
cell.PutValue("4");
cell = cells["B18"];
cell.PutValue("1");
cell = cells["B19"];
cell.PutValue("1");
cell = cells["B20"];
cell.PutValue("2");
cell = cells["B21"];
cell.PutValue("3");
cell = cells["B22"];
cell.PutValue("3");
cell = cells["B23"];
cell.PutValue("4");
cell = cells["B24"];
cell.PutValue("4");
cell = cells["B25"];
cell.PutValue("1");
cell = cells["B26"];
cell.PutValue("2");
cell = cells["B27"];
cell.PutValue("3");
cell = cells["B28"];
cell.PutValue("1");
cell = cells["B29"];
cell.PutValue("2");
cell = cells["B30"];
cell.PutValue("3");
cell = cells["C2"];
cell.PutValue("Maxilaku");
cell = cells["C3"];
cell.PutValue("Maxilaku");
cell = cells["C4"];
cell.PutValue("Chai");
cell = cells["C5"];
cell.PutValue("Maxilaku");
cell = cells["C6"];
cell.PutValue("Chang");
cell = cells["C7"];
cell.PutValue("Chang");
cell = cells["C8"];
cell.PutValue("Chang");
cell = cells["C9"];
cell.PutValue("Chang");
cell = cells["C10"];
cell.PutValue("Chang");
cell = cells["C11"];
cell.PutValue("Geitost");
cell = cells["C12"];
cell.PutValue("Chai");
cell = cells["C13"];
cell.PutValue("Geitost");
cell = cells["C14"];
cell.PutValue("Geitost");
cell = cells["C15"];
cell.PutValue("Maxilaku");
cell = cells["C16"];
cell.PutValue("Geitost");
cell = cells["C17"];
cell.PutValue("Geitost");
cell = cells["C18"];
cell.PutValue("Ikuru");
cell = cells["C19"];
cell.PutValue("Ikuru");
cell = cells["C20"];
cell.PutValue("Ikuru");
cell = cells["C21"];
cell.PutValue("Ikuru");
cell = cells["C22"];
cell.PutValue("Ipoh Coffee");
cell = cells["C23"];
cell.PutValue("Ipoh Coffee");
cell = cells["C24"];
cell.PutValue("Ipoh Coffee");
cell = cells["C25"];
cell.PutValue("Chocolade");
cell = cells["C26"];
cell.PutValue("Chocolade");
cell = cells["C27"];
cell.PutValue("Chocolade");
cell = cells["C28"];
cell.PutValue("Chocolade");
cell = cells["C29"];
cell.PutValue("Chocolade");
cell = cells["C30"];
cell.PutValue("Chocolade");
cell = cells["D2"];
cell.PutValue("Asia");
cell = cells["D3"];
cell.PutValue("Asia");
cell = cells["D4"];
cell.PutValue("Asia");
cell = cells["D5"];
cell.PutValue("Asia");
cell = cells["D6"];
cell.PutValue("Europe");
cell = cells["D7"];
cell.PutValue("Europe");
cell = cells["D8"];
cell.PutValue("Europe");
cell = cells["D9"];
cell.PutValue("Europe");
cell = cells["D10"];
cell.PutValue("Europe");
cell = cells["D11"];
cell.PutValue("America");
cell = cells["D12"];
cell.PutValue("America");
cell = cells["D13"];
cell.PutValue("America");
cell = cells["D14"];
cell.PutValue("America");
cell = cells["D15"];
cell.PutValue("America");
cell = cells["D16"];
cell.PutValue("America");
cell = cells["D17"];
cell.PutValue("America");
cell = cells["D18"];
cell.PutValue("Europe");
cell = cells["D19"];
cell.PutValue("Europe");
cell = cells["D20"];
cell.PutValue("Europe");
cell = cells["D21"];
cell.PutValue("Oceania");
cell = cells["D22"];
cell.PutValue("Oceania");
cell = cells["D23"];
cell.PutValue("Oceania");
cell = cells["D24"];
cell.PutValue("Oceania");
cell = cells["D25"];
cell.PutValue("Africa");
cell = cells["D26"];
cell.PutValue("Africa");
cell = cells["D27"];
cell.PutValue("Africa");
cell = cells["D28"];
cell.PutValue("Africa");
cell = cells["D29"];
cell.PutValue("Africa");
cell = cells["D30"];
cell.PutValue("Africa");
cell = cells["E2"];
cell.PutValue("China");
cell = cells["E3"];
cell.PutValue("India");
cell = cells["E4"];
cell.PutValue("Korea");
cell = cells["E5"];
cell.PutValue("India");
cell = cells["E6"];
cell.PutValue("France");
cell = cells["E7"];
cell.PutValue("France");
cell = cells["E8"];
cell.PutValue("Germany");
cell = cells["E9"];
cell.PutValue("Italy");
cell = cells["E10"];
cell.PutValue("France");
cell = cells["E11"];
cell.PutValue("U.S.");
cell = cells["E12"];
cell.PutValue("U.S.");
cell = cells["E13"];
cell.PutValue("Brazil");
cell = cells["E14"];
cell.PutValue("U.S.");
cell = cells["E15"];
cell.PutValue("U.S.");
cell = cells["E16"];
cell.PutValue("Canada");
cell = cells["E17"];
cell.PutValue("U.S.");
cell = cells["E18"];
cell.PutValue("Italy");
cell = cells["E19"];
cell.PutValue("France");
cell = cells["E20"];
cell.PutValue("Italy");
cell = cells["E21"];
cell.PutValue("New Zealand");
cell = cells["E22"];
cell.PutValue("Australia");
cell = cells["E23"];
cell.PutValue("Australia");
cell = cells["E24"];
cell.PutValue("New Zealand");
cell = cells["E25"];
cell.PutValue("S.Africa");
cell = cells["E26"];
cell.PutValue("S.Africa");
cell = cells["E27"];
cell.PutValue("S.Africa");
cell = cells["E28"];
cell.PutValue("Egypt");
cell = cells["E29"];
cell.PutValue("Egypt");
cell = cells["E30"];
cell.PutValue("Egypt");
cell = cells["F2"];
cell.PutValue(2000);
cell = cells["F3"];
cell.PutValue(500);
cell = cells["F4"];
cell.PutValue(1200);
cell = cells["F5"];
cell.PutValue(1500);
cell = cells["F6"];
cell.PutValue(500);
cell = cells["F7"];
cell.PutValue(1500);
cell = cells["F8"];
cell.PutValue(800);
cell = cells["F9"];
cell.PutValue(900);
cell = cells["F10"];
cell.PutValue(500);
cell = cells["F11"];
cell.PutValue(1600);
cell = cells["F12"];
cell.PutValue(600);
cell = cells["F13"];
cell.PutValue(2000);
cell = cells["F14"];
cell.PutValue(500);
cell = cells["F15"];
cell.PutValue(900);
cell = cells["F16"];
cell.PutValue(700);
cell = cells["F17"];
cell.PutValue(1400);
cell = cells["F18"];
cell.PutValue(1350);
cell = cells["F19"];
cell.PutValue(300);
cell = cells["F20"];
cell.PutValue(500);
cell = cells["F21"];
cell.PutValue(1000);
cell = cells["F22"];
cell.PutValue(1500);
cell = cells["F23"];
cell.PutValue(1500);
cell = cells["F24"];
cell.PutValue(1600);
cell = cells["F25"];
cell.PutValue(1000);
cell = cells["F26"];
cell.PutValue(1200);
cell = cells["F27"];
cell.PutValue(1300);
cell = cells["F28"];
cell.PutValue(1500);
cell = cells["F29"];
cell.PutValue(1400);
cell = cells["F30"];
cell.PutValue(1000);
// Adding a new sheet
Worksheet sheet2 = workbook.Worksheets[workbook.Worksheets.Add()];
// Naming the sheet
sheet2.Name = "PivotTable";
// Getting the pivottables collection in the sheet
Aspose.Cells.Pivot.PivotTableCollection pivotTables = sheet2.PivotTables;
// Adding a PivotTable to the worksheet
int index = pivotTables.Add("=Data!A1:F30", "B3", "PivotTable1");
// Accessing the instance of the newly added PivotTable
Aspose.Cells.Pivot.PivotTable pivotTable = pivotTables[index];
// Showing the grand totals
pivotTable.RowGrand = true;
pivotTable.ColumnGrand = true;
// Setting the PivotTable report is automatically formatted
pivotTable.IsAutoFormat = true;
// Setting the PivotTable autoformat type.
pivotTable.AutoFormatType = Aspose.Cells.Pivot.PivotTableAutoFormatType.Report6;
// Draging the first field to the row area.
pivotTable.AddFieldToArea(Aspose.Cells.Pivot.PivotFieldType.Row, 0);
// Draging the third field to the row area.
pivotTable.AddFieldToArea(Aspose.Cells.Pivot.PivotFieldType.Row, 2);
// Draging the second field to the row area.
pivotTable.AddFieldToArea(Aspose.Cells.Pivot.PivotFieldType.Row, 1);
// Draging the fourth field to the column area.
pivotTable.AddFieldToArea(Aspose.Cells.Pivot.PivotFieldType.Column, 3);
// Draging the fifth field to the data area.
pivotTable.AddFieldToArea(Aspose.Cells.Pivot.PivotFieldType.Data, 5);
// Setting the number format of the first data field
pivotTable.DataFields[0].NumberFormat = "$#,##0.00";
// Saving the Excel file
workbook.Save(outputDir + "outputCreatePivotTableWithFormatting.xlsx");
Console.WriteLine("CreatePivotTableWithFormatting executed successfully.");
}
}
}
| |
#region Using directives
using SimpleFramework.Xml.Core;
using SimpleFramework.Xml.Strategy;
using SimpleFramework.Xml;
using System;
#endregion
namespace SimpleFramework.Xml.Strategy {
public class PrimitiveCycleTest : ValidationTestCase {
private const String SOURCE =
"<?xml version=\"1.0\"?>\n"+
"<test>\n"+
" <primitive>\n"+
" <bool>true</bool>\r\n"+
" <byte>16</byte> \n\r"+
" <short>120</short> \n\r"+
" <int>1234</int>\n"+
" <float>1234.56</float> \n\r"+
" <long>1234567</long>\n"+
" <double>1234567.89</double> \n\r"+
" </primitive>\n"+
" <object>\n"+
" <Boolean>true</Boolean>\r\n"+
" <Byte>16</Byte> \n\r"+
" <Short>120</Short> \n\r"+
" <Integer>1234</Integer>\n"+
" <Float>1234.56</Float> \n\r"+
" <Long>1234567</Long>\n"+
" <Double>1234567.89</Double> \n\r"+
" <String>text value</String>\n\r"+
" <Enum>TWO</Enum>\n"+
" </object>\n\r"+
"</test>";
[Root(Name="test")]
private static class PrimitiveCycleEntry {
[Element(Name="primitive")]
private PrimitiveEntry primitive;
[Element(Name="object")]
private ObjectEntry object;
}
private static class PrimitiveEntry {
[Element(Name="bool")]
private bool boolValue;
[Element(Name="byte")]
private byte byteValue;
[Element(Name="short")]
private short shortValue;
[Element(Name="int")]
private int intValue;
[Element(Name="float")]
private float floatValue;
[Element(Name="long")]
private long longValue;
[Element(Name="double")]
private double doubleValue;
}
private static class ObjectEntry {
[Element(Name="Boolean")]
private Boolean boolValue;
[Element(Name="Byte")]
private Byte byteValue;
[Element(Name="Short")]
private Short shortValue;
[Element(Name="Integer")]
private Integer intValue;
[Element(Name="Float")]
private Float floatValue;
[Element(Name="Long")]
private Long longValue;
[Element(Name="Double")]
private Double doubleValue;
[Element(Name="String")]
private String stringValue;
[Element(Name="Enum")]
private TestEnum enumValue;
}
private static enum TestEnum {
ONE,
TWO,
THREE
}
[Root]
private static class StringReferenceExample {
[Element]
private String a;
[Element]
private String b;
[Element]
private String c;
public StringReferenceExample() {
super();
}
public StringReferenceExample(String a, String b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
}
[Root]
private static class IntegerReferenceExample {
[Element]
private Integer a;
[Element]
private Integer b;
[Element]
private Integer c;
public IntegerReferenceExample() {
super();
}
public IntegerReferenceExample(Integer a, Integer b, Integer c) {
this.a = a;
this.b = b;
this.c = c;
}
}
private Persister persister;
public void SetUp() {
persister = new Persister(new CycleStrategy());
}
public void TestPrimitive() {
PrimitiveCycleEntry entry = persister.Read(PrimitiveCycleEntry.class, SOURCE);
AssertEquals(entry.primitive.boolValue, true);
AssertEquals(entry.primitive.byteValue, 16);
AssertEquals(entry.primitive.shortValue, 120);
AssertEquals(entry.primitive.intValue, 1234);
AssertEquals(entry.primitive.floatValue, 1234.56f);
AssertEquals(entry.primitive.longValue, 1234567l);
AssertEquals(entry.primitive.doubleValue, 1234567.89d);
AssertEquals(entry.object.boolValue, Boolean.TRUE);
AssertEquals(entry.object.byteValue, new Byte("16"));
AssertEquals(entry.object.shortValue, new Short("120"));
AssertEquals(entry.object.intValue, new Integer(1234));
AssertEquals(entry.object.floatValue, new Float(1234.56));
AssertEquals(entry.object.longValue, new Long(1234567));
AssertEquals(entry.object.doubleValue, new Double(1234567.89));
AssertEquals(entry.object.stringValue, "text value");
AssertEquals(entry.object.enumValue, TestEnum.TWO);
StringWriter out = new StringWriter();
persister.Write(entry, out);
String text = out.toString();
assertXpathExists("/test[@id='0']", text);
assertXpathExists("/test/primitive[@id='1']", text);
assertXpathExists("/test/object[@id='2']", text);
assertXpathEvaluatesTo("true", "/test/primitive/bool", text);
assertXpathEvaluatesTo("16", "/test/primitive/byte", text);
assertXpathEvaluatesTo("120", "/test/primitive/short", text);
assertXpathEvaluatesTo("1234", "/test/primitive/int", text);
assertXpathEvaluatesTo("1234.56", "/test/primitive/float", text);
assertXpathEvaluatesTo("1234567", "/test/primitive/long", text);
assertXpathEvaluatesTo("1234567.89", "/test/primitive/double", text);
assertXpathEvaluatesTo("true", "/test/object/Boolean", text);
assertXpathEvaluatesTo("16", "/test/object/Byte", text);
assertXpathEvaluatesTo("120", "/test/object/Short", text);
assertXpathEvaluatesTo("1234", "/test/object/Integer", text);
assertXpathEvaluatesTo("1234.56", "/test/object/Float", text);
assertXpathEvaluatesTo("1234567", "/test/object/Long", text);
assertXpathEvaluatesTo("1234567.89", "/test/object/Double", text);
assertXpathEvaluatesTo("text value", "/test/object/String", text);
assertXpathEvaluatesTo("TWO", "/test/object/Enum", text);
Validate(entry, persister);
}
public void TestPrimitiveReference() {
StringReferenceExample example = new StringReferenceExample("a", "a", "a");
StringWriter out = new StringWriter();
persister.Write(example, out);
String text = out.toString();
assertXpathExists("/stringReferenceExample[@id='0']", text);
assertXpathExists("/stringReferenceExample/a[@id='1']", text);
assertXpathExists("/stringReferenceExample/b[@reference='1']", text);
assertXpathExists("/stringReferenceExample/c[@reference='1']", text);
Validate(example, persister);
example = new StringReferenceExample("a", "b", "a");
out = new StringWriter();
persister.Write(example, out);
text = out.toString();
assertXpathExists("/stringReferenceExample[@id='0']", text);
assertXpathExists("/stringReferenceExample/a[@id='1']", text);
assertXpathExists("/stringReferenceExample/b[@id='2']", text);
assertXpathExists("/stringReferenceExample/c[@reference='1']", text);
Validate(example, persister);
Integer one = new Integer(1);
Integer two = new Integer(1);
Integer three = new Integer(1);
IntegerReferenceExample integers = new IntegerReferenceExample(one, two, three);
out = new StringWriter();
persister.Write(integers, out);
text = out.toString();
assertXpathExists("/integerReferenceExample[@id='0']", text);
assertXpathExists("/integerReferenceExample/a[@id='1']", text);
assertXpathExists("/integerReferenceExample/b[@id='2']", text);
assertXpathExists("/integerReferenceExample/c[@id='3']", text);
Validate(integers, persister);
integers = new IntegerReferenceExample(one, one, two);
out = new StringWriter();
persister.Write(integers, out);
text = out.toString();
assertXpathExists("/integerReferenceExample[@id='0']", text);
assertXpathExists("/integerReferenceExample/a[@id='1']", text);
assertXpathExists("/integerReferenceExample/b[@reference='1']", text);
assertXpathExists("/integerReferenceExample/c[@id='2']", text);
Validate(integers, persister);
}
}
}
| |
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// A client for issuing REST requests to the Azure Batch service.
/// </summary>
public partial class BatchServiceClient : ServiceClient<BatchServiceClient>, IBatchServiceClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Client API Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IApplicationOperations.
/// </summary>
public virtual IApplicationOperations Application { get; private set; }
/// <summary>
/// Gets the IPoolOperations.
/// </summary>
public virtual IPoolOperations Pool { get; private set; }
/// <summary>
/// Gets the IAccountOperations.
/// </summary>
public virtual IAccountOperations Account { get; private set; }
/// <summary>
/// Gets the IJobOperations.
/// </summary>
public virtual IJobOperations Job { get; private set; }
/// <summary>
/// Gets the ICertificateOperations.
/// </summary>
public virtual ICertificateOperations Certificate { get; private set; }
/// <summary>
/// Gets the IFileOperations.
/// </summary>
public virtual IFileOperations File { get; private set; }
/// <summary>
/// Gets the IJobScheduleOperations.
/// </summary>
public virtual IJobScheduleOperations JobSchedule { get; private set; }
/// <summary>
/// Gets the ITaskOperations.
/// </summary>
public virtual ITaskOperations Task { get; private set; }
/// <summary>
/// Gets the IComputeNodeOperations.
/// </summary>
public virtual IComputeNodeOperations ComputeNode { get; private set; }
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected BatchServiceClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected BatchServiceClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected BatchServiceClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected BatchServiceClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BatchServiceClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BatchServiceClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BatchServiceClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BatchServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BatchServiceClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.Application = new ApplicationOperations(this);
this.Pool = new PoolOperations(this);
this.Account = new AccountOperations(this);
this.Job = new JobOperations(this);
this.Certificate = new CertificateOperations(this);
this.File = new FileOperations(this);
this.JobSchedule = new JobScheduleOperations(this);
this.Task = new TaskOperations(this);
this.ComputeNode = new ComputeNodeOperations(this);
this.BaseUri = new Uri("https://batch.core.windows.net");
this.ApiVersion = "2016-07-01.3.1";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, 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.
//
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace NLog.Fluent
{
/// <summary>
/// A fluent class to build log events for NLog.
/// </summary>
public class LogBuilder
{
private readonly LogEventInfo _logEvent;
private readonly ILogger _logger;
/// <summary>
/// Initializes a new instance of the <see cref="LogBuilder"/> class.
/// </summary>
/// <param name="logger">The <see cref="Logger"/> to send the log event.</param>
[CLSCompliant(false)]
public LogBuilder(ILogger logger)
: this(logger, LogLevel.Debug)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogBuilder"/> class.
/// </summary>
/// <param name="logger">The <see cref="Logger"/> to send the log event.</param>
/// <param name="logLevel">The <see cref="LogLevel"/> for the log event.</param>
[CLSCompliant(false)]
public LogBuilder(ILogger logger, LogLevel logLevel)
{
if (logger == null)
throw new ArgumentNullException(nameof(logger));
if (logLevel == null)
throw new ArgumentNullException(nameof(logLevel));
_logger = logger;
_logEvent = new LogEventInfo() { LoggerName = logger.Name, Level = logLevel };
}
/// <summary>
/// Gets the <see cref="LogEventInfo"/> created by the builder.
/// </summary>
public LogEventInfo LogEventInfo => _logEvent;
/// <summary>
/// Sets the <paramref name="exception"/> information of the logging event.
/// </summary>
/// <param name="exception">The exception information of the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Exception(Exception exception)
{
_logEvent.Exception = exception;
return this;
}
/// <summary>
/// Sets the level of the logging event.
/// </summary>
/// <param name="logLevel">The level of the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Level(LogLevel logLevel)
{
if (logLevel == null)
throw new ArgumentNullException(nameof(logLevel));
_logEvent.Level = logLevel;
return this;
}
/// <summary>
/// Sets the logger name of the logging event.
/// </summary>
/// <param name="loggerName">The logger name of the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder LoggerName(string loggerName)
{
_logEvent.LoggerName = loggerName;
return this;
}
/// <summary>
/// Sets the log message on the logging event.
/// </summary>
/// <param name="message">The log message for the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Message(string message)
{
_logEvent.Message = message;
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The object to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[MessageTemplateFormatMethod("format")]
public LogBuilder Message(string format, object arg0)
{
_logEvent.Message = format;
_logEvent.Parameters = new[] { arg0 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The first object to format.</param>
/// <param name="arg1">The second object to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[MessageTemplateFormatMethod("format")]
public LogBuilder Message(string format, object arg0, object arg1)
{
_logEvent.Message = format;
_logEvent.Parameters = new[] { arg0, arg1 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The first object to format.</param>
/// <param name="arg1">The second object to format.</param>
/// <param name="arg2">The third object to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[MessageTemplateFormatMethod("format")]
public LogBuilder Message(string format, object arg0, object arg1, object arg2)
{
_logEvent.Message = format;
_logEvent.Parameters = new[] { arg0, arg1, arg2 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The first object to format.</param>
/// <param name="arg1">The second object to format.</param>
/// <param name="arg2">The third object to format.</param>
/// <param name="arg3">The fourth object to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[MessageTemplateFormatMethod("format")]
public LogBuilder Message(string format, object arg0, object arg1, object arg2, object arg3)
{
_logEvent.Message = format;
_logEvent.Parameters = new[] { arg0, arg1, arg2, arg3 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[MessageTemplateFormatMethod("format")]
public LogBuilder Message(string format, params object[] args)
{
_logEvent.Message = format;
_logEvent.Parameters = args;
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A composite format string.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[MessageTemplateFormatMethod("format")]
public LogBuilder Message(IFormatProvider provider, string format, params object[] args)
{
_logEvent.FormatProvider = provider;
_logEvent.Message = format;
_logEvent.Parameters = args;
return this;
}
/// <summary>
/// Sets a per-event context property on the logging event.
/// </summary>
/// <param name="name">The name of the context property.</param>
/// <param name="value">The value of the context property.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Property(object name, object value)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
_logEvent.Properties[name] = value;
return this;
}
/// <summary>
/// Sets multiple per-event context properties on the logging event.
/// </summary>
/// <param name="properties">The properties to set.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Properties(IDictionary properties)
{
if (properties == null)
throw new ArgumentNullException(nameof(properties));
foreach (var key in properties.Keys)
{
_logEvent.Properties[key] = properties[key];
}
return this;
}
/// <summary>
/// Sets the timestamp of the logging event.
/// </summary>
/// <param name="timeStamp">The timestamp of the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder TimeStamp(DateTime timeStamp)
{
_logEvent.TimeStamp = timeStamp;
return this;
}
/// <summary>
/// Sets the stack trace for the event info.
/// </summary>
/// <param name="stackTrace">The stack trace.</param>
/// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder StackTrace(StackTrace stackTrace, int userStackFrame)
{
_logEvent.SetStackTrace(stackTrace, userStackFrame);
return this;
}
#if NET4_5
/// <summary>
/// Writes the log event to the underlying logger.
/// </summary>
/// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param>
/// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param>
public void Write(
[CallerMemberName]string callerMemberName = null,
[CallerFilePath]string callerFilePath = null,
[CallerLineNumber]int callerLineNumber = 0)
{
if (!_logger.IsEnabled(_logEvent.Level))
return;
// TODO NLog ver. 5 - Remove these properties
if (callerMemberName != null)
Property("CallerMemberName", callerMemberName);
if (callerFilePath != null)
Property("CallerFilePath", callerFilePath);
if (callerLineNumber != 0)
Property("CallerLineNumber", callerLineNumber);
_logEvent.SetCallerInfo(null, callerMemberName, callerFilePath, callerLineNumber);
_logger.Log(_logEvent);
}
#else
/// <summary>
/// Writes the log event to the underlying logger.
/// </summary>
public void Write()
{
_logger.Log(_logEvent);
}
#endif
#if NET4_5
/// <summary>
/// Writes the log event to the underlying logger if the condition delegate is true.
/// </summary>
/// <param name="condition">If condition is true, write log event; otherwise ignore event.</param>
/// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param>
/// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param>
public void WriteIf(
Func<bool> condition,
[CallerMemberName]string callerMemberName = null,
[CallerFilePath]string callerFilePath = null,
[CallerLineNumber]int callerLineNumber = 0)
{
if (condition == null || !condition() || !_logger.IsEnabled(_logEvent.Level))
return;
if (callerMemberName != null)
Property("CallerMemberName", callerMemberName);
if (callerFilePath != null)
Property("CallerFilePath", callerFilePath);
if (callerLineNumber != 0)
Property("CallerLineNumber", callerLineNumber);
_logEvent.SetCallerInfo(null, callerMemberName, callerFilePath, callerLineNumber);
_logger.Log(_logEvent);
}
#else
/// <summary>
/// Writes the log event to the underlying logger.
/// </summary>
/// <param name="condition">If condition is true, write log event; otherwise ignore event.</param>
public void WriteIf(Func<bool> condition)
{
if (condition == null || !condition() || !_logger.IsEnabled(_logEvent.Level))
return;
_logger.Log(_logEvent);
}
#endif
#if NET4_5
/// <summary>
/// Writes the log event to the underlying logger if the condition is true.
/// </summary>
/// <param name="condition">If condition is true, write log event; otherwise ignore event.</param>
/// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param>
/// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param>
public void WriteIf(
bool condition,
[CallerMemberName]string callerMemberName = null,
[CallerFilePath]string callerFilePath = null,
[CallerLineNumber]int callerLineNumber = 0)
{
if (!condition || !_logger.IsEnabled(_logEvent.Level))
return;
if (callerMemberName != null)
Property("CallerMemberName", callerMemberName);
if (callerFilePath != null)
Property("CallerFilePath", callerFilePath);
if (callerLineNumber != 0)
Property("CallerLineNumber", callerLineNumber);
_logEvent.SetCallerInfo(null, callerMemberName, callerFilePath, callerLineNumber);
_logger.Log(_logEvent);
}
#else
/// <summary>
/// Writes the log event to the underlying logger.
/// </summary>
/// <param name="condition">If condition is true, write log event; otherwise ignore event.</param>
public void WriteIf(bool condition)
{
if (!condition || !_logger.IsEnabled(_logEvent.Level))
return;
_logger.Log(_logEvent);
}
#endif
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
namespace Shielded
{
/// <summary>
/// Supports adding at both ends O(1), taking from head O(1), and every other op
/// involves a search, O(n). Enumerating must be done in transaction, unless you
/// read only one element, e.g. using LINQ Any or First.
/// The 'Nc' stands for 'no count' - the number of items can only be obtained by
/// enumerating. This enables it to be faster in other ops, since counters are
/// very contentious.
/// For a sequence with a counter, see <see cref="ShieldedSeq<T>"/>.
/// </summary>
public class ShieldedSeqNc<T> : IEnumerable<T>
{
private class ItemKeeper
{
public readonly T Value;
public readonly Shielded<ItemKeeper> Next;
public ItemKeeper(T val, ItemKeeper next, object owner)
{
Value = val;
Next = new Shielded<ItemKeeper>(next, owner);
}
public void ClearNext()
{
// this somehow fixes the leak in Queue test... cannot explain it.
Next.Value = null;
}
}
// a ShieldedRef should always be readonly! unfortunate, really. if you forget, a horrible
// class of error becomes possible..
private readonly Shielded<ItemKeeper> _head;
private readonly Shielded<ItemKeeper> _tail;
private readonly object _owner;
private Shielded<ItemKeeper> CreateRef(ItemKeeper item = null)
{
return new Shielded<ItemKeeper>(item, _owner);
}
/// <summary>
/// Initialize a new sequence with the given initial contents.
/// </summary>
/// <param name="items">Initial items.</param>
/// <param name="owner">If this is given, then in WhenCommitting subscriptions
/// this shielded will report its owner instead of itself.</param>
public ShieldedSeqNc(T[] items, object owner)
{
_owner = owner ?? this;
ItemKeeper item = null;
for (int i = items.Length - 1; i >= 0; i--)
{
item = new ItemKeeper(items[i], item, _owner);
if (_tail == null)
_tail = CreateRef(item);
}
_head = CreateRef(item);
// if this is true, there were no items.
if (_tail == null)
_tail = CreateRef();
}
/// <summary>
/// Initialize a new sequence with the given initial contents.
/// </summary>
public ShieldedSeqNc(params T[] items) : this(items, null) { }
/// <summary>
/// Initialize a new empty sequence.
/// </summary>
public ShieldedSeqNc(object owner = null)
{
_owner = owner ?? this;
_head = CreateRef();
_tail = CreateRef();
}
/// <summary>
/// Prepend an item, i.e. insert at index 0.
/// </summary>
public void Prepend(T val)
{
var keeper = new ItemKeeper(val, _head, _owner);
if (_head.Value == null)
_tail.Value = keeper;
_head.Value = keeper;
}
/// <summary>
/// Peek at the first element. Throws <see cref="InvalidOperationException"/> if
/// there is none.
/// </summary>
public T Head
{
get
{
// single read => safe out of transaction.
var h = _head.Value;
if (h == null) throw new InvalidOperationException();
return h.Value;
}
}
/// <summary>
/// Remove the first element of the sequence, and return it.
/// </summary>
public T TakeHead()
{
return Consume.Take(1).Single();
}
/// <summary>
/// Remove and yield elements from the head of the sequence.
/// </summary>
public IEnumerable<T> Consume
{
get
{
while (true)
{
var item = _head.Value;
if (item == null)
yield break;
Skip(_head);
// NB we don't read the tail if not needed!
if (_head.Value == null)
_tail.Value = null;
yield return item.Value;
}
}
}
/// <summary>
/// Append the specified value, commutatively - if you don't / haven't touched the
/// sequence in this transaction (using other methods/properties), this will not cause
/// conflicts! Effectively, the value is simply appended to whatever the sequence
/// is at commit time. Multiple calls to Append made in one transaction will
/// append the items in that order - they commute with other transactions only.
/// </summary>
public void Append(T val)
{
var newItem = new ItemKeeper(val, null, _owner);
Shield.EnlistCommute(() => {
if (_head.Value == null)
{
_head.Value = newItem;
_tail.Value = newItem;
}
else
{
_tail.Modify((ref ItemKeeper t) => {
t.Next.Value = newItem;
t = newItem;
});
}
}, _head, _tail); // the commute degenerates if you read from the seq..
}
private Shielded<ItemKeeper> RefToIndex(int index, bool plusOne = false)
{
return Shield.InTransaction(() => {
if (index < 0)
throw new IndexOutOfRangeException();
var curr = _head;
for (; index > 0; index--)
{
if (curr.Value == null)
throw new IndexOutOfRangeException();
curr = curr.Value.Next;
}
if (!plusOne && curr.Value == null)
throw new IndexOutOfRangeException();
return curr;
});
}
/// <summary>
/// Get or set the item at the specified index. This iterates through the internal
/// linked list, so it is not efficient for large sequences.
/// </summary>
public T this [int index]
{
get
{
return RefToIndex(index).Value.Value;
}
set
{
RefToIndex(index).Modify((ref ItemKeeper r) => {
var newItem = new ItemKeeper(value, r.Next, _owner);
if (r.Next.Value == null)
_tail.Value = newItem;
r.ClearNext();
r = newItem;
});
}
}
private static void Skip(Shielded<ItemKeeper> sh)
{
sh.Modify((ref ItemKeeper c) => {
var old = c;
c = c.Next;
old.ClearNext();
});
}
/// <summary>
/// Remove from the sequence all items that satisfy the given predicate.
/// </summary>
public void RemoveAll(Func<T, bool> condition)
{
int _;
RemoveAll(condition, out _);
}
/// <summary>
/// Remove from the sequence all items that satisfy the given predicate.
/// Returns the number of removed items in an out param, guaranteed to
/// equal actual number of removed items even if the condition lambda throws.
/// </summary>
public void RemoveAll(Func<T, bool> condition, out int removed)
{
Shield.AssertInTransaction();
var curr = _head;
var tail = _tail.Value;
ItemKeeper previous = null;
removed = 0;
while (curr.Value != null)
{
if (condition(curr.Value.Value))
{
removed++;
if (tail == curr.Value)
{
_tail.Value = previous;
if (previous == null)
{
_head.Value = null;
break;
}
}
Skip(curr);
}
else
{
previous = curr;
curr = curr.Value.Next;
}
}
}
/// <summary>
/// Clear the sequence.
/// </summary>
public void Clear()
{
_head.Value = null;
_tail.Value = null;
}
/// <summary>
/// Remove the item at the given index.
/// </summary>
public void RemoveAt(int index)
{
Shield.AssertInTransaction();
if (index == 0)
{
if (_head.Value == null)
throw new IndexOutOfRangeException();
Skip(_head);
if (_head.Value == null)
_tail.Value = null;
}
else
{
// slightly more tricky, in case we need to change _tail
var r = RefToIndex(index - 1).Value;
Skip(r.Next);
if (r.Next.Value == null)
_tail.Value = r;
}
}
/// <summary>
/// Remove the specified item from the sequence.
/// </summary>
public bool Remove(T item, IEqualityComparer<T> comp = null)
{
Shield.AssertInTransaction();
if (comp == null) comp = EqualityComparer<T>.Default;
var curr = _head;
ItemKeeper previous = null;
while (curr.Value != null)
{
if (comp.Equals(item, curr.Value.Value))
{
if (curr.Value.Next.Value == null)
_tail.Value = previous;
Skip(curr);
return true;
}
else
{
previous = curr;
curr = curr.Value.Next;
}
}
return false;
}
/// <summary>
/// Search the sequence for the given item.
/// </summary>
/// <returns>The index of the item in the sequence, or -1 if not found.</returns>
public int IndexOf(T item, IEqualityComparer<T> comp = null)
{
if (comp == null)
comp = EqualityComparer<T>.Default;
return Shield.InTransaction(() => {
var curr = _head;
int i = 0;
while (curr.Value != null && !comp.Equals(curr.Value.Value, item))
{
i++;
curr = curr.Value.Next;
}
return curr.Value == null ? -1 : i;
});
}
/// <summary>
/// Get an enumerator for the sequence. Although it is just a read, it must be
/// done in a transaction since concurrent changes would make the result unstable.
/// However, if you just read the first item (e.g. by calling Any or First), that
/// will work out of transaction too.
/// </summary>
public IEnumerator<T> GetEnumerator()
{
var curr = _head.Value;
if (curr == null)
yield break;
yield return curr.Value;
Shield.AssertInTransaction();
curr = curr.Next;
while (curr != null)
{
yield return curr.Value;
curr = curr.Next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)this).GetEnumerator();
}
/// <summary>
/// Add the specified item to the end of the sequence. Same as <see cref="Append"/>,
/// so, it's commutable.
/// </summary>
public void Add(T item)
{
Append(item);
}
/// <summary>
/// Check if the sequence contains a given item.
/// </summary>
public bool Contains(T item)
{
return IndexOf(item) >= 0;
}
/// <summary>
/// Copy the sequence to an array.
/// </summary>
/// <param name="array">The array to copy to.</param>
/// <param name="arrayIndex">Index in the array where to begin the copy.</param>
public void CopyTo(T[] array, int arrayIndex)
{
Shield.InTransaction(() => {
foreach (var v in this)
array[arrayIndex++] = v;
});
}
/// <summary>
/// Insert an item at the specified index.
/// </summary>
public void Insert(int index, T item)
{
RefToIndex(index, plusOne: true).Modify((ref ItemKeeper r) => {
var newItem = new ItemKeeper(item, r, _owner);
if (r == null)
_tail.Value = newItem;
r = newItem;
});
}
}
}
| |
using System;
using System.IO;
using System.Reflection;
using Nohros.Logging;
using Nohros.Configuration;
namespace Nohros.Providers
{
/// <summary>
/// A class used to instantiate others factories using information defined
/// on a <see cref="IProviderNode"/> object.
/// </summary>
/// <remarks>
/// The <typeparam name="T"> is usually a interface or an abstract class that
/// the factory should implement or derive from.</typeparam>
/// <para>
/// The type that is instantiated should be defined in the
/// <see cref="IProviderNode"/> object and should have a constructor with no
/// parameters.
/// </para>
/// </remarks>
[Obsolete("This class has been deprecated. Plese use the RuntimeTypeFactory instead.")]
public sealed class ProviderFactory<T> where T : class
{
/// <summary>
/// Gets the <see cref="Type"/> of a provider, using the specified provider
/// node.
/// </summary>
/// <param name="node">A <see cref="IProviderNode"/> object that contains
/// information about the type <typeparamref name="T"/></param>
/// <returns>The type instance that represents the exact runtime type of
/// the specified provider or null if the type could not be loaded.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="node"/> is a
/// null reference.</exception>
/// <remarks>
/// If the location of the assemlby is specified on the configuration node
/// we will try load the assembly using this location and them get the type
/// from the loaded assembly.
/// </remarks>
public static Type GetProviderFactoryType(IProviderNode node) {
if (node == null)
throw new ArgumentNullException("node");
// Try to get the type from the loaded assemblies.
Type type = Type.GetType(node.Type);
// attempt to load .NET type of the provider. If the location of the
// assemlby is specified we need to load the assembly and try to get the
// type from the loaded assembly. The name of the assembly will be
// extracted from the provider type.
if (type == null) {
string assembly_name = node.Type;
int num = assembly_name.IndexOf(',');
if (num == -1) {
throw new ProviderException(
string.Format(
Resources.Resources.Provider_AssemblyNotSpecified, assembly_name));
}
assembly_name = assembly_name.Substring(num + 1).Trim();
int num2 = assembly_name.IndexOfAny(new char[] {' ', ','});
if (num2 != -1)
assembly_name = assembly_name.Substring(0, num2);
if (!assembly_name.EndsWith(".dll"))
assembly_name = assembly_name + ".dll";
string assembly_path =
Path.Combine(node.Location, assembly_name);
if (!File.Exists(assembly_path)) {
throw new ProviderException(
string.Format(
Resources.Resources.Provider_LoadAssembly, assembly_path));
}
try {
Assembly assembly = Assembly.LoadFrom(assembly_path);
type = assembly.GetType(node.Type.Substring(0, num));
} catch (Exception ex) {
throw new ProviderException(
string.Format(
Resources.Resources.Provider_LoadAssembly, assembly_path), ex);
}
}
return type;
}
/// <summary>
/// Creates a new instance of the <typeparamref name="T"/> class by using
/// the type that is defined on the configuration node.
/// </summary>
/// <param name="node">A <see cref="IProviderNode"/> object that contains
/// information about the type <typeparamref name="T"/></param>
/// <param name="args">An array of arguments that match in number, order,
/// and type the parameters of the constructor to invoke. If args is an
/// empty array or null, the constructor that takes no parameters(the
/// default constructor) is invoked.</param>
/// <returns>An instance of the <typeparamref name="T"/> class.
/// or null if a class of the type <typeparamref name="T"/> could not be
/// created.</returns>
/// <remarks>
/// A exception is never raised by this method. If a exception is raised
/// by the object constructor it will be catched and <c>null</c> will be
/// returned. If you need to know about the exception use the method
/// <see cref="CreateProviderFactory"/>.
/// </remarks>
/// <seealso cref="CreateProviderFactory"/>
/// <seealso cref="IProviderNode"/>
public static T CreateProviderFactoryNoException(IProviderNode node,
params object[] args) {
// A try/catch block is used here because this method should not throw
// any exception.
try {
return CreateProviderFactory(node, args);
} catch (ProviderException) {
// TODO: Add meaing to the exception.
MustLogger.ForCurrentProcess.Error("");
}
return null;
}
/// <summary>
/// Creates a new instance of the <typeparamref name="T"/> class by using
/// the type defined by the <paramref name="node"/> and the specified
/// arguments, falling back to the default constructor.
/// </summary>
/// <param name="node">
/// A <see cref="IProviderNode"/> object that contains information about
/// the type <typeparamref name="T"/>
/// </param>
/// <param name="args">
/// An array of arguments that match in number, order,
/// and type the parameters of the constructor to invoke. If args is an
/// empty array or null, the constructor that takes no parameters(the
/// default constructor) is invoked.
/// </param>
/// <returns>
/// An instance of the <typeparamref name="T"/> class.
/// </returns>
/// <remarks>
/// If a constructor that match in number, order and type the specified
/// array of arguments is not found, this method try to create an instance
/// of the type <typeparamref name="T"/> using the default constructor.
/// </remarks>
/// <seealso cref="CreateProviderFactory"/>
/// <seealso cref="IProviderNode"/>
public static T CreateProviderFactoryFallback(IProviderNode node,
params object[] args) {
return CreateProviderFactory(node, true, args);
}
/// <summary>
/// Creates a new instance of the <typeparamref name="T"/> class by using
/// the type that is defined on the configuration node.
/// </summary>
/// <param name="node">
/// A <see cref="IProviderNode"/> object that contains information about
/// the type <typeparamref name="T"/>.
/// </param>
/// <param name="args">
/// An array of arguments that match in number, order, and type the
/// parameters of the constructor to invoke. If args is an empty array or
/// null, the constructor that takes no parameters(the default constructor)
/// is invoked.
/// </param>
/// <returns>
/// An instance of the <typeparamref name="T"/> class.
/// </returns>
/// <exception cref="ProviderException">
/// A instance of the specified type could not be created.
/// </exception>
public static T CreateProviderFactory(IProviderNode node,
params object[] args) {
return CreateProviderFactory(node, false, args);
}
static T CreateProviderFactory(IProviderNode node, bool fallback,
params object[] args) {
Exception inner_exception = null;
// A try/catch block is used here because this method should throw only
// a ProviderException, any other exception throwed should be packed
// into a ProviderException.
try {
Type type = GetProviderFactoryType(node);
if (type != null) {
// create a new object instance using a public or non-public
// constructor.
const BindingFlags kFlags =
BindingFlags.CreateInstance | BindingFlags.Public |
BindingFlags.Instance | BindingFlags.NonPublic;
T new_obj = null;
// A try catch block is used here because we need to fallback, if
// desired, to the default constructor if the first CreateInstance
// fails because of a missing constructor.
try {
new_obj =
Activator.CreateInstance(type, kFlags, null, args, null) as T;
} catch (MissingMethodException) {
if (fallback) {
new_obj =
Activator.CreateInstance(type, kFlags, null, null, null) as T;
}
}
if (new_obj != null) {
return new_obj;
}
}
} catch (ProviderException) {
throw;
} catch (Exception ex) {
// minimizing code duplication.
inner_exception = ex;
}
// the provider could not be created and we need to pack the exception
// into a new ProviderException exception.
throw new ProviderException(
string.Format(Resources.Resources.TypeLoad_CreateInstance,
typeof (T)), inner_exception);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading;
namespace System.Diagnostics
{
public class TraceSource
{
private static readonly List<WeakReference> s_tracesources = new List<WeakReference>();
private static int s_LastCollectionCount;
private volatile SourceSwitch _internalSwitch;
private volatile TraceListenerCollection _listeners;
private readonly SourceLevels _switchLevel;
private readonly string _sourceName;
internal volatile bool _initCalled = false; // Whether we've called Initialize already.
private StringDictionary _attributes;
public TraceSource(string name)
: this(name, SourceLevels.Off)
{
}
public TraceSource(string name, SourceLevels defaultLevel)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException(SR.Format(SR.InvalidNullEmptyArgument, nameof(name)), nameof(name));
_sourceName = name;
_switchLevel = defaultLevel;
// Add a weakreference to this source and cleanup invalid references
lock (s_tracesources)
{
_pruneCachedTraceSources();
s_tracesources.Add(new WeakReference(this));
}
}
private static void _pruneCachedTraceSources()
{
lock (s_tracesources)
{
if (s_LastCollectionCount != GC.CollectionCount(2))
{
List<WeakReference> buffer = new List<WeakReference>(s_tracesources.Count);
for (int i = 0; i < s_tracesources.Count; i++)
{
TraceSource tracesource = ((TraceSource)s_tracesources[i].Target);
if (tracesource != null)
{
buffer.Add(s_tracesources[i]);
}
}
if (buffer.Count < s_tracesources.Count)
{
s_tracesources.Clear();
s_tracesources.AddRange(buffer);
s_tracesources.TrimExcess();
}
s_LastCollectionCount = GC.CollectionCount(2);
}
}
}
private void Initialize()
{
if (!_initCalled)
{
lock (this)
{
if (_initCalled)
return;
NoConfigInit();
_initCalled = true;
}
}
}
private void NoConfigInit()
{
_internalSwitch = new SourceSwitch(_sourceName, _switchLevel.ToString());
_listeners = new TraceListenerCollection();
_listeners.Add(new DefaultTraceListener());
}
public void Close()
{
// No need to call Initialize()
if (_listeners != null)
{
// Use global lock
lock (TraceInternal.critSec)
{
foreach (TraceListener listener in _listeners)
{
listener.Close();
}
}
}
}
public void Flush()
{
// No need to call Initialize()
if (_listeners != null)
{
if (TraceInternal.UseGlobalLock)
{
lock (TraceInternal.critSec)
{
foreach (TraceListener listener in _listeners)
{
listener.Flush();
}
}
}
else
{
foreach (TraceListener listener in _listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.Flush();
}
}
else
{
listener.Flush();
}
}
}
}
}
protected internal virtual string[] GetSupportedAttributes() => null;
internal static void RefreshAll()
{
lock (s_tracesources)
{
_pruneCachedTraceSources();
for (int i = 0; i < s_tracesources.Count; i++)
{
TraceSource tracesource = ((TraceSource)s_tracesources[i].Target);
if (tracesource != null)
{
tracesource.Refresh();
}
}
}
}
internal void Refresh()
{
if (!_initCalled)
{
Initialize();
return;
}
}
[Conditional("TRACE")]
public void TraceEvent(TraceEventType eventType, int id)
{
Initialize();
if (_internalSwitch.ShouldTrace(eventType) && _listeners != null)
{
TraceEventCache manager = new TraceEventCache();
if (TraceInternal.UseGlobalLock)
{
// we lock on the same object that Trace does because we're writing to the same Listeners.
lock (TraceInternal.critSec)
{
for (int i = 0; i < _listeners.Count; i++)
{
TraceListener listener = _listeners[i];
listener.TraceEvent(manager, Name, eventType, id);
if (Trace.AutoFlush) listener.Flush();
}
}
}
else
{
for (int i = 0; i < _listeners.Count; i++)
{
TraceListener listener = _listeners[i];
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.TraceEvent(manager, Name, eventType, id);
if (Trace.AutoFlush) listener.Flush();
}
}
else
{
listener.TraceEvent(manager, Name, eventType, id);
if (Trace.AutoFlush) listener.Flush();
}
}
}
}
}
[Conditional("TRACE")]
public void TraceEvent(TraceEventType eventType, int id, string message)
{
Initialize();
if (_internalSwitch.ShouldTrace(eventType) && _listeners != null)
{
TraceEventCache manager = new TraceEventCache();
if (TraceInternal.UseGlobalLock)
{
// we lock on the same object that Trace does because we're writing to the same Listeners.
lock (TraceInternal.critSec)
{
for (int i = 0; i < _listeners.Count; i++)
{
TraceListener listener = _listeners[i];
listener.TraceEvent(manager, Name, eventType, id, message);
if (Trace.AutoFlush) listener.Flush();
}
}
}
else
{
for (int i = 0; i < _listeners.Count; i++)
{
TraceListener listener = _listeners[i];
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.TraceEvent(manager, Name, eventType, id, message);
if (Trace.AutoFlush) listener.Flush();
}
}
else
{
listener.TraceEvent(manager, Name, eventType, id, message);
if (Trace.AutoFlush) listener.Flush();
}
}
}
}
}
[Conditional("TRACE")]
public void TraceEvent(TraceEventType eventType, int id, string format, params object[] args)
{
Initialize();
if (_internalSwitch.ShouldTrace(eventType) && _listeners != null)
{
TraceEventCache manager = new TraceEventCache();
if (TraceInternal.UseGlobalLock)
{
// we lock on the same object that Trace does because we're writing to the same Listeners.
lock (TraceInternal.critSec)
{
for (int i = 0; i < _listeners.Count; i++)
{
TraceListener listener = _listeners[i];
listener.TraceEvent(manager, Name, eventType, id, format, args);
if (Trace.AutoFlush) listener.Flush();
}
}
}
else
{
for (int i = 0; i < _listeners.Count; i++)
{
TraceListener listener = _listeners[i];
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.TraceEvent(manager, Name, eventType, id, format, args);
if (Trace.AutoFlush) listener.Flush();
}
}
else
{
listener.TraceEvent(manager, Name, eventType, id, format, args);
if (Trace.AutoFlush) listener.Flush();
}
}
}
}
}
[Conditional("TRACE")]
public void TraceData(TraceEventType eventType, int id, object data)
{
Initialize();
if (_internalSwitch.ShouldTrace(eventType) && _listeners != null)
{
TraceEventCache manager = new TraceEventCache();
if (TraceInternal.UseGlobalLock)
{
// we lock on the same object that Trace does because we're writing to the same Listeners.
lock (TraceInternal.critSec)
{
for (int i = 0; i < _listeners.Count; i++)
{
TraceListener listener = _listeners[i];
listener.TraceData(manager, Name, eventType, id, data);
if (Trace.AutoFlush) listener.Flush();
}
}
}
else
{
for (int i = 0; i < _listeners.Count; i++)
{
TraceListener listener = _listeners[i];
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.TraceData(manager, Name, eventType, id, data);
if (Trace.AutoFlush) listener.Flush();
}
}
else
{
listener.TraceData(manager, Name, eventType, id, data);
if (Trace.AutoFlush) listener.Flush();
}
}
}
}
}
[Conditional("TRACE")]
public void TraceData(TraceEventType eventType, int id, params object[] data)
{
Initialize();
if (_internalSwitch.ShouldTrace(eventType) && _listeners != null)
{
TraceEventCache manager = new TraceEventCache();
if (TraceInternal.UseGlobalLock)
{
// we lock on the same object that Trace does because we're writing to the same Listeners.
lock (TraceInternal.critSec)
{
for (int i = 0; i < _listeners.Count; i++)
{
TraceListener listener = _listeners[i];
listener.TraceData(manager, Name, eventType, id, data);
if (Trace.AutoFlush) listener.Flush();
}
}
}
else
{
for (int i = 0; i < _listeners.Count; i++)
{
TraceListener listener = _listeners[i];
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.TraceData(manager, Name, eventType, id, data);
if (Trace.AutoFlush) listener.Flush();
}
}
else
{
listener.TraceData(manager, Name, eventType, id, data);
if (Trace.AutoFlush) listener.Flush();
}
}
}
}
}
[Conditional("TRACE")]
public void TraceInformation(string message)
{ // eventType= TraceEventType.Info, id=0
// No need to call Initialize()
TraceEvent(TraceEventType.Information, 0, message, null);
}
[Conditional("TRACE")]
public void TraceInformation(string format, params object[] args)
{
// No need to call Initialize()
TraceEvent(TraceEventType.Information, 0, format, args);
}
[Conditional("TRACE")]
public void TraceTransfer(int id, string message, Guid relatedActivityId)
{
// Ensure that config is loaded
Initialize();
TraceEventCache manager = new TraceEventCache();
if (_internalSwitch.ShouldTrace(TraceEventType.Transfer) && _listeners != null)
{
if (TraceInternal.UseGlobalLock)
{
// we lock on the same object that Trace does because we're writing to the same Listeners.
lock (TraceInternal.critSec)
{
for (int i = 0; i < _listeners.Count; i++)
{
TraceListener listener = _listeners[i];
listener.TraceTransfer(manager, Name, id, message, relatedActivityId);
if (Trace.AutoFlush)
{
listener.Flush();
}
}
}
}
else
{
for (int i = 0; i < _listeners.Count; i++)
{
TraceListener listener = _listeners[i];
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.TraceTransfer(manager, Name, id, message, relatedActivityId);
if (Trace.AutoFlush)
{
listener.Flush();
}
}
}
else
{
listener.TraceTransfer(manager, Name, id, message, relatedActivityId);
if (Trace.AutoFlush)
{
listener.Flush();
}
}
}
}
}
}
public StringDictionary Attributes
{
get
{
// Ensure that config is loaded
Initialize();
if (_attributes == null)
_attributes = new StringDictionary();
return _attributes;
}
}
public string Name
{
get
{
return _sourceName;
}
}
public TraceListenerCollection Listeners
{
get
{
Initialize();
return _listeners;
}
}
public SourceSwitch Switch
{
// No need for security demand here. SourceSwitch.set_Level is protected already.
get
{
Initialize();
return _internalSwitch;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(Switch));
Initialize();
_internalSwitch = value;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright company="CoApp Project">
// Copyright (c) 2010-2013 Garrett Serack and CoApp Contributors.
// Contributors can be discovered using the 'git log' command.
// All rights reserved.
// </copyright>
// <license>
// The software is licensed under the Apache 2.0 License (the "License")
// You may not use the software except in compliance with the License.
// </license>
//-----------------------------------------------------------------------
namespace ClrPlus.Powershell.Azure.Provider {
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation.Provider;
using System.Threading;
using ClrPlus.Core.Exceptions;
using ClrPlus.Core.Extensions;
using ClrPlus.Core.Utility;
using Microsoft.WindowsAzure.Storage.Blob;
using Powershell.Provider.Base;
using Path = Powershell.Provider.Utility.Path;
public class AzureLocation : Location {
public static AzureLocation InvalidLocation = new AzureLocation(null, new Path(), null) {
_invalidLocation = true
};
public static AzureLocation UnknownLocation = new AzureLocation(null, new Path(), null) {
_invalidLocation = true
};
private readonly AsyncLazy<IListBlobItem> _cloudItem;
private readonly AzureDriveInfo _driveInfo;
private string _absolutePath;
private Stream _blobStream;
private CloudBlobContainer _cloudContainer;
private bool _invalidLocation;
public AzureLocation(AzureDriveInfo driveInfo, Path path, IListBlobItem cloudItem) {
_driveInfo = driveInfo;
Path = path;
Path.Validate();
if (cloudItem != null) {
_cloudItem = new AsyncLazy<IListBlobItem>(() => {
if (cloudItem is CloudBlockBlob) {
(cloudItem as CloudBlockBlob).FetchAttributes();
}
return cloudItem;
});
} else {
if (IsRootNamespace || IsAccount || IsContainer) {
// azure namespace mount.
_cloudItem = new AsyncLazy<IListBlobItem>(() => null);
return;
}
_cloudItem = new AsyncLazy<IListBlobItem>(() => {
if (CloudContainer == null) {
return null;
}
// not sure if it's a file or a directory.
if (path.EndsWithSlash) {
// can't be a file!
CloudContainer.GetDirectoryReference(Path.SubPath);
}
// check to see if it's a file.
ICloudBlob blobRef = null;
try {
blobRef = CloudContainer.GetBlobReferenceFromServer(Path.SubPath);
if (blobRef != null && blobRef.BlobType == BlobType.BlockBlob) {
blobRef.FetchAttributes();
return blobRef;
}
} catch {
}
// well, we know it's not a file, container, or account.
// it could be a directory (but the only way to really know that is to see if there is any files that have this as a parent path)
var dirRef = CloudContainer.GetDirectoryReference(Path.SubPath);
if (dirRef.ListBlobs().Any()) {
return dirRef;
}
blobRef = CloudContainer.GetBlockBlobReference(Path.SubPath);
if (blobRef != null && blobRef.BlobType == BlobType.BlockBlob) {
return blobRef;
}
// it really didn't match anything, we'll return the reference to the blob in case we want to write to it.
return blobRef;
});
_cloudItem.InitializeAsync();
}
}
protected bool IsRootNamespace {
get {
return !_invalidLocation && _driveInfo == null;
}
}
protected bool IsAccount {
get {
return !_invalidLocation && !IsRootNamespace && Path.Container.IsNullOrEmpty() && Path.SubPath.IsNullOrEmpty();
}
}
protected CloudBlockBlob FileBlob {
get {
return _cloudItem.Value as CloudBlockBlob;
}
}
protected CloudBlobDirectory DirectoryBlob {
get {
return _cloudItem.Value as CloudBlobDirectory;
}
}
protected CloudBlobContainer CloudContainer {
get {
if (!_invalidLocation && _cloudContainer == null) {
/*
if (_driveInfo.CloudFileSystem == null || Path.Container.IndexOfAny(Wildcards) > -1 || !_driveInfo.CloudFileSystem.ContainerExists(Path.Container)) {
return null;
}
_cloudContainer = _driveInfo.CloudFileSystem[Path.Container];
* */
if (_driveInfo.CloudFileSystem != null && Path.Container.IndexOfAny(Wildcards) == -1) {
_cloudContainer = _driveInfo.GetContainer(Path.Container);
}
}
return _cloudContainer;
}
}
public bool IsContainer {
get {
if (_invalidLocation || string.IsNullOrEmpty(Path.Container) || !string.IsNullOrEmpty(Path.SubPath)) {
return false;
}
return CloudContainer != null;
}
}
public bool IsDirectory {
get {
return !_invalidLocation && !string.IsNullOrEmpty(Path.SubPath) && _cloudItem != null && _cloudItem.Value is CloudBlobDirectory;
}
}
public string MD5 {
get {
if (FileBlob == null) {
return string.Empty;
}
var result = FileBlob.Properties.ContentMD5;
if (string.IsNullOrEmpty(result)) {
if (FileBlob.Metadata.ContainsKey("MD5")) {
return FileBlob.Metadata["MD5"];
}
return string.Empty;
}
return result;
}
}
public string MimeType {
get {
return FileBlob != null ? FileBlob.Properties.ContentType : string.Empty;
}
}
public override string Name {
get {
return _invalidLocation ? "<invalid>"
: IsRootNamespace ? AzureDriveInfo.ProviderScheme + ":"
: IsAccount ? _driveInfo.HostAndPort
: IsContainer ? Path.Container
: Path.Name;
}
}
public override string AbsolutePath {
get {
return _absolutePath ?? (_absolutePath = _invalidLocation ? "???"
: IsRootNamespace ? @"{0}:\".format(AzureDriveInfo.ProviderScheme)
: IsAccount ? @"{0}:\{1}\".format(AzureDriveInfo.ProviderScheme, Path.HostAndPort)
: IsContainer ? @"{0}:\{1}\{2}".format(AzureDriveInfo.ProviderScheme, Path.HostAndPort, Path.Container)
: IsDirectory ? @"{0}:\{1}\{2}\{3}\".format(AzureDriveInfo.ProviderScheme, Path.HostAndPort, Path.Container, Path.SubPath)
: @"{0}:\{1}\{2}\{3}".format(AzureDriveInfo.ProviderScheme, Path.HostAndPort, Path.Container, Path.SubPath));
}
}
public override string Url {
get {
return (_invalidLocation || IsRootNamespace || IsAccount) ? string.Empty : IsContainer ? CloudContainer.Uri.AbsoluteUri : IsDirectory || IsFile ? _cloudItem.Value.Uri.AbsoluteUri : string.Empty;
}
}
public override string Type {
get {
return _invalidLocation ? "<invalid>" : IsRootNamespace ? "<root>" : IsAccount ? "<account>" : IsContainer ? "<container>" : (IsDirectory ? "<dir>" : (IsFile ? MimeType : "<?>"));
}
}
public override long Length {
get {
return FileBlob != null ? FileBlob.Properties.Length : -1;
}
}
public override DateTime TimeStamp {
get {
if (FileBlob != null) {
return FileBlob.Properties.LastModified.Value.UtcDateTime.ToLocalTime();
}
return DateTime.MinValue;
}
}
public override bool IsItemContainer {
get {
return IsRootNamespace || IsAccount || IsContainer || IsDirectory;
}
}
public override bool IsFileContainer {
get {
return IsContainer || IsDirectory;
}
}
public override bool IsFile {
get {
return !_invalidLocation && FileBlob != null && FileBlob.Properties.Length > 0;
}
}
public override bool Exists {
get {
return !_invalidLocation && IsRootNamespace || IsAccount || IsContainer || IsDirectory || IsFile;
}
}
public override void Delete(bool recurse) {
if (IsFile) {
var result = FileBlob.DeleteIfExists();
if (!result) {
throw new UnauthorizedAccessException("{0} could not be found or you do not have permissions to delete it.".format(FileBlob.Uri));
}
return;
}
if (IsDirectory && recurse) {
foreach (var d in GetDirectories(true)) {
d.Delete(true);
}
foreach (var d in GetFiles(false)) {
d.Delete(false);
}
}
if (IsContainer) {
if (recurse || (!GetDirectories(false).Any() && !GetFiles(false).Any())) {
var result = CloudContainer.DeleteIfExists();
if (!result) {
throw new UnauthorizedAccessException("{0} could not be found or you do not have permissions to delete it.".format(FileBlob.Uri));
}
}
}
}
public override IEnumerable<ILocation> GetDirectories(bool recurse) {
if (_invalidLocation) {
return Enumerable.Empty<AzureLocation>();
}
if (recurse) {
var dirs = GetDirectories(false);
return dirs.Union(dirs.SelectMany(each => each.GetDirectories(true)));
}
if (IsRootNamespace) {
// list accounts we know
return AzureProviderInfo.NamespaceProvider.Drives
.Select(each => each as AzureDriveInfo)
.Where(each => !string.IsNullOrEmpty(each.HostAndPort))
.Distinct(new ClrPlus.Core.Extensions.EqualityComparer<AzureDriveInfo>((a, b) => a.HostAndPort == b.HostAndPort, a => a.HostAndPort.GetHashCode()))
.Select(each => new AzureLocation(each, new Path {
HostAndPort = each.HostAndPort,
Container = string.Empty,
SubPath = string.Empty,
}, null));
}
if (IsAccount) {
return _driveInfo.CloudFileSystem.ListContainers().Select(each => new AzureLocation(_driveInfo, new Path {
HostAndPort = Path.HostAndPort,
Container = each.Name,
}, null));
}
if (IsContainer) {
return ListSubdirectories(CloudContainer).Select(each => new AzureLocation(_driveInfo, new Path {
HostAndPort = Path.HostAndPort,
Container = Path.Container,
SubPath = Path.ParseUrl(each.Uri).Name,
}, each));
}
if (IsDirectory) {
var cbd = (_cloudItem.Value as CloudBlobDirectory);
return cbd == null
? Enumerable.Empty<ILocation>()
: ListSubdirectories(cbd).Select(each => {
return new AzureLocation(_driveInfo, new Path {
HostAndPort = Path.HostAndPort,
Container = Path.Container,
SubPath = Path.SubPath + '\\' + Path.ParseUrl(each.Uri).Name,
}, each);
});
}
return Enumerable.Empty<AzureLocation>();
}
public static IEnumerable<CloudBlobDirectory> ListSubdirectories(CloudBlobContainer cloudBlobContainer) {
var l = cloudBlobContainer.Uri.AbsolutePath.Length;
return (from blob in cloudBlobContainer.ListBlobs().Select(each => each.Uri.AbsolutePath.Substring(l + 1))
let i = blob.IndexOf('/')
where i > -1
select blob.Substring(0, i)).Distinct().Select(cloudBlobContainer.GetDirectoryReference);
}
public static IEnumerable<CloudBlobDirectory> ListSubdirectories(CloudBlobDirectory cloudBlobDirectory) {
var p = cloudBlobDirectory.Uri.AbsolutePath;
var l = p.EndsWith("/") ? cloudBlobDirectory.Uri.AbsolutePath.Length : cloudBlobDirectory.Uri.AbsolutePath.Length + 1;
return (from blob in cloudBlobDirectory.ListBlobs().Select(each => each.Uri.AbsolutePath.Substring(l))
let i = blob.IndexOf('/')
where i > -1
select blob.Substring(0, i)).Distinct().Select(cloudBlobDirectory.GetSubdirectoryReference);
}
public override IEnumerable<ILocation> GetFiles(bool recurse) {
if (recurse) {
return GetFiles(false).Union(GetDirectories(false).SelectMany(each => each.GetFiles(true)));
}
if (IsContainer) {
return CloudContainer.ListBlobs().Where(each => each is ICloudBlob && !(each as ICloudBlob).Name.EndsWith("/")).Select(each => new AzureLocation(_driveInfo, new Path {
HostAndPort = Path.HostAndPort,
Container = Path.Container,
SubPath = Path.ParseUrl(each.Uri).Name,
}, each));
}
if (IsDirectory) {
var cbd = (_cloudItem.Value as CloudBlobDirectory);
return cbd == null ? Enumerable.Empty<ILocation>() : cbd.ListBlobs().Where(each => each is ICloudBlob && !(each as ICloudBlob).Name.EndsWith("/")).Select(each => new AzureLocation(_driveInfo, new Path {
HostAndPort = Path.HostAndPort,
Container = Path.Container,
SubPath = Path.SubPath + '\\' + Path.ParseUrl(each.Uri).Name,
}, each));
}
return Enumerable.Empty<AzureLocation>();
}
public void Dispose() {
Close();
}
public void Close() {
if (_blobStream != null) {
_blobStream.Close();
_blobStream.Dispose();
_blobStream = null;
}
}
public override IEnumerable<ILocation> Copy(ILocation newLocation, bool recurse) {
throw new NotImplementedException();
}
public override Stream Open(FileMode mode) {
if (_blobStream != null) {
return _blobStream;
}
switch (mode) {
case FileMode.Create:
case FileMode.CreateNew:
case FileMode.Truncate:
var b = FileBlob;
if (b == null) {
//CloudContainer.GetBlockBlobReference();
}
return _blobStream = FileBlob.OpenWrite();
case FileMode.Open:
if (!Exists || !IsFile) {
throw new ClrPlusException("Path not found '{0}'".format(AbsolutePath));
}
return _blobStream = FileBlob.OpenRead();
}
throw new ClrPlusException("Unsupported File Mode.");
}
public override ILocation GetChildLocation(string relativePath) {
return new AzureLocation(_driveInfo, Path.ParseWithContainer(AbsolutePath + "\\" + relativePath), null);
}
public override IContentReader GetContentReader() {
return new ContentReader(Open(FileMode.Open), Length);
}
public override IContentWriter GetContentWriter() {
return new UniversalContentWriter(Open(FileMode.Create));
}
public override void ClearContent() {
}
public override ILocation NewItem(string type, object newItemValue) {
if ((type ?? "d").ToLower().FirstOrDefault() == 'f') {
// new file
} else {
// new directory
}
return null;
}
public override ILocation Rename(string newName) {
if (newName.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) > -1) {
throw new ClrPlusException("Invalid characters in new pathname");
}
if (IsContainer) {
var newContainer = _driveInfo.CloudFileSystem.GetContainerReference(newName);
if (newContainer.Exists()) {
throw new ClrPlusException("Target location exists.");
}
newContainer.CreateIfNotExists();
var results = newContainer.ListBlobs().OfType<CloudBlockBlob>().Select(blob => {
var newBlob = newContainer.GetBlockBlobReference(Name);
newBlob.StartCopyFromBlob(blob);
return newBlob;
}).ToList();
while (results.Count > 0) {
for (var i = results.Count; i <= 0; i--) {
var blob = results[i];
switch (blob.CopyState.Status) {
case CopyStatus.Success:
results.RemoveAt(i);
continue;
case CopyStatus.Aborted:
case CopyStatus.Invalid:
case CopyStatus.Failed:
// something happened. bail on everything.
results.RemoveAt(i);
foreach (var each in results) {
if (each.CopyState.Status == CopyStatus.Pending) {
each.AbortCopy(each.CopyState.CopyId);
}
}
newContainer.DeleteIfExists();
throw new ClrPlusException("Container rename failed");
}
}
// breathe.
Thread.Sleep(20);
}
// delete the old container.
_cloudContainer.DeleteIfExists();
} else if (IsDirectory) {
} else if (IsFile) {
}
throw new NotImplementedException();
}
public override ILocation Move(ILocation newLocation) {
throw new NotImplementedException();
}
}
}
| |
// 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.Diagnostics;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using IServiceProvider = System.IServiceProvider;
using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants;
namespace Microsoft.VisualStudioTools.Project
{
/// <summary>
/// Defines an abstract class implementing IVsUpdateSolutionEvents interfaces.
/// </summary>
internal class UpdateSolutionEventsListener : IVsUpdateSolutionEvents3, IVsUpdateSolutionEvents2, IDisposable
{
#region fields
/// <summary>
/// The cookie associated to the the events based IVsUpdateSolutionEvents2.
/// </summary>
private uint solutionEvents2Cookie;
/// <summary>
/// The cookie associated to the theIVsUpdateSolutionEvents3 events.
/// </summary>
private uint solutionEvents3Cookie;
/// <summary>
/// The IVsSolutionBuildManager2 object controlling the update solution events.
/// </summary>
private IVsSolutionBuildManager2 solutionBuildManager;
/// <summary>
/// The associated service provider.
/// </summary>
private IServiceProvider serviceProvider;
/// <summary>
/// Flag determining if the object has been disposed.
/// </summary>
private bool isDisposed;
/// <summary>
/// Defines an object that will be a mutex for this object for synchronizing thread calls.
/// </summary>
private static volatile object Mutex = new object();
#endregion
#region ctors
/// <summary>
/// Overloaded constructor.
/// </summary>
/// <param name="serviceProvider">A service provider.</param>
public UpdateSolutionEventsListener(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
this.serviceProvider = serviceProvider;
this.solutionBuildManager = this.serviceProvider.GetService(typeof(SVsSolutionBuildManager)) as IVsSolutionBuildManager2;
if (this.solutionBuildManager == null)
{
throw new InvalidOperationException();
}
ErrorHandler.ThrowOnFailure(this.solutionBuildManager.AdviseUpdateSolutionEvents(this, out this.solutionEvents2Cookie));
Debug.Assert(this.solutionBuildManager is IVsSolutionBuildManager3, "The solution build manager object implementing IVsSolutionBuildManager2 does not implement IVsSolutionBuildManager3");
ErrorHandler.ThrowOnFailure(this.SolutionBuildManager3.AdviseUpdateSolutionEvents3(this, out this.solutionEvents3Cookie));
}
#endregion
#region properties
/// <summary>
/// The associated service provider.
/// </summary>
protected IServiceProvider ServiceProvider => this.serviceProvider;
/// <summary>
/// The solution build manager object controlling the solution events.
/// </summary>
protected IVsSolutionBuildManager2 SolutionBuildManager2 => this.solutionBuildManager;
/// <summary>
/// The solution build manager object controlling the solution events.
/// </summary>
protected IVsSolutionBuildManager3 SolutionBuildManager3 => (IVsSolutionBuildManager3)this.solutionBuildManager;
#endregion
#region IVsUpdateSolutionEvents3 Members
/// <summary>
/// Fired after the active solution config is changed (pOldActiveSlnCfg can be NULL).
/// </summary>
/// <param name="oldActiveSlnCfg">Old configuration.</param>
/// <param name="newActiveSlnCfg">New configuration.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int OnAfterActiveSolutionCfgChange(IVsCfg oldActiveSlnCfg, IVsCfg newActiveSlnCfg)
{
var handlers = AfterActiveSolutionConfigurationChange;
if (handlers != null)
{
handlers(this, EventArgs.Empty);
}
return VSConstants.S_OK;
}
public event EventHandler AfterActiveSolutionConfigurationChange;
/// <summary>
/// Fired before the active solution config is changed (pOldActiveSlnCfg can be NULL
/// </summary>
/// <param name="oldActiveSlnCfg">Old configuration.</param>
/// <param name="newActiveSlnCfg">New configuration.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int OnBeforeActiveSolutionCfgChange(IVsCfg oldActiveSlnCfg, IVsCfg newActiveSlnCfg)
{
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsUpdateSolutionEvents2 Members
/// <summary>
/// Called when the active project configuration for a project in the solution has changed.
/// </summary>
/// <param name="hierarchy">The project whose configuration has changed.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int OnActiveProjectCfgChange(IVsHierarchy hierarchy)
{
return VSConstants.E_NOTIMPL;
}
/// <summary>
/// Called right before a project configuration begins to build.
/// </summary>
/// <param name="hierarchy">The project that is to be build.</param>
/// <param name="configProject">A configuration project object.</param>
/// <param name="configSolution">A configuration solution object.</param>
/// <param name="action">The action taken.</param>
/// <param name="cancel">A flag indicating cancel.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
/// <remarks>The values for the action are defined in the enum _SLNUPDACTION env\msenv\core\slnupd2.h</remarks>
public int UpdateProjectCfg_Begin(IVsHierarchy hierarchy, IVsCfg configProject, IVsCfg configSolution, uint action, ref int cancel)
{
return VSConstants.E_NOTIMPL;
}
/// <summary>
/// Called right after a project configuration is finished building.
/// </summary>
/// <param name="hierarchy">The project that has finished building.</param>
/// <param name="configProject">A configuration project object.</param>
/// <param name="configSolution">A configuration solution object.</param>
/// <param name="action">The action taken.</param>
/// <param name="success">Flag indicating success.</param>
/// <param name="cancel">Flag indicating cancel.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
/// <remarks>The values for the action are defined in the enum _SLNUPDACTION env\msenv\core\slnupd2.h</remarks>
public virtual int UpdateProjectCfg_Done(IVsHierarchy hierarchy, IVsCfg configProject, IVsCfg configSolution, uint action, int success, int cancel)
{
return VSConstants.E_NOTIMPL;
}
/// <summary>
/// Called before any build actions have begun. This is the last chance to cancel the build before any building begins.
/// </summary>
/// <param name="cancelUpdate">Flag indicating cancel update.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int UpdateSolution_Begin(ref int cancelUpdate)
{
return VSConstants.E_NOTIMPL;
}
/// <summary>
/// Called when a build is being cancelled.
/// </summary>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int UpdateSolution_Cancel()
{
return VSConstants.E_NOTIMPL;
}
/// <summary>
/// Called when a build is completed.
/// </summary>
/// <param name="succeeded">true if no update actions failed.</param>
/// <param name="modified">true if any update action succeeded.</param>
/// <param name="cancelCommand">true if update actions were canceled.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int UpdateSolution_Done(int fSucceeded, int fModified, int fCancelCommand)
{
return VSConstants.E_NOTIMPL;
}
/// <summary>
/// Called before the first project configuration is about to be built.
/// </summary>
/// <param name="cancelUpdate">A flag indicating cancel update.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int UpdateSolution_StartUpdate(ref int cancelUpdate)
{
return VSConstants.E_NOTIMPL;
}
#endregion
#region IDisposable Members
/// <summary>
/// The IDispose interface Dispose method for disposing the object determinastically.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region methods
/// <summary>
/// The method that does the cleanup.
/// </summary>
/// <param name="disposing">true if called from IDispose.Dispose; false if called from Finalizer.</param>
protected virtual void Dispose(bool disposing)
{
// Everybody can go here.
if (!this.isDisposed)
{
// Synchronize calls to the Dispose simultaniously.
lock (Mutex)
{
if (this.solutionEvents2Cookie != (uint)ShellConstants.VSCOOKIE_NIL)
{
ErrorHandler.ThrowOnFailure(this.solutionBuildManager.UnadviseUpdateSolutionEvents(this.solutionEvents2Cookie));
this.solutionEvents2Cookie = (uint)ShellConstants.VSCOOKIE_NIL;
}
if (this.solutionEvents3Cookie != (uint)ShellConstants.VSCOOKIE_NIL)
{
ErrorHandler.ThrowOnFailure(this.SolutionBuildManager3.UnadviseUpdateSolutionEvents3(this.solutionEvents3Cookie));
this.solutionEvents3Cookie = (uint)ShellConstants.VSCOOKIE_NIL;
}
this.isDisposed = true;
}
}
}
#endregion
}
}
| |
// 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 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for DeploymentsOperations.
/// </summary>
public static partial class DeploymentsOperationsExtensions
{
/// <summary>
/// Delete deployment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment to be deleted.
/// </param>
public static void Delete(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IDeploymentsOperations)s).DeleteAsync(resourceGroupName, deploymentName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete deployment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task DeleteAsync(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, deploymentName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Checks whether deployment exists.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to check. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
public static bool CheckExistence(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDeploymentsOperations)s).CheckExistenceAsync(resourceGroupName, deploymentName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Checks whether deployment exists.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to check. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<bool> CheckExistenceAsync(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.CheckExistenceWithHttpMessagesAsync(resourceGroupName, deploymentName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create a named template deployment using a template.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Additional parameters supplied to the operation.
/// </param>
public static DeploymentExtended CreateOrUpdate(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, Deployment parameters)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDeploymentsOperations)s).CreateOrUpdateAsync(resourceGroupName, deploymentName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a named template deployment using a template.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Additional parameters supplied to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<DeploymentExtended> CreateOrUpdateAsync(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, Deployment parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, deploymentName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get a deployment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
public static DeploymentExtended Get(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDeploymentsOperations)s).GetAsync(resourceGroupName, deploymentName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get a deployment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<DeploymentExtended> GetAsync(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, deploymentName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Cancel a currently running template deployment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
public static void Cancel(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IDeploymentsOperations)s).CancelAsync(resourceGroupName, deploymentName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Cancel a currently running template deployment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task CancelAsync(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.CancelWithHttpMessagesAsync(resourceGroupName, deploymentName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Validate a deployment template.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Deployment to validate.
/// </param>
public static DeploymentValidateResult Validate(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, Deployment parameters)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDeploymentsOperations)s).ValidateAsync(resourceGroupName, deploymentName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Validate a deployment template.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Deployment to validate.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<DeploymentValidateResult> ValidateAsync(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, Deployment parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ValidateWithHttpMessagesAsync(resourceGroupName, deploymentName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Exports a deployment template.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
public static DeploymentExportResult ExportTemplate(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDeploymentsOperations)s).ExportTemplateAsync(resourceGroupName, deploymentName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Exports a deployment template.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<DeploymentExportResult> ExportTemplateAsync(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ExportTemplateWithHttpMessagesAsync(resourceGroupName, deploymentName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get a list of deployments.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to filter by. The name is case insensitive.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<DeploymentExtended> List(this IDeploymentsOperations operations, string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery<DeploymentExtendedFilter> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<DeploymentExtendedFilter>))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDeploymentsOperations)s).ListAsync(resourceGroupName, odataQuery), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get a list of deployments.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to filter by. The name is case insensitive.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<DeploymentExtended>> ListAsync(this IDeploymentsOperations operations, string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery<DeploymentExtendedFilter> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<DeploymentExtendedFilter>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete deployment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment to be deleted.
/// </param>
public static void BeginDelete(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IDeploymentsOperations)s).BeginDeleteAsync(resourceGroupName, deploymentName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete deployment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task BeginDeleteAsync(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, deploymentName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Create a named template deployment using a template.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Additional parameters supplied to the operation.
/// </param>
public static DeploymentExtended BeginCreateOrUpdate(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, Deployment parameters)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDeploymentsOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, deploymentName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a named template deployment using a template.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Additional parameters supplied to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<DeploymentExtended> BeginCreateOrUpdateAsync(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, Deployment parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, deploymentName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get a list of deployments.
/// </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 Microsoft.Rest.Azure.IPage<DeploymentExtended> ListNext(this IDeploymentsOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDeploymentsOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get a list of deployments.
/// </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<Microsoft.Rest.Azure.IPage<DeploymentExtended>> ListNextAsync(this IDeploymentsOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Security;
namespace Alphaleonis.Win32.Filesystem
{
public static partial class Directory
{
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, Path.WildcardStarMatchAll, null, null, null, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, DirectoryEnumerationOptions options)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, Path.WildcardStarMatchAll, null, options, null, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, Path.WildcardStarMatchAll, null, options, null, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, string searchPattern)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, searchPattern, null, null, null, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, string searchPattern, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, searchPattern, null, null, null, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path using <see cref="DirectoryEnumerationOptions"/>.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, string searchPattern, DirectoryEnumerationOptions options)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, searchPattern, null, options, null, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path using <see cref="DirectoryEnumerationOptions"/>.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, searchPattern, null, options, null, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, DirectoryEnumerationFilters filters)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, Path.WildcardStarMatchAll, null, null, filters, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, DirectoryEnumerationFilters filters, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, Path.WildcardStarMatchAll, null, null, filters, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, Path.WildcardStarMatchAll, null, options, filters, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, Path.WildcardStarMatchAll, null, options, filters, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
[Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, string searchPattern, DirectoryEnumerationFilters filters)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, searchPattern, null, null, filters, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
[Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, string searchPattern, DirectoryEnumerationFilters filters, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, searchPattern, null, null, filters, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
[Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, searchPattern, null, options, filters, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
[Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(null, null, path, searchPattern, null, options, filters, pathFormat);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareEqualInt16()
{
var test = new SimpleBinaryOpTest__CompareEqualInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareEqualInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int16> _fld1;
public Vector256<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqualInt16 testClass)
{
var result = Avx2.CompareEqual(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareEqualInt16 testClass)
{
fixed (Vector256<Int16>* pFld1 = &_fld1)
fixed (Vector256<Int16>* pFld2 = &_fld2)
{
var result = Avx2.CompareEqual(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareEqualInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
}
public SimpleBinaryOpTest__CompareEqualInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.CompareEqual(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.CompareEqual(
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.CompareEqual(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.CompareEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int16>* pClsVar2 = &_clsVar2)
{
var result = Avx2.CompareEqual(
Avx.LoadVector256((Int16*)(pClsVar1)),
Avx.LoadVector256((Int16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var result = Avx2.CompareEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.CompareEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.CompareEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareEqualInt16();
var result = Avx2.CompareEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__CompareEqualInt16();
fixed (Vector256<Int16>* pFld1 = &test._fld1)
fixed (Vector256<Int16>* pFld2 = &test._fld2)
{
var result = Avx2.CompareEqual(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.CompareEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int16>* pFld1 = &_fld1)
fixed (Vector256<Int16>* pFld2 = &_fld2)
{
var result = Avx2.CompareEqual(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.CompareEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.CompareEqual(
Avx.LoadVector256((Int16*)(&test._fld1)),
Avx.LoadVector256((Int16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int16> op1, Vector256<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != ((left[0] == right[0]) ? unchecked((short)(-1)) : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] == right[i]) ? unchecked((short)(-1)) : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.CompareEqual)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Runtime;
using System.Threading.Tasks;
using System.ServiceModel.Diagnostics;
using System.Collections.Generic;
using System.Threading;
namespace System.ServiceModel.Channels
{
public abstract class CommunicationObject : ICommunicationObject, IAsyncCommunicationObject
{
private bool _closeCalled;
private ExceptionQueue _exceptionQueue;
private bool _onClosingCalled;
private bool _onClosedCalled;
private bool _onOpeningCalled;
private bool _onOpenedCalled;
private bool _raisedClosed;
private bool _raisedClosing;
private bool _raisedFaulted;
private bool _traceOpenAndClose;
private CommunicationState _state;
internal bool _isSynchronousOpen;
internal bool _isSynchronousClose;
private bool _supportsAsyncOpenClose;
private bool _supportsAsyncOpenCloseSet;
private AsyncLock _asyncLock;
private object _thisLock;
protected CommunicationObject()
: this(new object())
{
}
protected CommunicationObject(object mutex)
{
_thisLock = mutex;
EventSender = this;
_state = CommunicationState.Created;
}
// External CommunicationObjects cannot support IAsyncCommunicationObject,
// but can appear to because they may derive from WCF types that do.
// Attempting to call any IAsyncCommunicationObject method on those types
// will go directly to the WCF base type and bypass the external type's
// synchronous or asynchronous code paths. We cannot distinguish between
// this and a product CommunicationObject handling it and calling base.
// This property detects if the current type is safe to use for
// IAsyncCommunicationObject method calls.
internal bool SupportsAsyncOpenClose
{
get
{
if (!_supportsAsyncOpenCloseSet)
{
// We'll use the simple heuristic that namespace System.ServiceModel
// indicates a product type that is required to support async open/close.
// We don't expect exceptions here in NET Native because the product rd.xml
// grants the Reflection degree to all subtypes of ICommunicationObject.
// However, in the interests of being safe, catch that exception if it happens.
try
{
string ns = GetType().Namespace;
_supportsAsyncOpenClose = ns != null && ns.StartsWith("System.ServiceModel");
}
catch
{
// The most likely situation for this exception is the NET Native
// toolchain not recognizing this type is ICommunicationObject.
// But in that case, the best assumption is that this is a WCF
// product type, and therefore it supports async open/close.
_supportsAsyncOpenClose = true;
}
_supportsAsyncOpenCloseSet = true;
}
return _supportsAsyncOpenClose;
}
set
{
// It is permissible for types to set this value if they know
// they can or cannot support async open/close. Unsealed public
// types must *not* set this to true because they cannot know if
// an external derived type does support it.
_supportsAsyncOpenClose = value;
_supportsAsyncOpenCloseSet = true;
}
}
internal bool Aborted { get; private set; }
internal object EventSender { get; set; }
protected bool IsDisposed
{
get { return _state == CommunicationState.Closed; }
}
public CommunicationState State
{
get { return _state; }
}
protected object ThisLock {
get
{
#if DEBUG
if (_asyncLock != null)
{
Fx.Assert("Inconsistent usage of ThisLock and AsyncLock");
}
#endif
return _thisLock;
}
}
internal AsyncLock ThisAsyncLock
{
get
{
if (_asyncLock != null)
{
return _asyncLock;
}
_ = Interlocked.CompareExchange(ref _asyncLock, new AsyncLock(), null);
return _asyncLock;
}
}
protected abstract TimeSpan DefaultCloseTimeout { get; }
protected abstract TimeSpan DefaultOpenTimeout { get; }
internal TimeSpan InternalCloseTimeout
{
get { return DefaultCloseTimeout; }
}
internal TimeSpan InternalOpenTimeout
{
get { return DefaultOpenTimeout; }
}
public event EventHandler Closed;
public event EventHandler Closing;
public event EventHandler Faulted;
public event EventHandler Opened;
public event EventHandler Opening;
public void Abort()
{
lock (_thisLock)
{
if (Aborted || _state == CommunicationState.Closed)
{
return;
}
Aborted = true;
_state = CommunicationState.Closing;
}
try
{
OnClosing();
if (!_onClosingCalled)
{
throw TraceUtility.ThrowHelperError(CreateBaseClassMethodNotCalledException("OnClosing"), Guid.Empty, this);
}
OnAbort();
OnClosed();
if (!_onClosedCalled)
{
throw TraceUtility.ThrowHelperError(CreateBaseClassMethodNotCalledException("OnClosed"), Guid.Empty, this);
}
}
finally
{
}
}
public IAsyncResult BeginClose(AsyncCallback callback, object state)
{
return BeginClose(DefaultCloseTimeout, callback, state);
}
public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return CloseAsyncInternal(timeout).ToApm(callback, state);
}
public IAsyncResult BeginOpen(AsyncCallback callback, object state)
{
return BeginOpen(DefaultOpenTimeout, callback, state);
}
public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return OpenAsyncInternal(timeout).ToApm(callback, state);
}
public void Close()
{
Close(DefaultCloseTimeout);
}
public void Close(TimeSpan timeout)
{
_isSynchronousClose = true;
CloseAsyncInternal(timeout).WaitForCompletion();
}
private async Task CloseAsyncInternal(TimeSpan timeout)
{
await TaskHelpers.EnsureDefaultTaskScheduler();
await ((IAsyncCommunicationObject)this).CloseAsync(timeout);
}
async Task IAsyncCommunicationObject.CloseAsync(TimeSpan timeout)
{
if (timeout < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException(nameof(timeout), SR.SFxTimeoutOutOfRange0));
}
CommunicationState originalState;
lock (_thisLock)
{
originalState = _state;
if (originalState != CommunicationState.Closed)
{
_state = CommunicationState.Closing;
}
_closeCalled = true;
}
switch (originalState)
{
case CommunicationState.Created:
case CommunicationState.Opening:
case CommunicationState.Faulted:
Abort();
if (originalState == CommunicationState.Faulted)
{
throw TraceUtility.ThrowHelperError(CreateFaultedException(), Guid.Empty, this);
}
break;
case CommunicationState.Opened:
{
bool throwing = true;
try
{
TimeoutHelper actualTimeout = new TimeoutHelper(timeout);
OnClosing();
if (!_onClosingCalled)
{
throw TraceUtility.ThrowHelperError(CreateBaseClassMethodNotCalledException("OnClosing"), Guid.Empty, this);
}
await OnCloseAsyncInternal(actualTimeout.RemainingTime());
OnClosed();
if (!_onClosedCalled)
{
throw TraceUtility.ThrowHelperError(CreateBaseClassMethodNotCalledException("OnClosed"), Guid.Empty, this);
}
throwing = false;
}
finally
{
if (throwing)
{
Abort();
}
}
break;
}
case CommunicationState.Closing:
case CommunicationState.Closed:
break;
default:
throw Fx.AssertAndThrow("CommunicationObject.BeginClose: Unknown CommunicationState");
}
}
// Internal helper to call the right form of the OnClose() method
// asynchronously. It depends on whether the type can support the
// async API's and how the current Communication object is being closed.
private async Task OnCloseAsyncInternal(TimeSpan timeout)
{
// If this type is capable of overriding OnCloseAsync,
// then use it for both async and sync closes
if (SupportsAsyncOpenClose)
{
// The class supports OnCloseAsync(), so use it
await OnCloseAsync(timeout);
}
else
{
// This type is an external type that cannot override OnCloseAsync.
// If this is a synchronous close, invoke the synchronous OnClose)
if (_isSynchronousClose)
{
await TaskHelpers.CallActionAsync(OnClose, timeout);
}
else
{
// The class does not support OnCloseAsync, and this is an asynchronous
// close, so use the Begin/End pattern
await Task.Factory.FromAsync(OnBeginClose, OnEndClose, timeout, TaskCreationOptions.RunContinuationsAsynchronously);
}
}
}
private Exception CreateNotOpenException()
{
return new InvalidOperationException(SR.Format(SR.CommunicationObjectCannotBeUsed, GetCommunicationObjectType().ToString(), _state.ToString()));
}
private Exception CreateImmutableException()
{
return new InvalidOperationException(SR.Format(SR.CommunicationObjectCannotBeModifiedInState, GetCommunicationObjectType().ToString(), _state.ToString()));
}
private Exception CreateBaseClassMethodNotCalledException(string method)
{
return new InvalidOperationException(SR.Format(SR.CommunicationObjectBaseClassMethodNotCalled, GetCommunicationObjectType().ToString(), method));
}
internal Exception CreateClosedException()
{
if (!_closeCalled)
{
return CreateAbortedException();
}
else
{
return new ObjectDisposedException(GetCommunicationObjectType().ToString());
}
}
internal Exception CreateFaultedException()
{
string message = SR.Format(SR.CommunicationObjectFaulted1, GetCommunicationObjectType().ToString());
return new CommunicationObjectFaultedException(message);
}
internal Exception CreateAbortedException()
{
return new CommunicationObjectAbortedException(SR.Format(SR.CommunicationObjectAborted1, GetCommunicationObjectType().ToString()));
}
internal bool DoneReceivingInCurrentState()
{
ThrowPending();
switch (_state)
{
case CommunicationState.Created:
throw TraceUtility.ThrowHelperError(CreateNotOpenException(), Guid.Empty, this);
case CommunicationState.Opening:
throw TraceUtility.ThrowHelperError(CreateNotOpenException(), Guid.Empty, this);
case CommunicationState.Opened:
return false;
case CommunicationState.Closing:
return true;
case CommunicationState.Closed:
return true;
case CommunicationState.Faulted:
return true;
default:
throw Fx.AssertAndThrow("DoneReceivingInCurrentState: Unknown CommunicationObject.state");
}
}
public void EndClose(IAsyncResult result)
{
result.ToApmEnd();
}
public void EndOpen(IAsyncResult result)
{
result.ToApmEnd();
}
protected void Fault()
{
lock (_thisLock)
{
if (_state == CommunicationState.Closed || _state == CommunicationState.Closing)
{
return;
}
if (_state == CommunicationState.Faulted)
{
return;
}
_state = CommunicationState.Faulted;
}
OnFaulted();
}
internal void Fault(Exception exception)
{
AddPendingException(exception);
Fault();
}
internal void AddPendingException(Exception exception)
{
lock (_thisLock)
{
if (_exceptionQueue == null)
{
_exceptionQueue = new ExceptionQueue(_thisLock);
}
}
_exceptionQueue.AddException(exception);
}
internal Exception GetPendingException()
{
CommunicationState currentState = _state;
Fx.Assert(currentState == CommunicationState.Closing || currentState == CommunicationState.Closed || currentState == CommunicationState.Faulted,
"CommunicationObject.GetPendingException(currentState == CommunicationState.Closing || currentState == CommunicationState.Closed || currentState == CommunicationState.Faulted)");
ExceptionQueue queue = _exceptionQueue;
if (queue != null)
{
return queue.GetException();
}
else
{
return null;
}
}
// Terminal is loosely defined as an interruption to close or a fault.
internal Exception GetTerminalException()
{
Exception exception = GetPendingException();
if (exception != null)
{
return exception;
}
switch (_state)
{
case CommunicationState.Closing:
case CommunicationState.Closed:
return new CommunicationException(SR.Format(SR.CommunicationObjectCloseInterrupted1, GetCommunicationObjectType().ToString()));
case CommunicationState.Faulted:
return CreateFaultedException();
default:
throw Fx.AssertAndThrow("GetTerminalException: Invalid CommunicationObject.state");
}
}
public void Open()
{
Open(DefaultOpenTimeout);
}
public void Open(TimeSpan timeout)
{
_isSynchronousOpen = true;
OpenAsyncInternal(timeout).WaitForCompletion();
}
private async Task OpenAsyncInternal(TimeSpan timeout)
{
await TaskHelpers.EnsureDefaultTaskScheduler();
await ((IAsyncCommunicationObject)this).OpenAsync(timeout);
}
async Task IAsyncCommunicationObject.OpenAsync(TimeSpan timeout)
{
if (timeout < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException(nameof(timeout), SR.SFxTimeoutOutOfRange0));
}
lock (_thisLock)
{
ThrowIfDisposedOrImmutable();
_state = CommunicationState.Opening;
}
bool throwing = true;
try
{
TimeoutHelper actualTimeout = new TimeoutHelper(timeout);
OnOpening();
if (!_onOpeningCalled)
{
throw TraceUtility.ThrowHelperError(CreateBaseClassMethodNotCalledException("OnOpening"), Guid.Empty, this);
}
await OnOpenAsyncInternal(actualTimeout.RemainingTime());
OnOpened();
if (!_onOpenedCalled)
{
throw TraceUtility.ThrowHelperError(CreateBaseClassMethodNotCalledException("OnOpened"), Guid.Empty, this);
}
throwing = false;
}
finally
{
if (throwing)
{
Fault();
}
}
}
// Internal helper to call the right form of the OnOpen() method
// asynchronously. It depends on whether the type can support the
// async API's and how the current Communication object is being opened.
private async Task OnOpenAsyncInternal(TimeSpan timeout)
{
// If this type is capable of overriding OnOpenAsync,
// then use it for both async and sync opens
if (SupportsAsyncOpenClose)
{
// The class supports OnOpenAsync(), so use it
await OnOpenAsync(timeout);
}
else
{
// This type is an external type that cannot override OnOpenAsync.
// If this is a synchronous open, invoke the synchronous OnOpen)
if (_isSynchronousOpen)
{
await TaskHelpers.CallActionAsync(OnOpen, timeout);
}
else
{
// The class does not support OnOpenAsync, so use the Begin/End pattern
await Task.Factory.FromAsync(OnBeginOpen, OnEndOpen, timeout, TaskCreationOptions.RunContinuationsAsynchronously);
}
}
}
protected virtual void OnClosed()
{
_onClosedCalled = true;
lock (_thisLock)
{
if (_raisedClosed)
{
return;
}
_raisedClosed = true;
_state = CommunicationState.Closed;
}
EventHandler handler = Closed;
if (handler != null)
{
try
{
handler(EventSender, EventArgs.Empty);
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception);
}
}
}
protected virtual void OnClosing()
{
_onClosingCalled = true;
lock (_thisLock)
{
if (_raisedClosing)
{
return;
}
_raisedClosing = true;
}
EventHandler handler = Closing;
if (handler != null)
{
try
{
handler(EventSender, EventArgs.Empty);
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception);
}
}
}
protected virtual void OnFaulted()
{
lock (_thisLock)
{
if (_raisedFaulted)
{
return;
}
_raisedFaulted = true;
}
EventHandler handler = Faulted;
if (handler != null)
{
try
{
handler(EventSender, EventArgs.Empty);
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception);
}
}
}
protected virtual void OnOpened()
{
_onOpenedCalled = true;
lock (_thisLock)
{
if (Aborted || _state != CommunicationState.Opening)
{
return;
}
_state = CommunicationState.Opened;
}
EventHandler handler = Opened;
if (handler != null)
{
try
{
handler(EventSender, EventArgs.Empty);
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception);
}
}
}
protected virtual void OnOpening()
{
_onOpeningCalled = true;
EventHandler handler = Opening;
if (handler != null)
{
try
{
handler(EventSender, EventArgs.Empty);
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception);
}
}
}
internal void ThrowIfFaulted()
{
ThrowPending();
switch (_state)
{
case CommunicationState.Created:
break;
case CommunicationState.Opening:
break;
case CommunicationState.Opened:
break;
case CommunicationState.Closing:
break;
case CommunicationState.Closed:
break;
case CommunicationState.Faulted:
throw TraceUtility.ThrowHelperError(CreateFaultedException(), Guid.Empty, this);
default:
throw Fx.AssertAndThrow("ThrowIfFaulted: Unknown CommunicationObject.state");
}
}
internal void ThrowIfAborted()
{
if (Aborted && !_closeCalled)
{
throw TraceUtility.ThrowHelperError(CreateAbortedException(), Guid.Empty, this);
}
}
internal bool TraceOpenAndClose
{
get
{
return _traceOpenAndClose;
}
set
{
_traceOpenAndClose = value && DiagnosticUtility.ShouldUseActivity;
}
}
internal void ThrowIfClosed()
{
ThrowPending();
switch (_state)
{
case CommunicationState.Created:
break;
case CommunicationState.Opening:
break;
case CommunicationState.Opened:
break;
case CommunicationState.Closing:
break;
case CommunicationState.Closed:
throw TraceUtility.ThrowHelperError(CreateClosedException(), Guid.Empty, this);
case CommunicationState.Faulted:
throw TraceUtility.ThrowHelperError(CreateFaultedException(), Guid.Empty, this);
default:
throw Fx.AssertAndThrow("ThrowIfClosed: Unknown CommunicationObject.state");
}
}
protected virtual Type GetCommunicationObjectType()
{
return GetType();
}
protected internal void ThrowIfDisposed()
{
ThrowPending();
switch (_state)
{
case CommunicationState.Created:
break;
case CommunicationState.Opening:
break;
case CommunicationState.Opened:
break;
case CommunicationState.Closing:
throw TraceUtility.ThrowHelperError(CreateClosedException(), Guid.Empty, this);
case CommunicationState.Closed:
throw TraceUtility.ThrowHelperError(CreateClosedException(), Guid.Empty, this);
case CommunicationState.Faulted:
throw TraceUtility.ThrowHelperError(CreateFaultedException(), Guid.Empty, this);
default:
throw Fx.AssertAndThrow("ThrowIfDisposed: Unknown CommunicationObject.state");
}
}
internal void ThrowIfClosedOrOpened()
{
ThrowPending();
switch (_state)
{
case CommunicationState.Created:
break;
case CommunicationState.Opening:
break;
case CommunicationState.Opened:
throw TraceUtility.ThrowHelperError(CreateImmutableException(), Guid.Empty, this);
case CommunicationState.Closing:
throw TraceUtility.ThrowHelperError(CreateImmutableException(), Guid.Empty, this);
case CommunicationState.Closed:
throw TraceUtility.ThrowHelperError(CreateClosedException(), Guid.Empty, this);
case CommunicationState.Faulted:
throw TraceUtility.ThrowHelperError(CreateFaultedException(), Guid.Empty, this);
default:
throw Fx.AssertAndThrow("ThrowIfClosedOrOpened: Unknown CommunicationObject.state");
}
}
protected internal void ThrowIfDisposedOrImmutable()
{
ThrowPending();
switch (_state)
{
case CommunicationState.Created:
break;
case CommunicationState.Opening:
throw TraceUtility.ThrowHelperError(CreateImmutableException(), Guid.Empty, this);
case CommunicationState.Opened:
throw TraceUtility.ThrowHelperError(CreateImmutableException(), Guid.Empty, this);
case CommunicationState.Closing:
throw TraceUtility.ThrowHelperError(CreateClosedException(), Guid.Empty, this);
case CommunicationState.Closed:
throw TraceUtility.ThrowHelperError(CreateClosedException(), Guid.Empty, this);
case CommunicationState.Faulted:
throw TraceUtility.ThrowHelperError(CreateFaultedException(), Guid.Empty, this);
default:
throw Fx.AssertAndThrow("ThrowIfDisposedOrImmutable: Unknown CommunicationObject.state");
}
}
protected internal void ThrowIfDisposedOrNotOpen()
{
ThrowPending();
switch (_state)
{
case CommunicationState.Created:
throw TraceUtility.ThrowHelperError(CreateNotOpenException(), Guid.Empty, this);
case CommunicationState.Opening:
throw TraceUtility.ThrowHelperError(CreateNotOpenException(), Guid.Empty, this);
case CommunicationState.Opened:
break;
case CommunicationState.Closing:
throw TraceUtility.ThrowHelperError(CreateClosedException(), Guid.Empty, this);
case CommunicationState.Closed:
throw TraceUtility.ThrowHelperError(CreateClosedException(), Guid.Empty, this);
case CommunicationState.Faulted:
throw TraceUtility.ThrowHelperError(CreateFaultedException(), Guid.Empty, this);
default:
throw Fx.AssertAndThrow("ThrowIfDisposedOrNotOpen: Unknown CommunicationObject.state");
}
}
internal void ThrowIfNotOpened()
{
if (_state == CommunicationState.Created || _state == CommunicationState.Opening)
{
throw TraceUtility.ThrowHelperError(CreateNotOpenException(), Guid.Empty, this);
}
}
internal void ThrowIfClosedOrNotOpen()
{
ThrowPending();
switch (_state)
{
case CommunicationState.Created:
throw TraceUtility.ThrowHelperError(CreateNotOpenException(), Guid.Empty, this);
case CommunicationState.Opening:
throw TraceUtility.ThrowHelperError(CreateNotOpenException(), Guid.Empty, this);
case CommunicationState.Opened:
break;
case CommunicationState.Closing:
break;
case CommunicationState.Closed:
throw TraceUtility.ThrowHelperError(CreateClosedException(), Guid.Empty, this);
case CommunicationState.Faulted:
throw TraceUtility.ThrowHelperError(CreateFaultedException(), Guid.Empty, this);
default:
throw Fx.AssertAndThrow("ThrowIfClosedOrNotOpen: Unknown CommunicationObject.state");
}
}
internal void ThrowPending()
{
}
//
// State callbacks
//
protected abstract void OnAbort();
protected abstract void OnClose(TimeSpan timeout);
protected abstract IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state);
protected abstract void OnEndClose(IAsyncResult result);
protected abstract void OnOpen(TimeSpan timeout);
protected abstract IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state);
protected abstract void OnEndOpen(IAsyncResult result);
internal protected virtual Task OnCloseAsync(TimeSpan timeout)
{
// All WCF product types are required to override this method and not call base.
// No external types will be able to reach here because it is not public.
Contract.Assert(false, String.Format("Type '{0}' is required to override OnCloseAsync", GetType()));
return TaskHelpers.CompletedTask();
}
internal protected virtual Task OnOpenAsync(TimeSpan timeout)
{
// All WCF product types are required to override this method and not call base.
// No external types will be able to reach here because it is not public.
Contract.Assert(false, String.Format("Type '{0}' is required to override OnOpenAsync", GetType()));
return TaskHelpers.CompletedTask();
}
// Helper used to open another CommunicationObject "owned" by the current one.
// It is used to propagate the use of either the synchronous or asynchronous methods
internal Task OpenOtherAsync(ICommunicationObject other, TimeSpan timeout)
{
// If the current object is being opened synchronously, use the synchronous
// open path for the other object.
if (_isSynchronousOpen)
{
return TaskHelpers.CallActionAsync(other.Open, timeout);
}
else
{
return Task.Factory.FromAsync(other.BeginOpen, other.EndOpen, timeout, null);
}
}
// Helper used to close another CommunicationObject "owned" by the current one.
// It is used to propagate the use of either the synchronous or asynchronous methods
internal Task CloseOtherAsync(ICommunicationObject other, TimeSpan timeout)
{
// If the current object is being closed synchronously, use the synchronous
// close path for the other object.
if (_isSynchronousClose)
{
return TaskHelpers.CallActionAsync(other.Close, timeout);
}
else
{
return Task.Factory.FromAsync(other.BeginClose, other.EndClose, timeout, null);
}
}
private class ExceptionQueue
{
private Queue<Exception> _exceptions = new Queue<Exception>();
internal ExceptionQueue(object thisLock)
{
_thisLock = thisLock;
}
private object _thisLock { get; }
public void AddException(Exception exception)
{
if (exception == null)
{
return;
}
lock (_thisLock)
{
_exceptions.Enqueue(exception);
}
}
public Exception GetException()
{
lock (_thisLock)
{
if (_exceptions.Count > 0)
{
return _exceptions.Dequeue();
}
}
return null;
}
}
}
// This helper class exists to expose non-contract API's to other ServiceModel projects
public static class CommunicationObjectInternal
{
public static void ThrowIfClosed(CommunicationObject communicationObject)
{
Contract.Assert(communicationObject != null);
communicationObject.ThrowIfClosed();
}
public static void ThrowIfClosedOrOpened(CommunicationObject communicationObject)
{
Contract.Assert(communicationObject != null);
communicationObject.ThrowIfClosedOrOpened();
}
public static void ThrowIfDisposedOrNotOpen(CommunicationObject communicationObject)
{
Contract.Assert(communicationObject != null);
communicationObject.ThrowIfDisposedOrNotOpen();
}
public static void ThrowIfDisposed(CommunicationObject communicationObject)
{
Contract.Assert(communicationObject != null);
communicationObject.ThrowIfDisposed();
}
public static TimeSpan GetInternalCloseTimeout(this CommunicationObject communicationObject)
{
return communicationObject.InternalCloseTimeout;
}
public static void OnClose(CommunicationObject communicationObject, TimeSpan timeout)
{
OnCloseAsyncInternal(communicationObject, timeout).WaitForCompletion();
}
public static IAsyncResult OnBeginClose(CommunicationObject communicationObject, TimeSpan timeout, AsyncCallback callback, object state)
{
return communicationObject.OnCloseAsync(timeout).ToApm(callback, state);
}
public static void OnEnd(IAsyncResult result)
{
result.ToApmEnd();
}
public static void OnOpen(CommunicationObject communicationObject, TimeSpan timeout)
{
OnOpenAsyncInternal(communicationObject, timeout).WaitForCompletion();
}
public static IAsyncResult OnBeginOpen(CommunicationObject communicationObject, TimeSpan timeout, AsyncCallback callback, object state)
{
return communicationObject.OnOpenAsync(timeout).ToApm(callback, state);
}
public static async Task OnCloseAsyncInternal(CommunicationObject communicationObject, TimeSpan timeout)
{
await TaskHelpers.EnsureDefaultTaskScheduler();
await communicationObject.OnCloseAsync(timeout);
}
public static async Task OnOpenAsyncInternal(CommunicationObject communicationObject, TimeSpan timeout)
{
await TaskHelpers.EnsureDefaultTaskScheduler();
await communicationObject.OnOpenAsync(timeout);
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Services.Query;
using Adxstudio.Xrm.Web.UI.JsonConfiguration;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Portal.Web;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Newtonsoft.Json;
namespace Adxstudio.Xrm.EntityList
{
public class EntityListPackageRepositoryDataAdapter : EntityListDataAdapter
{
public EntityListPackageRepositoryDataAdapter(EntityReference packageRepository, EntityReference entityList, EntityReference view, IDataAdapterDependencies dependencies, Func<Guid, Guid, string> getPackageRepositoryUrl, Func<Guid, Guid, string> getPackageVersionUrl, Func<Guid, Guid, string> getPackageImageUrl)
: base(entityList, view, dependencies)
{
if (packageRepository == null) throw new ArgumentNullException("packageRepository");
if (getPackageRepositoryUrl == null) throw new ArgumentNullException("getPackageRepositoryUrl");
if (getPackageVersionUrl == null) throw new ArgumentNullException("getPackageVersionUrl");
if (getPackageImageUrl == null) throw new ArgumentNullException("getPackageImageUrl");
PackageRepository = packageRepository;
GetPackageRepositoryUrl = getPackageRepositoryUrl;
GetPackageVersionUrl = getPackageVersionUrl;
GetPackageImageUrl = getPackageImageUrl;
}
protected Func<Guid, Guid, string> GetPackageImageUrl { get; private set; }
protected Func<Guid, Guid, string> GetPackageRepositoryUrl { get; private set; }
protected Func<Guid, Guid, string> GetPackageVersionUrl { get; private set; }
protected EntityReference PackageRepository { get; private set; }
public PackageRepository SelectRepository(string category = null, string filter = null, string search = null)
{
AssertEntityListAccess();
var serviceContext = Dependencies.GetServiceContext();
Entity packageRepository;
if (!TryGetPackageRepository(serviceContext, PackageRepository, out packageRepository))
{
throw new InvalidOperationException("Unable to retrieve the package repository ({0}:{1}).".FormatWith(PackageRepository.LogicalName, PackageRepository.Id));
}
Entity entityList;
if (!TryGetEntityList(serviceContext, EntityList, out entityList))
{
throw new InvalidOperationException("Unable to retrieve the entity list ({0}:{1}).".FormatWith(EntityList.LogicalName, EntityList.Id));
}
Entity view;
if (!TryGetView(serviceContext, entityList, View, out view))
{
throw new InvalidOperationException("Unable to retrieve view ({0}:{1}).".FormatWith(View.LogicalName, View.Id));
}
var fetchXml = view.GetAttributeValue<string>("fetchxml");
if (string.IsNullOrEmpty(fetchXml))
{
throw new InvalidOperationException("Unable to retrieve the view FetchXML ({0}:{1}).".FormatWith(View.LogicalName, View.Id));
}
var fetch = Fetch.Parse(fetchXml);
var searchableAttributes = fetch.Entity.Attributes.Select(a => a.Name).ToArray();
fetch.Entity.Attributes = FetchAttribute.All;
var settings = new EntityListSettings(entityList);
AddPackageCategoryJoin(fetch.Entity);
AddPackageComponentJoin(fetch.Entity);
AddPackageDependencyJoin(fetch.Entity);
AddPackageImageJoin(fetch.Entity);
AddPackagePublisherJoin(fetch.Entity);
AddPackageVersionJoin(fetch.Entity);
// Refactor the query to reduce links, but just do an in-memory category filter for now.
//AddPackageCategoryFilter(fetch.Entity, category);
AddSelectableFilterToFetchEntity(fetch.Entity, settings, filter);
AddWebsiteFilterToFetchEntity(fetch.Entity, settings);
AddSearchFilterToFetchEntity(fetch.Entity, settings, search, searchableAttributes);
var entityGroupings = FetchEntities(serviceContext, fetch).GroupBy(e => e.Id);
var packages = GetPackages(entityGroupings, GetPackageUrl(settings)).ToArray();
var categoryComparer = new PackageCategoryComparer();
var repositoryCategories = packages.SelectMany(e => e.Categories).Distinct(categoryComparer).OrderBy(e => e.Name);
// Do in-memory category filter.
if (!string.IsNullOrWhiteSpace(category))
{
var filterCategory = new PackageCategory(category);
packages = packages
.Where(e => e.Categories.Any(c => categoryComparer.Equals(c, filterCategory)))
.ToArray();
}
return new PackageRepository
{
Title = packageRepository.GetAttributeValue<string>("adx_name"),
Categories = repositoryCategories,
Packages = packages,
Description = packageRepository.GetAttributeValue<string>("adx_description"),
RequiredInstallerVersion = packageRepository.GetAttributeValue<string>("adx_requiredinstallerversion")
};
}
protected override IEnumerable<Entity> FetchEntities(OrganizationServiceContext serviceContext, Fetch fetch)
{
fetch.PageNumber = 1;
while (true)
{
var response = (RetrieveMultipleResponse)serviceContext.Execute(fetch.ToRetrieveMultipleRequest());
foreach (var entity in response.EntityCollection.Entities)
{
yield return entity;
}
if (!response.EntityCollection.MoreRecords)
{
break;
}
fetch.PageNumber++;
}
}
private Func<Guid, string> GetPackageUrl(EntityListSettings settings)
{
if (settings.WebPageForDetailsView == null)
{
return id => null;
}
var serviceContext = Dependencies.GetServiceContext();
var page = serviceContext.CreateQuery("adx_webpage")
.FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_webpageid") == settings.WebPageForDetailsView.Id);
if (page == null)
{
return id => null;
}
var pageUrl = Dependencies.GetUrlProvider().GetUrl(serviceContext, page);
if (string.IsNullOrEmpty(pageUrl))
{
return id => null;
}
if (string.IsNullOrWhiteSpace(settings.IdQueryStringParameterName))
{
return id => new UrlBuilder(pageUrl) { Fragment = id.ToString() }.ToString();
}
return id =>
{
var url = new UrlBuilder(pageUrl);
url.QueryString.Set(settings.IdQueryStringParameterName, id.ToString());
return url.ToString();
};
}
private IEnumerable<Package> GetPackages(IEnumerable<IGrouping<Guid, Entity>> entityGroupings, Func<Guid, string> getPackageUrl)
{
var website = Dependencies.GetWebsite();
foreach (var entityGrouping in entityGroupings)
{
var entity = entityGrouping.FirstOrDefault();
if (entity == null)
{
continue;
}
var versions = GetPackageVersions(entityGrouping, website.Id)
.OrderByDescending(e => e.ReleaseDate)
.ToArray();
var currentVersion = versions.FirstOrDefault();
if (currentVersion == null)
{
continue;
}
PackageImage icon;
var images = GetPackageImages(entityGrouping, website.Id, entity.GetAttributeValue<EntityReference>("adx_iconid"), out icon)
.OrderBy(e => e.Name)
.ToArray();
yield return new Package
{
Categories = GetPackageCategories(entityGrouping).ToArray(),
Components = GetPackageComponents(entityGrouping, website.Id).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
ContentUrl = currentVersion.Url,
Dependencies = GetPackageDependencies(entityGrouping, website.Id).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
Description = entity.GetAttributeValue<string>("adx_description"),
DisplayName = entity.GetAttributeValue<string>("adx_name"),
HideFromPackageListing = entity.GetAttributeValue<bool?>("adx_hidefromlisting").GetValueOrDefault(false),
Icon = icon,
Images = images,
OverwriteWarning = entity.GetAttributeValue<bool?>("adx_overwritewarning").GetValueOrDefault(false),
PublisherName = entity.GetAttributeAliasedValue<string>("adx_name", "publisher"),
ReleaseDate = currentVersion.ReleaseDate,
RequiredInstallerVersion = currentVersion.RequiredInstallerVersion,
Summary = entity.GetAttributeValue<string>("adx_summary"),
Type = GetPackageType(entity.GetAttributeValue<OptionSetValue>("adx_type")),
UniqueName = entity.GetAttributeValue<string>("adx_uniquename"),
Uri = GetPackageUri(entity.GetAttributeValue<EntityReference>("adx_packagerepositoryid"), website.Id, entity.GetAttributeValue<string>("adx_uniquename")),
Url = getPackageUrl(entity.Id),
Version = currentVersion.Version,
Versions = versions,
Configuration = currentVersion.Configuration
};
}
}
private IEnumerable<PackageCategory> GetPackageCategories(IGrouping<Guid, Entity> entityGrouping)
{
return entityGrouping
.GroupBy(e => e.GetAttributeAliasedValue<Guid?>("adx_packagecategoryid", "category"))
.Where(e => e.Key != null)
.Select(e => e.FirstOrDefault())
.Where(e => e != null)
.Select(e => e.GetAttributeAliasedValue<string>("adx_name", "category"))
.Where(e => !string.IsNullOrWhiteSpace(e))
.Select(e => new PackageCategory(e))
.Distinct(new PackageCategoryComparer())
.OrderBy(e => e.Name);
}
private IEnumerable<PackageComponent> GetPackageComponents(IGrouping<Guid, Entity> entityGrouping, Guid websiteId)
{
var groupings = entityGrouping
.GroupBy(e => e.GetAttributeAliasedValue<Guid?>("adx_packagecomponentid", "component"))
.Where(e => e.Key != null);
foreach (var grouping in groupings)
{
var entity = grouping.FirstOrDefault();
if (entity == null)
{
continue;
}
var packageDisplayName = entity.GetAttributeAliasedValue<string>("adx_name", "componentpackage");
if (string.IsNullOrWhiteSpace(packageDisplayName))
{
continue;
}
var packageUniqueName = entity.GetAttributeAliasedValue<string>("adx_uniquename", "componentpackage");
if (string.IsNullOrWhiteSpace(packageUniqueName))
{
continue;
}
var componentPackageRepository = entity.GetAttributeAliasedValue<EntityReference>("adx_packagerepositoryid", "componentpackage");
yield return new PackageComponent
{
DisplayName = packageDisplayName,
Uri = GetPackageUri(componentPackageRepository, websiteId, packageUniqueName),
Version = entity.GetAttributeAliasedValue<string>("adx_version", "component"),
Order = entity.GetAttributeAliasedValue<int?>("adx_order", "component").GetValueOrDefault(0),
CreatedOn = entity.GetAttributeAliasedValue<DateTime?>("createdon", "component").GetValueOrDefault()
};
}
}
private IEnumerable<PackageDependency> GetPackageDependencies(IGrouping<Guid, Entity> entityGrouping, Guid websiteId)
{
var groupings = entityGrouping
.GroupBy(e => e.GetAttributeAliasedValue<Guid?>("adx_packagedependencyid", "dependency"))
.Where(e => e.Key != null);
foreach (var grouping in groupings)
{
var entity = grouping.FirstOrDefault();
if (entity == null)
{
continue;
}
var packageDisplayName = entity.GetAttributeAliasedValue<string>("adx_name", "dependencypackage");
var packageUniqueName = entity.GetAttributeAliasedValue<string>("adx_uniquename", "dependencypackage");
if (!string.IsNullOrWhiteSpace(packageDisplayName) && !string.IsNullOrWhiteSpace(packageUniqueName))
{
var dependencyPackageRepository = entity.GetAttributeAliasedValue<EntityReference>("adx_packagerepositoryid", "dependencypackage");
yield return new PackageDependency
{
DisplayName = packageDisplayName,
Uri = GetPackageUri(dependencyPackageRepository, websiteId, packageUniqueName),
Version = entity.GetAttributeAliasedValue<string>("adx_version", "dependency"),
Order = entity.GetAttributeAliasedValue<int?>("adx_order", "dependency").GetValueOrDefault(0),
CreatedOn = entity.GetAttributeAliasedValue<DateTime?>("createdon", "dependency").GetValueOrDefault()
};
continue;
}
var packageUri = entity.GetAttributeAliasedValue<string>("adx_dependencypackageuri", "dependency");
Uri parsed;
if (!string.IsNullOrWhiteSpace(packageUri) && Uri.TryCreate(packageUri, UriKind.RelativeOrAbsolute, out parsed))
{
yield return new PackageDependency
{
DisplayName = entity.GetAttributeAliasedValue<string>("adx_name", "dependency"),
Uri = parsed,
Version = entity.GetAttributeAliasedValue<string>("adx_version", "dependency"),
Order = entity.GetAttributeAliasedValue<int?>("adx_order", "dependency").GetValueOrDefault(0),
CreatedOn = entity.GetAttributeAliasedValue<DateTime?>("createdon", "dependency").GetValueOrDefault()
};
}
}
}
private Uri GetPackageUri(EntityReference packageRepository, Guid websiteId, string packageUniqueName)
{
if (packageRepository == null)
{
return new Uri("#" + packageUniqueName, UriKind.Relative);
}
var repositoryUrl = GetPackageRepositoryUrl(websiteId, packageRepository.Id);
return repositoryUrl == null
? new Uri("#" + packageUniqueName, UriKind.Relative)
: new Uri(repositoryUrl + "#" + packageUniqueName, UriKind.RelativeOrAbsolute);
}
private IEnumerable<PackageImage> GetPackageImages(IGrouping<Guid, Entity> entityGrouping, Guid websiteId, EntityReference iconReference, out PackageImage icon)
{
icon = null;
var images = new List<PackageImage>();
var groupings = entityGrouping
.GroupBy(e => e.GetAttributeAliasedValue<Guid?>("adx_packageimageid", "image"))
.Where(e => e.Key != null);
foreach (var grouping in groupings)
{
var entity = grouping.FirstOrDefault();
if (entity == null)
{
continue;
}
var imageId = entity.GetAttributeAliasedValue<Guid?>("adx_packageimageid", "image");
if (imageId == null)
{
continue;
}
var image = new PackageImage
{
Name = entity.GetAttributeAliasedValue<string>("adx_name", "image"),
Description = entity.GetAttributeAliasedValue<string>("adx_description", "image")
?? entity.GetAttributeAliasedValue<string>("adx_name", "image"),
Url = GetPackageImageUrl(websiteId, imageId.Value)
};
if (iconReference != null && iconReference.Id == imageId)
{
icon = image;
}
else
{
images.Add(image);
}
}
return images;
}
private PackageType GetPackageType(OptionSetValue type)
{
if (type == null)
{
return PackageType.Solution;
}
if (type.Value == (int)PackageType.Data)
{
return PackageType.Data;
}
return PackageType.Solution;
}
private IEnumerable<PackageVersion> GetPackageVersions(IGrouping<Guid, Entity> entityGrouping, Guid websiteId)
{
var groupings = entityGrouping
.GroupBy(e => e.GetAttributeAliasedValue<Guid?>("adx_packageversionid", "version"))
.Where(e => e.Key != null);
foreach (var grouping in groupings)
{
var entity = grouping.FirstOrDefault();
if (entity == null)
{
continue;
}
var versionId = entity.GetAttributeAliasedValue<Guid?>("adx_packageversionid", "version");
if (versionId == null)
{
continue;
}
var configurationJson = entity.GetAttributeAliasedValue<string>("adx_configuration", "version");
var configuration = new PackageConfiguration();
if (!string.IsNullOrWhiteSpace(configurationJson))
{
try
{
configuration = JsonConvert.DeserializeObject<PackageConfiguration>(configurationJson,
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, Binder = new PackageConfigurationSerializationBinder() });
}
catch (Exception e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("GetPackageVersions", "{0}", e.ToString()));
}
}
yield return new PackageVersion
{
Description = entity.GetAttributeAliasedValue<string>("adx_description", "version"),
DisplayName = entity.GetAttributeAliasedValue<string>("adx_name", "version"),
ReleaseDate = entity.GetAttributeAliasedValue<DateTime?>("adx_releasedate", "version").GetValueOrDefault(),
RequiredInstallerVersion = entity.GetAttributeAliasedValue<string>("adx_requiredinstallerversion", "version"),
Url = GetPackageVersionUrl(websiteId, versionId.Value),
Version = entity.GetAttributeAliasedValue<string>("adx_version", "version"),
Configuration = configuration
};
}
}
protected virtual void AddPackageCategoryJoin(FetchEntity fetchEntity)
{
fetchEntity.Links.Add(new Link
{
Name = "adx_package_packagecategory",
FromAttribute = "adx_packageid",
ToAttribute = "adx_packageid",
Type = JoinOperator.LeftOuter,
Links = new[]
{
new Link
{
Alias = "category",
Name = "adx_packagecategory",
FromAttribute = "adx_packagecategoryid",
ToAttribute = "adx_packagecategoryid",
Type = JoinOperator.LeftOuter,
Attributes = new[]
{
new FetchAttribute("adx_packagecategoryid"),
new FetchAttribute("adx_name"),
},
Filters = new[]
{
new Filter
{
Conditions = new[]
{
new Condition("statecode", ConditionOperator.Equal, 0)
}
}
}
}
}
});
}
protected virtual void AddPackageComponentJoin(FetchEntity fetchEntity)
{
fetchEntity.Links.Add(new Link
{
Alias = "component",
Name = "adx_packagecomponent",
FromAttribute = "adx_packageid",
ToAttribute = "adx_packageid",
Type = JoinOperator.LeftOuter,
Attributes = new[]
{
new FetchAttribute("adx_packagecomponentid"),
new FetchAttribute("adx_name"),
new FetchAttribute("adx_packageid"),
new FetchAttribute("adx_componentpackageid"),
new FetchAttribute("adx_version"),
new FetchAttribute("adx_order"),
new FetchAttribute("createdon"),
},
Links = new[]
{
new Link
{
Alias = "componentpackage",
Name = "adx_package",
FromAttribute = "adx_packageid",
ToAttribute = "adx_componentpackageid",
Type = JoinOperator.LeftOuter,
Attributes = new[]
{
new FetchAttribute("adx_packageid"),
new FetchAttribute("adx_name"),
new FetchAttribute("adx_uniquename"),
new FetchAttribute("adx_packagerepositoryid")
},
Filters = new[]
{
new Filter
{
Conditions = new[]
{
new Condition("statecode", ConditionOperator.Equal, 0)
}
}
}
}
},
Filters = new[]
{
new Filter
{
Conditions = new[]
{
new Condition("statecode", ConditionOperator.Equal, 0)
}
}
}
});
}
protected virtual void AddPackageDependencyJoin(FetchEntity fetchEntity)
{
fetchEntity.Links.Add(new Link
{
Alias = "dependency",
Name = "adx_packagedependency",
FromAttribute = "adx_packageid",
ToAttribute = "adx_packageid",
Type = JoinOperator.LeftOuter,
Attributes = new[]
{
new FetchAttribute("adx_packagedependencyid"),
new FetchAttribute("adx_name"),
new FetchAttribute("adx_packageid"),
new FetchAttribute("adx_dependencypackageid"),
new FetchAttribute("adx_dependencypackageuri"),
new FetchAttribute("adx_version"),
new FetchAttribute("adx_order"),
new FetchAttribute("createdon"),
},
Links = new[]
{
new Link
{
Alias = "dependencypackage",
Name = "adx_package",
FromAttribute = "adx_packageid",
ToAttribute = "adx_dependencypackageid",
Type = JoinOperator.LeftOuter,
Attributes = new[]
{
new FetchAttribute("adx_packageid"),
new FetchAttribute("adx_name"),
new FetchAttribute("adx_uniquename"),
new FetchAttribute("adx_packagerepositoryid")
},
Filters = new[]
{
new Filter
{
Conditions = new[]
{
new Condition("statecode", ConditionOperator.Equal, 0)
}
}
}
}
},
Filters = new[]
{
new Filter
{
Conditions = new[]
{
new Condition("statecode", ConditionOperator.Equal, 0)
}
}
}
});
}
protected virtual void AddPackageImageJoin(FetchEntity fetchEntity)
{
fetchEntity.Links.Add(new Link
{
Alias = "image",
Name = "adx_packageimage",
FromAttribute = "adx_packageid",
ToAttribute = "adx_packageid",
Type = JoinOperator.LeftOuter,
Attributes = new[]
{
new FetchAttribute("adx_packageimageid"),
new FetchAttribute("adx_name"),
new FetchAttribute("adx_description"),
},
Filters = new[]
{
new Filter
{
Conditions = new[]
{
new Condition("statecode", ConditionOperator.Equal, 0)
}
}
}
});
}
protected virtual void AddPackagePublisherJoin(FetchEntity fetchEntity)
{
fetchEntity.Links.Add(new Link
{
Alias = "publisher",
Name = "adx_packagepublisher",
FromAttribute = "adx_packagepublisherid",
ToAttribute = "adx_publisherid",
Type = JoinOperator.LeftOuter,
Attributes = new[]
{
new FetchAttribute("adx_name"),
new FetchAttribute("adx_uniquename"),
}
});
}
protected virtual void AddPackageVersionJoin(FetchEntity fetchEntity)
{
fetchEntity.Links.Add(new Link
{
Alias = "version",
Name = "adx_packageversion",
FromAttribute = "adx_packageid",
ToAttribute = "adx_packageid",
Type = JoinOperator.LeftOuter,
Attributes = new[]
{
new FetchAttribute("adx_packageversionid"),
new FetchAttribute("adx_description"),
new FetchAttribute("adx_name"),
new FetchAttribute("adx_packageid"),
new FetchAttribute("adx_releasedate"),
new FetchAttribute("adx_requiredinstallerversion"),
new FetchAttribute("adx_version"),
new FetchAttribute("adx_configuration")
},
Filters = new[]
{
new Filter
{
Conditions = new[]
{
new Condition("statecode", ConditionOperator.Equal, 0)
}
}
}
});
}
protected virtual void AddPackageCategoryFilter(FetchEntity fetchEntity, string category)
{
if (string.IsNullOrWhiteSpace(category))
{
return;
}
fetchEntity.Links.Add(new Link
{
Name = "adx_package_packagecategory",
FromAttribute = "adx_packageid",
ToAttribute = "adx_packageid",
Type = JoinOperator.Inner,
Links = new[]
{
new Link
{
Name = "adx_packagecategory",
FromAttribute = "adx_packagecategoryid",
ToAttribute = "adx_packagecategoryid",
Type = JoinOperator.Inner,
Filters = new[]
{
new Filter
{
Type = LogicalOperator.And,
Conditions = new[]
{
new Condition("adx_name", ConditionOperator.Equal, category),
new Condition("statecode", ConditionOperator.Equal, 0)
}
}
}
}
}
});
}
protected static bool TryGetPackageRepository(OrganizationServiceContext serviceContext, EntityReference packageRepositoryReference, out Entity packageRepository)
{
packageRepository = serviceContext.CreateQuery("adx_packagerepository")
.FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_packagerepositoryid") == packageRepositoryReference.Id
&& e.GetAttributeValue<int?>("statecode") == 0);
return packageRepository != null;
}
protected class PackageCategoryComparer : IEqualityComparer<PackageCategory>
{
public bool Equals(PackageCategory x, PackageCategory y)
{
return StringComparer.InvariantCultureIgnoreCase.Equals(x.Name, y.Name);
}
public int GetHashCode(PackageCategory category)
{
return category.Name.GetHashCode();
}
}
}
public class PackageRepository
{
public IEnumerable<PackageCategory> Categories { get; set; }
public IEnumerable<Package> Packages { get; set; }
public string RequiredInstallerVersion { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
public enum PackageType
{
Solution = 756150000,
Data = 756150001
}
public class Package
{
public IEnumerable<PackageCategory> Categories { get; set; }
public IEnumerable<PackageComponent> Components { get; set; }
public PackageConfiguration Configuration { get; set; }
public string ContentUrl { get; set; }
public IEnumerable<PackageDependency> Dependencies { get; set; }
public string Description { get; set; }
public string DisplayName { get; set; }
public bool HideFromPackageListing { get; set; }
public PackageImage Icon { get; set; }
public IEnumerable<PackageImage> Images { get; set; }
public bool OverwriteWarning { get; set; }
public string PublisherName { get; set; }
public DateTime ReleaseDate { get; set; }
public string RequiredInstallerVersion { get; set; }
public string Summary { get; set; }
public PackageType Type { get; set; }
public string UniqueName { get; set; }
public Uri Uri { get; set; }
public string Url { get; set; }
public string Version { get; set; }
public IEnumerable<PackageVersion> Versions { get; set; }
}
public class PackageCategory
{
public PackageCategory(string name)
{
if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value can't be null or whitespace.", "name");
Name = name;
}
public string Name { get; private set; }
}
public class PackageComponent
{
public DateTime CreatedOn { get; set; }
public string DisplayName { get; set; }
public int Order { get; set; }
public Uri Uri { get; set; }
public string Version { get; set; }
}
public class PackageDependency
{
public DateTime CreatedOn { get; set; }
public string DisplayName { get; set; }
public int Order { get; set; }
public Uri Uri { get; set; }
public string Version { get; set; }
}
public class PackageImage
{
public string Description { get; set; }
public string Name { get; set; }
public string Url { get; set; }
}
public class PackageVersion
{
public PackageConfiguration Configuration { get; set; }
public string Description { get; set; }
public string DisplayName { get; set; }
public DateTime ReleaseDate { get; set; }
public string RequiredInstallerVersion { get; set; }
public string Url { get; set; }
public string Version { get; set; }
}
/// <summary>
/// Definition of entity reference replacements for a given data package
/// </summary>
public class PackageReferenceReplacements
{
/// <summary>
/// Id of the record
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Logical name of the entity
/// </summary>
public string LogicalName { get; set; }
/// <summary>
/// Name of the record
/// </summary>
public string Name { get; set; }
/// <summary>
/// Operation that informs the installer how to acquire the replacement entity reference. One of the following values 'SelectWebsite', 'FindVisibleState', 'FindByName', 'FindRootPage'.
/// </summary>
public string Operation { get; set; }
}
/// <summary>
/// The definition of attribute value replacements for a given data package.
/// </summary>
public class PackageAttributeReplacements
{
/// <summary>
/// The Id of the record.
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// The Logical name of the entity.
/// </summary>
public string EntityLogicalName { get; set; }
/// <summary>
/// The Logical name of the attribute.
/// </summary>
public string AttributeLogicalName { get; set; }
/// <summary>
/// One of the valid HTML input types. Use 'textarea' to display a textarea. Use 'select' to display a select dropdown, combined with setting the Options property.
/// </summary>
public string Type { get; set; }
/// <summary>
/// An optional block of text to provide additional instructions or to describe the intentions of the input.
/// </summary>
public string Description { get; set; }
/// <summary>
/// The field's label text.
/// </summary>
public string Label { get; set; }
/// <summary>
/// The Id and name of the HTML element.
/// </summary>
public string InputId { get; set; }
/// <summary>
/// Indicates whether the field is required or not.
/// </summary>
public bool Required { get; set; }
/// <summary>
/// The placeholder text assigned to the input.
/// </summary>
public string Placeholder { get; set; }
/// <summary>
/// The maximum length of the input.
/// </summary>
public int? MaxLength { get; set; }
/// <summary>
/// The minimum value used when Type is 'number' during validation.
/// </summary>
public string Min { get; set; }
/// <summary>
/// The maximum value used when Type is 'number' during validation.
/// </summary>
public string Max { get; set; }
/// <summary>
/// The value of increment applicable when Type is 'number'.
/// </summary>
public string Step { get; set; }
/// <summary>
/// The default value assigned to the input.
/// </summary>
public string DefaultValue { get; set; }
/// <summary>
/// The options to be created when Type is 'select'.
/// </summary>
public IEnumerable<SelectOption> Options { get; set; }
/// <summary>
/// The number or rows applicable when Type is 'textarea'.
/// </summary>
public int? Rows { get; set; }
/// <summary>
/// The number or columns applicable when Type is 'textarea'.
/// </summary>
public int? Cols { get; set; }
}
public class SelectOption
{
public string Value { get; set; }
public string Text { get; set; }
}
public class PackageConfiguration
{
public bool DuplicationEnabled { get; set; }
public IEnumerable<PackageReferenceReplacements> ReferenceReplacementTargets { get; set; }
public IEnumerable<PackageAttributeReplacements> AttributeReplacementTargets { get; set; }
}
public class PackageConfigurationSerializationBinder : SerializationBinder
{
private IList<Type> _knownTypes;
/// <summary>
///
/// </summary>
private IList<Type> KnownTypes
{
get
{
if (_knownTypes == null)
{
_knownTypes = new List<Type>
{
typeof(PackageConfiguration)
};
}
return _knownTypes;
}
}
public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
{
assemblyName = null;
typeName = serializedType.Name;
}
public override Type BindToType(string assemblyName, string typeName)
{
return KnownTypes.FirstOrDefault(t => t.FullName == typeName) ?? typeof(NotSupportedAction);
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookChartLegendFormatRequest.
/// </summary>
public partial class WorkbookChartLegendFormatRequest : BaseRequest, IWorkbookChartLegendFormatRequest
{
/// <summary>
/// Constructs a new WorkbookChartLegendFormatRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookChartLegendFormatRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified WorkbookChartLegendFormat using POST.
/// </summary>
/// <param name="workbookChartLegendFormatToCreate">The WorkbookChartLegendFormat to create.</param>
/// <returns>The created WorkbookChartLegendFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartLegendFormat> CreateAsync(WorkbookChartLegendFormat workbookChartLegendFormatToCreate)
{
return this.CreateAsync(workbookChartLegendFormatToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified WorkbookChartLegendFormat using POST.
/// </summary>
/// <param name="workbookChartLegendFormatToCreate">The WorkbookChartLegendFormat to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookChartLegendFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartLegendFormat> CreateAsync(WorkbookChartLegendFormat workbookChartLegendFormatToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<WorkbookChartLegendFormat>(workbookChartLegendFormatToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified WorkbookChartLegendFormat.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified WorkbookChartLegendFormat.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<WorkbookChartLegendFormat>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified WorkbookChartLegendFormat.
/// </summary>
/// <returns>The WorkbookChartLegendFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartLegendFormat> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified WorkbookChartLegendFormat.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookChartLegendFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartLegendFormat> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<WorkbookChartLegendFormat>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified WorkbookChartLegendFormat using PATCH.
/// </summary>
/// <param name="workbookChartLegendFormatToUpdate">The WorkbookChartLegendFormat to update.</param>
/// <returns>The updated WorkbookChartLegendFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartLegendFormat> UpdateAsync(WorkbookChartLegendFormat workbookChartLegendFormatToUpdate)
{
return this.UpdateAsync(workbookChartLegendFormatToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified WorkbookChartLegendFormat using PATCH.
/// </summary>
/// <param name="workbookChartLegendFormatToUpdate">The WorkbookChartLegendFormat to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookChartLegendFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartLegendFormat> UpdateAsync(WorkbookChartLegendFormat workbookChartLegendFormatToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<WorkbookChartLegendFormat>(workbookChartLegendFormatToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartLegendFormatRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartLegendFormatRequest Expand(Expression<Func<WorkbookChartLegendFormat, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartLegendFormatRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartLegendFormatRequest Select(Expression<Func<WorkbookChartLegendFormat, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="workbookChartLegendFormatToInitialize">The <see cref="WorkbookChartLegendFormat"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(WorkbookChartLegendFormat workbookChartLegendFormatToInitialize)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.IO;
using System.Runtime.Versioning;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
namespace System.Runtime.Loader
{
public abstract class AssemblyLoadContext
{
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern bool CanUseAppPathAssemblyLoadContextInCurrentDomain();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext, bool fRepresentsTPALoadContext);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern IntPtr LoadFromStream(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyArray, int iAssemblyArrayLen, IntPtr ptrSymbols, int iSymbolArrayLen, ObjectHandleOnStack retAssembly);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern void InternalSetProfileRoot(string directoryPath);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext);
protected AssemblyLoadContext()
{
// Initialize the ALC representing non-TPA LoadContext
InitializeLoadContext(false);
}
internal AssemblyLoadContext(bool fRepresentsTPALoadContext)
{
// Initialize the ALC representing TPA LoadContext
InitializeLoadContext(fRepresentsTPALoadContext);
}
private void InitializeLoadContext(bool fRepresentsTPALoadContext)
{
// Initialize the VM side of AssemblyLoadContext if not already done.
GCHandle gchALC = GCHandle.Alloc(this);
IntPtr ptrALC = GCHandle.ToIntPtr(gchALC);
m_pNativeAssemblyLoadContext = InitializeAssemblyLoadContext(ptrALC, fRepresentsTPALoadContext);
// Initialize event handlers to be null by default
Resolving = null;
Unloading = null;
// Since unloading an AssemblyLoadContext is not yet implemented, this is a temporary solution to raise the
// Unloading event on process exit. Register for the current AppDomain's ProcessExit event, and the handler will in
// turn raise the Unloading event.
AppContext.Unloading += OnAppContextUnloading;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string ilPath, string niPath, ObjectHandleOnStack retAssembly);
public static Assembly[] GetLoadedAssemblies()
{
return AppDomain.CurrentDomain.GetAssemblies(false);
}
// These are helpers that can be used by AssemblyLoadContext derivations.
// They are used to load assemblies in DefaultContext.
public Assembly LoadFromAssemblyPath(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException(nameof(assemblyPath));
}
if (PathInternal.IsPartiallyQualified(assemblyPath))
{
throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(assemblyPath));
}
RuntimeAssembly loadedAssembly = null;
LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, null, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
return loadedAssembly;
}
public Assembly LoadFromNativeImagePath(string nativeImagePath, string assemblyPath)
{
if (nativeImagePath == null)
{
throw new ArgumentNullException(nameof(nativeImagePath));
}
if (PathInternal.IsPartiallyQualified(nativeImagePath))
{
throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(nativeImagePath));
}
if (assemblyPath != null && PathInternal.IsPartiallyQualified(assemblyPath))
{
throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(assemblyPath));
}
// Basic validation has succeeded - lets try to load the NI image.
// Ask LoadFile to load the specified assembly in the DefaultContext
RuntimeAssembly loadedAssembly = null;
LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, nativeImagePath, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
return loadedAssembly;
}
public Assembly LoadFromStream(Stream assembly)
{
return LoadFromStream(assembly, null);
}
public Assembly LoadFromStream(Stream assembly, Stream assemblySymbols)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
if (assembly.Length <= 0)
{
throw new BadImageFormatException(SR.BadImageFormat_BadILFormat);
}
int iAssemblyStreamLength = (int)assembly.Length;
int iSymbolLength = 0;
// Allocate the byte[] to hold the assembly
byte[] arrAssembly = new byte[iAssemblyStreamLength];
// Copy the assembly to the byte array
assembly.Read(arrAssembly, 0, iAssemblyStreamLength);
// Get the symbol stream in byte[] if provided
byte[] arrSymbols = null;
if (assemblySymbols != null)
{
iSymbolLength = (int)assemblySymbols.Length;
arrSymbols = new byte[iSymbolLength];
assemblySymbols.Read(arrSymbols, 0, iSymbolLength);
}
RuntimeAssembly loadedAssembly = null;
unsafe
{
fixed (byte* ptrAssembly = arrAssembly, ptrSymbols = arrSymbols)
{
LoadFromStream(m_pNativeAssemblyLoadContext, new IntPtr(ptrAssembly), iAssemblyStreamLength, new IntPtr(ptrSymbols), iSymbolLength, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
}
}
return loadedAssembly;
}
// Custom AssemblyLoadContext implementations can override this
// method to perform custom processing and use one of the protected
// helpers above to load the assembly.
protected abstract Assembly Load(AssemblyName assemblyName);
// This method is invoked by the VM when using the host-provided assembly load context
// implementation.
private static Assembly Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
return context.ResolveUsingLoad(assemblyName);
}
// This method is invoked by the VM to resolve an assembly reference using the Resolving event
// after trying assembly resolution via Load override and TPA load context without success.
private static Assembly ResolveUsingResolvingEvent(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
// Invoke the AssemblyResolve event callbacks if wired up
return context.ResolveUsingEvent(assemblyName);
}
private Assembly GetFirstResolvedAssembly(AssemblyName assemblyName)
{
Assembly resolvedAssembly = null;
Func<AssemblyLoadContext, AssemblyName, Assembly> assemblyResolveHandler = Resolving;
if (assemblyResolveHandler != null)
{
// Loop through the event subscribers and return the first non-null Assembly instance
foreach (Func<AssemblyLoadContext, AssemblyName, Assembly> handler in assemblyResolveHandler.GetInvocationList())
{
resolvedAssembly = handler(this, assemblyName);
if (resolvedAssembly != null)
{
break;
}
}
}
return resolvedAssembly;
}
private Assembly ValidateAssemblyNameWithSimpleName(Assembly assembly, string requestedSimpleName)
{
// Get the name of the loaded assembly
string loadedSimpleName = null;
// Derived type's Load implementation is expected to use one of the LoadFrom* methods to get the assembly
// which is a RuntimeAssembly instance. However, since Assembly type can be used build any other artifact (e.g. AssemblyBuilder),
// we need to check for RuntimeAssembly.
RuntimeAssembly rtLoadedAssembly = assembly as RuntimeAssembly;
if (rtLoadedAssembly != null)
{
loadedSimpleName = rtLoadedAssembly.GetSimpleName();
}
// The simple names should match at the very least
if (String.IsNullOrEmpty(loadedSimpleName) || (!requestedSimpleName.Equals(loadedSimpleName, StringComparison.InvariantCultureIgnoreCase)))
throw new InvalidOperationException(SR.Argument_CustomAssemblyLoadContextRequestedNameMismatch);
return assembly;
}
private Assembly ResolveUsingLoad(AssemblyName assemblyName)
{
string simpleName = assemblyName.Name;
Assembly assembly = Load(assemblyName);
if (assembly != null)
{
assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName);
}
return assembly;
}
private Assembly ResolveUsingEvent(AssemblyName assemblyName)
{
string simpleName = assemblyName.Name;
// Invoke the AssemblyResolve event callbacks if wired up
Assembly assembly = GetFirstResolvedAssembly(assemblyName);
if (assembly != null)
{
assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName);
}
// Since attempt to resolve the assembly via Resolving event is the last option,
// throw an exception if we do not find any assembly.
if (assembly == null)
{
throw new FileNotFoundException(SR.IO_FileLoad, simpleName);
}
return assembly;
}
public Assembly LoadFromAssemblyName(AssemblyName assemblyName)
{
// Attempt to load the assembly, using the same ordering as static load, in the current load context.
Assembly loadedAssembly = Assembly.Load(assemblyName, m_pNativeAssemblyLoadContext);
return loadedAssembly;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern IntPtr InternalLoadUnmanagedDllFromPath(string unmanagedDllPath);
// This method provides a way for overriders of LoadUnmanagedDll() to load an unmanaged DLL from a specific path in a
// platform-independent way. The DLL is loaded with default load flags.
protected IntPtr LoadUnmanagedDllFromPath(string unmanagedDllPath)
{
if (unmanagedDllPath == null)
{
throw new ArgumentNullException(nameof(unmanagedDllPath));
}
if (unmanagedDllPath.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(unmanagedDllPath));
}
if (PathInternal.IsPartiallyQualified(unmanagedDllPath))
{
throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(unmanagedDllPath));
}
return InternalLoadUnmanagedDllFromPath(unmanagedDllPath);
}
// Custom AssemblyLoadContext implementations can override this
// method to perform the load of unmanaged native dll
// This function needs to return the HMODULE of the dll it loads
protected virtual IntPtr LoadUnmanagedDll(String unmanagedDllName)
{
//defer to default coreclr policy of loading unmanaged dll
return IntPtr.Zero;
}
// This method is invoked by the VM when using the host-provided assembly load context
// implementation.
private static IntPtr ResolveUnmanagedDll(String unmanagedDllName, IntPtr gchManagedAssemblyLoadContext)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
return context.LoadUnmanagedDll(unmanagedDllName);
}
public static AssemblyLoadContext Default
{
get
{
if (s_DefaultAssemblyLoadContext == null)
{
// Try to initialize the default assembly load context with apppath one if we are allowed to
if (AssemblyLoadContext.CanUseAppPathAssemblyLoadContextInCurrentDomain())
{
// Synchronize access to initializing Default ALC
lock (s_initLock)
{
if (s_DefaultAssemblyLoadContext == null)
{
s_DefaultAssemblyLoadContext = new AppPathAssemblyLoadContext();
}
}
}
}
return s_DefaultAssemblyLoadContext;
}
}
// Helper to return AssemblyName corresponding to the path of an IL assembly
public static AssemblyName GetAssemblyName(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException(nameof(assemblyPath));
}
return AssemblyName.GetAssemblyName(assemblyPath);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern IntPtr GetLoadContextForAssembly(RuntimeAssembly assembly);
// Returns the load context in which the specified assembly has been loaded
public static AssemblyLoadContext GetLoadContext(Assembly assembly)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
AssemblyLoadContext loadContextForAssembly = null;
RuntimeAssembly rtAsm = assembly as RuntimeAssembly;
// We only support looking up load context for runtime assemblies.
if (rtAsm != null)
{
IntPtr ptrAssemblyLoadContext = GetLoadContextForAssembly(rtAsm);
if (ptrAssemblyLoadContext == IntPtr.Zero)
{
// If the load context is returned null, then the assembly was bound using the TPA binder
// and we shall return reference to the active "Default" binder - which could be the TPA binder
// or an overridden CLRPrivBinderAssemblyLoadContext instance.
loadContextForAssembly = AssemblyLoadContext.Default;
}
else
{
loadContextForAssembly = (AssemblyLoadContext)(GCHandle.FromIntPtr(ptrAssemblyLoadContext).Target);
}
}
return loadContextForAssembly;
}
// Set the root directory path for profile optimization.
public void SetProfileOptimizationRoot(string directoryPath)
{
InternalSetProfileRoot(directoryPath);
}
// Start profile optimization for the specified profile name.
public void StartProfileOptimization(string profile)
{
InternalStartProfile(profile, m_pNativeAssemblyLoadContext);
}
private void OnAppContextUnloading(object sender, EventArgs e)
{
var unloading = Unloading;
if (unloading != null)
{
unloading(this);
}
}
public event Func<AssemblyLoadContext, AssemblyName, Assembly> Resolving;
public event Action<AssemblyLoadContext> Unloading;
// Contains the reference to VM's representation of the AssemblyLoadContext
private IntPtr m_pNativeAssemblyLoadContext;
// Each AppDomain contains the reference to its AssemblyLoadContext instance, if one is
// specified by the host. By having the field as a static, we are
// making it an AppDomain-wide field.
private static volatile AssemblyLoadContext s_DefaultAssemblyLoadContext;
// Synchronization primitive for controlling initialization of Default load context
private static readonly object s_initLock = new Object();
// Occurs when an Assembly is loaded
public static event AssemblyLoadEventHandler AssemblyLoad
{
add { AppDomain.CurrentDomain.AssemblyLoad += value; }
remove { AppDomain.CurrentDomain.AssemblyLoad -= value; }
}
// Occurs when resolution of type fails
public static event ResolveEventHandler TypeResolve
{
add { AppDomain.CurrentDomain.TypeResolve += value; }
remove { AppDomain.CurrentDomain.TypeResolve -= value; }
}
// Occurs when resolution of resource fails
public static event ResolveEventHandler ResourceResolve
{
add { AppDomain.CurrentDomain.ResourceResolve += value; }
remove { AppDomain.CurrentDomain.ResourceResolve -= value; }
}
// Occurs when resolution of assembly fails
// This event is fired after resolve events of AssemblyLoadContext fails
public static event ResolveEventHandler AssemblyResolve
{
add { AppDomain.CurrentDomain.AssemblyResolve += value; }
remove { AppDomain.CurrentDomain.AssemblyResolve -= value; }
}
}
internal class AppPathAssemblyLoadContext : AssemblyLoadContext
{
internal AppPathAssemblyLoadContext() : base(true)
{
}
protected override Assembly Load(AssemblyName assemblyName)
{
// We were loading an assembly into TPA ALC that was not found on TPA list. As a result we are here.
// Returning null will result in the AssemblyResolve event subscribers to be invoked to help resolve the assembly.
return null;
}
}
internal class IndividualAssemblyLoadContext : AssemblyLoadContext
{
internal IndividualAssemblyLoadContext() : base(false)
{
}
protected override Assembly Load(AssemblyName assemblyName)
{
return null;
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Diagnostics;
using MyGeneration.CodeSmithConversion.Parser;
using MyGeneration.CodeSmithConversion.Template;
using MyGeneration.CodeSmithConversion.Conversion;
namespace MyGeneration.CodeSmithConversion
{
/// <summary>
/// Summary description for FormConvertCodeSmith.
/// </summary>
public class FormConvertCodeSmith : System.Windows.Forms.Form, ILog
{
private System.Windows.Forms.Button buttonConvert;
private System.Windows.Forms.TextBox textBoxConsole;
private System.Windows.Forms.TextBox textBoxCodeSmithPath;
private System.Windows.Forms.TextBox textBoxCSTFile;
private System.Windows.Forms.Label labelCodeSmithPath;
private System.Windows.Forms.Label labelCSTFile;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog;
private System.Windows.Forms.Button buttonCodeSmithPath;
private System.Windows.Forms.Button buttonCSTPath;
private System.Windows.Forms.CheckedListBox checkedListBoxTemplates;
private System.Windows.Forms.Label labelTemplates;
private System.Windows.Forms.Button buttonOutPath;
private System.Windows.Forms.Label labelOutFolder;
private System.Windows.Forms.TextBox textBoxOutFolder;
private System.Windows.Forms.GroupBox groupBoxCodeSmith;
private System.Windows.Forms.GroupBox groupBoxMyGen;
private System.Windows.Forms.MainMenu mainMenuConverter;
private System.Windows.Forms.MenuItem menuItemFile;
private System.Windows.Forms.MenuItem menuItemExit;
private System.Windows.Forms.MenuItem menuItemHelp;
private System.Windows.Forms.MenuItem menuItemAbout;
private System.Windows.Forms.Button buttonExit;
private System.Windows.Forms.Label labelConversionLog;
private System.Windows.Forms.MenuItem menuItemConvert;
private System.Windows.Forms.MenuItem menuItemFileSep01;
private System.Windows.Forms.CheckBox checkBoxLaunch;
private System.Windows.Forms.TextBox textBoxMyGenAppPath;
private System.Windows.Forms.Label labelMyGenAppPath;
private System.Windows.Forms.Button buttonMyGenAppPath;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.Button buttonSaveLog;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
[STAThread]
static void Main()
{
Application.Run(new FormConvertCodeSmith());
}
public FormConvertCodeSmith()
{
// Required for Windows Form Designer support
InitializeComponent();
}
private void FormConvertCodeSmith_Load(object sender, System.EventArgs e)
{
// Load settings from config file
Config conf = Config.Current;
this.textBoxCSTFile.Text = conf.CodeSmithTemplatePath;
this.textBoxCodeSmithPath.Text = conf.CodeSmithAppPath;
this.textBoxMyGenAppPath.Text = conf.MyGenExePath;
this.textBoxOutFolder.Text = conf.MyGenTemplatePath;
this.checkBoxLaunch.Checked = conf.Launch;
this.textBoxCSTFile_Leave(sender, e);
}
private void FormConvertCodeSmith_Closed(object sender, System.EventArgs e)
{
// Save settings to config file
Config conf = Config.Current;
conf.CodeSmithTemplatePath = this.textBoxCSTFile.Text;
conf.CodeSmithAppPath = this.textBoxCodeSmithPath.Text;
conf.MyGenExePath = this.textBoxMyGenAppPath.Text;
conf.MyGenTemplatePath = this.textBoxOutFolder.Text;
conf.Launch = this.checkBoxLaunch.Checked;
conf.Save();
}
private bool IsFormValid
{
get
{
bool isValid = true;
string message = "Form Failed Validation:";
FileInfo finfo;
DirectoryInfo dinfo;
finfo = new FileInfo(this.textBoxMyGenAppPath.Text);
if (!finfo.Exists)
{
isValid = false;
message += "\r\n -> The MyGeneration Application Path is Invalid.";
}
dinfo = new DirectoryInfo(this.textBoxCSTFile.Text);
if (!dinfo.Exists)
{
isValid = false;
message += "\r\n -> The CodeSmith Template Folder is Invalid.";
}
dinfo = new DirectoryInfo(this.textBoxCodeSmithPath.Text);
if (!dinfo.Exists)
{
isValid = false;
message += "\r\n -> The CodeSmith Application Path is Invalid.";
}
dinfo = new DirectoryInfo(this.textBoxOutFolder.Text);
if (!dinfo.Exists)
{
try
{
dinfo.Create();
}
catch
{
isValid = false;
message += "\r\n -> The MyGeneration Template Ouput Path is Invalid.";
}
}
if (!isValid)
{
MessageBox.Show(this, message);
}
return isValid;
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// The main entry point for the application.
/// </summary>
private void buttonConvert_Click(object sender, System.EventArgs e)
{
ConvertTemplates();
}
private void WriteToTextBox(string text)
{
this.textBoxConsole.Text = this.textBoxConsole.Text + text + Environment.NewLine;
this.textBoxConsole.SelectionStart = this.textBoxConsole.Text.Length;
this.textBoxConsole.ScrollToCaret();
this.textBoxConsole.Invalidate();
this.textBoxConsole.Refresh();
}
private void ConvertTemplates()
{
if (IsFormValid)
{
Cursor.Current = Cursors.WaitCursor;
string filename, tmp;
ArrayList templates = new ArrayList();
foreach (string file in this.checkedListBoxTemplates.CheckedItems)
{
StreamWriter writer = null;
try
{
CstParser parser = new CstParser(this);
CstTemplate template = parser.Parse(this.textBoxCSTFile.Text + "\\" + file);
LanguageHelper h = LanguageHelper.CreateInstance(template.Language);
tmp = h.BuildTemplate(template, this);
filename = this.textBoxOutFolder.Text + "\\" + file.Substring(0, file.LastIndexOf(".")) + ".zeus";
writer = File.CreateText(filename);
writer.Write(tmp);
writer.Flush();
writer.Close();
writer = null;
templates.Add(filename);
}
catch (Exception ex)
{
if (writer != null)
{
writer.Close();
writer = null;
}
this.AddEntry(ex);
}
}
if (templates.Count > 0)
{
string fileList = string.Empty;
foreach (string fname in templates)
{
if (fileList.Length > 0)
fileList += " ";
fileList += "\"" + fname + "\"";
}
if (this.checkBoxLaunch.Checked)
{
try
{
FileInfo finfo = new FileInfo(textBoxMyGenAppPath.Text);
ProcessStartInfo info = new ProcessStartInfo(finfo.FullName, fileList);
info.WorkingDirectory = finfo.DirectoryName;
System.Diagnostics.Process.Start(info);
}
catch {}
}
}
Cursor.Current = Cursors.Default;
}
}
private void buttonExit_Click(object sender, System.EventArgs e)
{
this.Close();
Application.Exit();
}
private void buttonMyGenAppPath_Click(object sender, System.EventArgs e)
{
PickFile(this.textBoxMyGenAppPath);
}
private void buttonOutPath_Click(object sender, System.EventArgs e)
{
PickPath(this.textBoxOutFolder);
}
private void buttonCodeSmithPath_Click(object sender, System.EventArgs e)
{
PickPath(this.textBoxCodeSmithPath);
}
private void buttonCSTPath_Click(object sender, System.EventArgs e)
{
PickPath(this.textBoxCSTFile);
this.textBoxCSTFile_Leave(sender, e);
}
private void buttonSaveLog_Click(object sender, System.EventArgs e)
{
this.saveFileDialog.RestoreDirectory = true;
this.saveFileDialog.FileName = "log.txt";
DialogResult r = this.saveFileDialog.ShowDialog(this);
if (r == DialogResult.OK)
{
StreamWriter writer = null;
try
{
writer = File.CreateText(saveFileDialog.FileName);
writer.Write(textBoxConsole.Text);
writer.Flush();
writer.Close();
writer = null;
}
catch (Exception ex)
{
if (writer != null)
{
writer.Close();
writer = null;
}
throw ex;
}
}
}
private void textBoxCSTFile_Leave(object sender, System.EventArgs e)
{
DirectoryInfo d = new DirectoryInfo(textBoxCSTFile.Text);
if (d.Exists)
{
this.checkedListBoxTemplates.Items.Clear();
foreach (FileInfo file in d.GetFiles())
{
if (file.Extension == ".cst")
this.checkedListBoxTemplates.Items.Add(file.Name);
}
}
}
private void PickPath(TextBox txt)
{
if (txt.Text != string.Empty)
{
this.folderBrowserDialog.SelectedPath = txt.Text;
}
DialogResult r = this.folderBrowserDialog.ShowDialog(this);
if (r == DialogResult.OK)
{
txt.Text = this.folderBrowserDialog.SelectedPath;
}
}
private void PickFile(TextBox txt)
{
this.openFileDialog.RestoreDirectory = true;
if (txt.Text != string.Empty)
{
this.openFileDialog.FileName = txt.Text;
}
DialogResult r = this.openFileDialog.ShowDialog(this);
if (r == DialogResult.OK)
{
txt.Text = this.openFileDialog.FileName;
}
}
private void LaunchProcess(string url)
{
try
{
System.Diagnostics.Process.Start( url );
}
catch {}
}
#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()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(FormConvertCodeSmith));
this.buttonConvert = new System.Windows.Forms.Button();
this.textBoxConsole = new System.Windows.Forms.TextBox();
this.textBoxCodeSmithPath = new System.Windows.Forms.TextBox();
this.textBoxCSTFile = new System.Windows.Forms.TextBox();
this.labelCodeSmithPath = new System.Windows.Forms.Label();
this.labelCSTFile = new System.Windows.Forms.Label();
this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
this.buttonCodeSmithPath = new System.Windows.Forms.Button();
this.buttonCSTPath = new System.Windows.Forms.Button();
this.checkedListBoxTemplates = new System.Windows.Forms.CheckedListBox();
this.labelTemplates = new System.Windows.Forms.Label();
this.buttonOutPath = new System.Windows.Forms.Button();
this.labelOutFolder = new System.Windows.Forms.Label();
this.textBoxOutFolder = new System.Windows.Forms.TextBox();
this.groupBoxCodeSmith = new System.Windows.Forms.GroupBox();
this.groupBoxMyGen = new System.Windows.Forms.GroupBox();
this.buttonMyGenAppPath = new System.Windows.Forms.Button();
this.textBoxMyGenAppPath = new System.Windows.Forms.TextBox();
this.labelMyGenAppPath = new System.Windows.Forms.Label();
this.checkBoxLaunch = new System.Windows.Forms.CheckBox();
this.mainMenuConverter = new System.Windows.Forms.MainMenu();
this.menuItemFile = new System.Windows.Forms.MenuItem();
this.menuItemConvert = new System.Windows.Forms.MenuItem();
this.menuItemFileSep01 = new System.Windows.Forms.MenuItem();
this.menuItemExit = new System.Windows.Forms.MenuItem();
this.menuItemHelp = new System.Windows.Forms.MenuItem();
this.menuItemAbout = new System.Windows.Forms.MenuItem();
this.labelConversionLog = new System.Windows.Forms.Label();
this.buttonExit = new System.Windows.Forms.Button();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.buttonSaveLog = new System.Windows.Forms.Button();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.groupBoxCodeSmith.SuspendLayout();
this.groupBoxMyGen.SuspendLayout();
this.SuspendLayout();
//
// buttonConvert
//
this.buttonConvert.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonConvert.Location = new System.Drawing.Point(248, 536);
this.buttonConvert.Name = "buttonConvert";
this.buttonConvert.Size = new System.Drawing.Size(64, 23);
this.buttonConvert.TabIndex = 19;
this.buttonConvert.Text = "&Convert";
this.buttonConvert.Click += new System.EventHandler(this.buttonConvert_Click);
//
// textBoxConsole
//
this.textBoxConsole.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxConsole.BackColor = System.Drawing.Color.Black;
this.textBoxConsole.Enabled = false;
this.textBoxConsole.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(192)), ((System.Byte)(0)));
this.textBoxConsole.Location = new System.Drawing.Point(8, 384);
this.textBoxConsole.MaxLength = 999999;
this.textBoxConsole.Multiline = true;
this.textBoxConsole.Name = "textBoxConsole";
this.textBoxConsole.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBoxConsole.Size = new System.Drawing.Size(376, 144);
this.textBoxConsole.TabIndex = 18;
this.textBoxConsole.Text = "";
this.textBoxConsole.WordWrap = false;
//
// textBoxCodeSmithPath
//
this.textBoxCodeSmithPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxCodeSmithPath.Location = new System.Drawing.Point(16, 40);
this.textBoxCodeSmithPath.Name = "textBoxCodeSmithPath";
this.textBoxCodeSmithPath.Size = new System.Drawing.Size(320, 20);
this.textBoxCodeSmithPath.TabIndex = 10;
this.textBoxCodeSmithPath.Text = "C:\\Program Files\\CodeSmith";
//
// textBoxCSTFile
//
this.textBoxCSTFile.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxCSTFile.Location = new System.Drawing.Point(16, 80);
this.textBoxCSTFile.Name = "textBoxCSTFile";
this.textBoxCSTFile.Size = new System.Drawing.Size(320, 20);
this.textBoxCSTFile.TabIndex = 13;
this.textBoxCSTFile.Text = "C:\\Program Files\\CodeSmith\\Samples\\Collections";
this.textBoxCSTFile.Leave += new System.EventHandler(this.textBoxCSTFile_Leave);
//
// labelCodeSmithPath
//
this.labelCodeSmithPath.ForeColor = System.Drawing.Color.Black;
this.labelCodeSmithPath.Location = new System.Drawing.Point(16, 24);
this.labelCodeSmithPath.Name = "labelCodeSmithPath";
this.labelCodeSmithPath.Size = new System.Drawing.Size(184, 16);
this.labelCodeSmithPath.TabIndex = 9;
this.labelCodeSmithPath.Text = "Application Path:";
this.labelCodeSmithPath.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
//
// labelCSTFile
//
this.labelCSTFile.ForeColor = System.Drawing.Color.Black;
this.labelCSTFile.Location = new System.Drawing.Point(16, 64);
this.labelCSTFile.Name = "labelCSTFile";
this.labelCSTFile.Size = new System.Drawing.Size(208, 16);
this.labelCSTFile.TabIndex = 12;
this.labelCSTFile.Text = "CTS Templates File Path:";
this.labelCSTFile.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
//
// buttonCodeSmithPath
//
this.buttonCodeSmithPath.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCodeSmithPath.ForeColor = System.Drawing.Color.Black;
this.buttonCodeSmithPath.Location = new System.Drawing.Point(336, 40);
this.buttonCodeSmithPath.Name = "buttonCodeSmithPath";
this.buttonCodeSmithPath.Size = new System.Drawing.Size(24, 23);
this.buttonCodeSmithPath.TabIndex = 11;
this.buttonCodeSmithPath.Text = "...";
this.buttonCodeSmithPath.Click += new System.EventHandler(this.buttonCodeSmithPath_Click);
//
// buttonCSTPath
//
this.buttonCSTPath.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCSTPath.ForeColor = System.Drawing.Color.Black;
this.buttonCSTPath.Location = new System.Drawing.Point(336, 80);
this.buttonCSTPath.Name = "buttonCSTPath";
this.buttonCSTPath.Size = new System.Drawing.Size(24, 23);
this.buttonCSTPath.TabIndex = 14;
this.buttonCSTPath.Text = "...";
this.buttonCSTPath.Click += new System.EventHandler(this.buttonCSTPath_Click);
//
// checkedListBoxTemplates
//
this.checkedListBoxTemplates.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.checkedListBoxTemplates.Location = new System.Drawing.Point(16, 120);
this.checkedListBoxTemplates.Name = "checkedListBoxTemplates";
this.checkedListBoxTemplates.Size = new System.Drawing.Size(344, 79);
this.checkedListBoxTemplates.TabIndex = 16;
//
// labelTemplates
//
this.labelTemplates.ForeColor = System.Drawing.Color.Black;
this.labelTemplates.Location = new System.Drawing.Point(16, 104);
this.labelTemplates.Name = "labelTemplates";
this.labelTemplates.Size = new System.Drawing.Size(128, 16);
this.labelTemplates.TabIndex = 15;
this.labelTemplates.Text = "CodeSmith Templates:";
this.labelTemplates.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
//
// buttonOutPath
//
this.buttonOutPath.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonOutPath.ForeColor = System.Drawing.Color.Black;
this.buttonOutPath.Location = new System.Drawing.Point(336, 40);
this.buttonOutPath.Name = "buttonOutPath";
this.buttonOutPath.Size = new System.Drawing.Size(24, 23);
this.buttonOutPath.TabIndex = 3;
this.buttonOutPath.Text = "...";
this.buttonOutPath.Click += new System.EventHandler(this.buttonOutPath_Click);
//
// labelOutFolder
//
this.labelOutFolder.ForeColor = System.Drawing.Color.Black;
this.labelOutFolder.Location = new System.Drawing.Point(16, 24);
this.labelOutFolder.Name = "labelOutFolder";
this.labelOutFolder.Size = new System.Drawing.Size(288, 16);
this.labelOutFolder.TabIndex = 1;
this.labelOutFolder.Text = "Generated Output Folder Path:";
this.labelOutFolder.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
//
// textBoxOutFolder
//
this.textBoxOutFolder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxOutFolder.Location = new System.Drawing.Point(16, 40);
this.textBoxOutFolder.Name = "textBoxOutFolder";
this.textBoxOutFolder.Size = new System.Drawing.Size(320, 20);
this.textBoxOutFolder.TabIndex = 2;
this.textBoxOutFolder.Text = "C:\\Program Files\\MyGeneration\\Templates\\CodeSmith";
//
// groupBoxCodeSmith
//
this.groupBoxCodeSmith.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBoxCodeSmith.Controls.Add(this.textBoxCSTFile);
this.groupBoxCodeSmith.Controls.Add(this.textBoxCodeSmithPath);
this.groupBoxCodeSmith.Controls.Add(this.labelTemplates);
this.groupBoxCodeSmith.Controls.Add(this.checkedListBoxTemplates);
this.groupBoxCodeSmith.Controls.Add(this.buttonCSTPath);
this.groupBoxCodeSmith.Controls.Add(this.buttonCodeSmithPath);
this.groupBoxCodeSmith.Controls.Add(this.labelCSTFile);
this.groupBoxCodeSmith.Controls.Add(this.labelCodeSmithPath);
this.groupBoxCodeSmith.ForeColor = System.Drawing.Color.Blue;
this.groupBoxCodeSmith.Location = new System.Drawing.Point(8, 152);
this.groupBoxCodeSmith.Name = "groupBoxCodeSmith";
this.groupBoxCodeSmith.Size = new System.Drawing.Size(376, 208);
this.groupBoxCodeSmith.TabIndex = 8;
this.groupBoxCodeSmith.TabStop = false;
this.groupBoxCodeSmith.Text = "CodeSmith Settings";
//
// groupBoxMyGen
//
this.groupBoxMyGen.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBoxMyGen.Controls.Add(this.buttonMyGenAppPath);
this.groupBoxMyGen.Controls.Add(this.textBoxMyGenAppPath);
this.groupBoxMyGen.Controls.Add(this.labelMyGenAppPath);
this.groupBoxMyGen.Controls.Add(this.checkBoxLaunch);
this.groupBoxMyGen.Controls.Add(this.textBoxOutFolder);
this.groupBoxMyGen.Controls.Add(this.labelOutFolder);
this.groupBoxMyGen.Controls.Add(this.buttonOutPath);
this.groupBoxMyGen.ForeColor = System.Drawing.Color.Blue;
this.groupBoxMyGen.Location = new System.Drawing.Point(8, 8);
this.groupBoxMyGen.Name = "groupBoxMyGen";
this.groupBoxMyGen.Size = new System.Drawing.Size(376, 136);
this.groupBoxMyGen.TabIndex = 0;
this.groupBoxMyGen.TabStop = false;
this.groupBoxMyGen.Text = "MyGeneration Settings";
//
// buttonMyGenAppPath
//
this.buttonMyGenAppPath.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonMyGenAppPath.ForeColor = System.Drawing.Color.Black;
this.buttonMyGenAppPath.Location = new System.Drawing.Point(336, 80);
this.buttonMyGenAppPath.Name = "buttonMyGenAppPath";
this.buttonMyGenAppPath.Size = new System.Drawing.Size(24, 23);
this.buttonMyGenAppPath.TabIndex = 6;
this.buttonMyGenAppPath.Text = "...";
this.buttonMyGenAppPath.Click += new System.EventHandler(this.buttonMyGenAppPath_Click);
//
// textBoxMyGenAppPath
//
this.textBoxMyGenAppPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxMyGenAppPath.Location = new System.Drawing.Point(16, 80);
this.textBoxMyGenAppPath.Name = "textBoxMyGenAppPath";
this.textBoxMyGenAppPath.Size = new System.Drawing.Size(320, 20);
this.textBoxMyGenAppPath.TabIndex = 5;
this.textBoxMyGenAppPath.Text = "C:\\Program Files\\MyGeneration\\MyGeneration.exe";
//
// labelMyGenAppPath
//
this.labelMyGenAppPath.ForeColor = System.Drawing.Color.Black;
this.labelMyGenAppPath.Location = new System.Drawing.Point(16, 64);
this.labelMyGenAppPath.Name = "labelMyGenAppPath";
this.labelMyGenAppPath.Size = new System.Drawing.Size(288, 16);
this.labelMyGenAppPath.TabIndex = 4;
this.labelMyGenAppPath.Text = "MyGeneration Application Path";
this.labelMyGenAppPath.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
//
// checkBoxLaunch
//
this.checkBoxLaunch.Checked = true;
this.checkBoxLaunch.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxLaunch.ForeColor = System.Drawing.Color.Black;
this.checkBoxLaunch.Location = new System.Drawing.Point(16, 112);
this.checkBoxLaunch.Name = "checkBoxLaunch";
this.checkBoxLaunch.Size = new System.Drawing.Size(376, 16);
this.checkBoxLaunch.TabIndex = 7;
this.checkBoxLaunch.Text = "Launch Templates After Conversion?";
//
// mainMenuConverter
//
this.mainMenuConverter.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemFile,
this.menuItemHelp});
//
// menuItemFile
//
this.menuItemFile.Index = 0;
this.menuItemFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemConvert,
this.menuItemFileSep01,
this.menuItemExit});
this.menuItemFile.Text = "&File";
//
// menuItemConvert
//
this.menuItemConvert.Index = 0;
this.menuItemConvert.Text = "&Convert";
this.menuItemConvert.Click += new System.EventHandler(this.menuItemConvert_Click);
//
// menuItemFileSep01
//
this.menuItemFileSep01.Index = 1;
this.menuItemFileSep01.Text = "-";
//
// menuItemExit
//
this.menuItemExit.Index = 2;
this.menuItemExit.Text = "E&xit";
this.menuItemExit.Click += new System.EventHandler(this.menuItemExit_Click);
//
// menuItemHelp
//
this.menuItemHelp.Index = 1;
this.menuItemHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemAbout});
this.menuItemHelp.Text = "&Help";
//
// menuItemAbout
//
this.menuItemAbout.Index = 0;
this.menuItemAbout.Text = "&About";
this.menuItemAbout.Click += new System.EventHandler(this.menuItemAbout_Click);
//
// labelConversionLog
//
this.labelConversionLog.Location = new System.Drawing.Point(8, 368);
this.labelConversionLog.Name = "labelConversionLog";
this.labelConversionLog.Size = new System.Drawing.Size(100, 16);
this.labelConversionLog.TabIndex = 17;
this.labelConversionLog.Text = "Conversion Log:";
//
// buttonExit
//
this.buttonExit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonExit.Location = new System.Drawing.Point(320, 536);
this.buttonExit.Name = "buttonExit";
this.buttonExit.Size = new System.Drawing.Size(64, 23);
this.buttonExit.TabIndex = 20;
this.buttonExit.Text = "E&xit";
this.buttonExit.Click += new System.EventHandler(this.buttonExit_Click);
//
// buttonSaveLog
//
this.buttonSaveLog.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonSaveLog.Location = new System.Drawing.Point(8, 536);
this.buttonSaveLog.Name = "buttonSaveLog";
this.buttonSaveLog.Size = new System.Drawing.Size(72, 23);
this.buttonSaveLog.TabIndex = 21;
this.buttonSaveLog.Text = "&Save Log";
this.buttonSaveLog.Click += new System.EventHandler(this.buttonSaveLog_Click);
//
// FormConvertCodeSmith
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(392, 561);
this.Controls.Add(this.buttonSaveLog);
this.Controls.Add(this.buttonExit);
this.Controls.Add(this.labelConversionLog);
this.Controls.Add(this.groupBoxMyGen);
this.Controls.Add(this.groupBoxCodeSmith);
this.Controls.Add(this.buttonConvert);
this.Controls.Add(this.textBoxConsole);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Menu = this.mainMenuConverter;
this.Name = "FormConvertCodeSmith";
this.Text = "CodeSmith-2-MyGeneration Converter";
this.Load += new System.EventHandler(this.FormConvertCodeSmith_Load);
this.Closed += new System.EventHandler(this.FormConvertCodeSmith_Closed);
this.groupBoxCodeSmith.ResumeLayout(false);
this.groupBoxMyGen.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
#region Menu Event Handlers
private void menuItemExit_Click(object sender, System.EventArgs e)
{
this.Close();
Application.Exit();
}
private void menuItemAbout_Click(object sender, System.EventArgs e)
{
FormAbout about = new FormAbout();
about.ShowDialog(this);
}
private void menuItemConvert_Click(object sender, System.EventArgs e)
{
ConvertTemplates();
}
#endregion
#region ILog Members
public void AddEntry(Exception ex)
{
AddEntry("EXCEPTION [{0}] - Message=\"{1}\" Source=\"{2}\" StackTrace=\"{3}\" ",
ex.GetType().Name, ex.Message, ex.Source, ex.StackTrace);
}
public void AddEntry(string message, params object[] args)
{
string item;
if (args.Length > 0)
item = DateTime.Now.ToString() + " - " + string.Format(message, args);
else
item = DateTime.Now.ToString() + " - " + message;
WriteToTextBox(item);
}
#endregion
}
}
| |
using System;
namespace MetroHash
{
public partial class MetroHash
{
//---------------------------------------------------------------------------//
private const ulong K0_64_1 = 0xC83A91E1;
private const ulong K1_64_1 = 0x8648DBDB;
private const ulong K2_64_1 = 0x7BDEC03B;
private const ulong K3_64_1 = 0x2F5870A5;
//---------------------------------------------------------------------------//
public static void Hash64_1(byte[] lKey, uint lStartOffset, uint lLength, uint lSeed, out ulong lHash)
{
uint lKeyIndex = lStartOffset;
uint lKeyEnd = lKeyIndex + lLength;
if (lKey.Length < lKeyEnd)
{
throw new IndexOutOfRangeException("Given Key for hashing is not of expected length");
}
unsafe
{
fixed (byte* ptr = lKey)
{
Hash64_1(ptr, lStartOffset, lLength, lSeed, out lHash);
//lOutput = BitConverter.GetBytes(lHash);
}
}
}
public static unsafe void Hash64_1(byte* lKey, uint lStartOffset, uint lLength, uint lSeed, out ulong lHash)
{
uint lKeyIndex = lStartOffset;
uint lKeyEnd = lKeyIndex + lLength;
lHash = ((lSeed + K2_64_1) * K0_64_1) + lLength;
if (lLength >= 32)
{
ulong[] lV = { lHash, lHash, lHash, lHash };
do
{
lV[0] += (*(ulong *)(lKey + lKeyIndex)) * K0_64_1; lKeyIndex += 8; lV[0] = RotateRight(lV[0],29) + lV[2];
lV[1] += (*(ulong *)(lKey + lKeyIndex)) * K1_64_1; lKeyIndex += 8; lV[1] = RotateRight(lV[1],29) + lV[3];
lV[2] += (*(ulong *)(lKey + lKeyIndex)) * K2_64_1; lKeyIndex += 8; lV[2] = RotateRight(lV[2],29) + lV[0];
lV[3] += (*(ulong *)(lKey + lKeyIndex)) * K3_64_1; lKeyIndex += 8; lV[3] = RotateRight(lV[3],29) + lV[1];
}
while (lKeyIndex <= (lKeyEnd - 32));
lV[2] ^= RotateRight(((lV[0] + lV[3]) * K0_64_1) + lV[1], 33) * K1_64_1;
lV[3] ^= RotateRight(((lV[1] + lV[2]) * K1_64_1) + lV[0], 33) * K0_64_1;
lV[0] ^= RotateRight(((lV[0] + lV[2]) * K0_64_1) + lV[3], 33) * K1_64_1;
lV[1] ^= RotateRight(((lV[1] + lV[3]) * K1_64_1) + lV[2], 33) * K0_64_1;
lHash += lV[0] ^ lV[1];
}
if ((lKeyEnd - lKeyIndex) >= 16)
{
ulong lV0 = lHash + ((*(UInt64 *)(lKey + lKeyIndex)) * K0_64_1); lKeyIndex += 8; lV0 = RotateRight(lV0,33) * K1_64_1;
ulong lV1 = lHash + ((*(UInt64 *)(lKey + lKeyIndex)) * K1_64_1); lKeyIndex += 8; lV1 = RotateRight(lV1,33) * K2_64_1;
lV0 ^= RotateRight(lV0 * K0_64_1, 35) + lV1;
lV1 ^= RotateRight(lV1 * K3_64_1, 35) + lV0;
lHash += lV1;
}
if ((lKeyEnd - lKeyIndex) >= 8)
{
lHash += (*(UInt64 *)(lKey + lKeyIndex)) * K3_64_1; lKeyIndex += 8;
lHash ^= RotateRight(lHash, 33) * K1_64_1;
}
if ((lKeyEnd - lKeyIndex) >= 4)
{
lHash += (*(UInt32*)(lKey + lKeyIndex)) * K3_64_1; lKeyIndex += 4;
lHash ^= RotateRight(lHash, 15) * K1_64_1;
}
if ((lKeyEnd - lKeyIndex) >= 2)
{
lHash += (*(UInt16*)(lKey + lKeyIndex)) * K3_64_1; lKeyIndex += 2;
lHash ^= RotateRight(lHash, 13) * K1_64_1;
}
if ((lKeyEnd - lKeyIndex) >= 1)
{
lHash += (*(byte*)(lKey + lKeyIndex)) * K3_64_1;
lHash ^= RotateRight(lHash, 25) * K1_64_1;
}
lHash ^= RotateRight(lHash, 33);
lHash *= K0_64_1;
lHash ^= RotateRight(lHash, 33);
}
//---------------------------------------------------------------------------//
private const ulong K0_64_2 = 0xD6D018F5;
private const ulong K1_64_2 = 0xA2AA033B;
private const ulong K2_64_2 = 0x62992FC1;
private const ulong K3_64_2 = 0x30BC5B29;
//---------------------------------------------------------------------------//
public static void Hash64_2(byte[] lKey, uint lStartOffset, uint lLength, uint lSeed, out byte[] lOutput)
{
uint lKeyIndex = lStartOffset;
uint lKeyEnd = lKeyIndex + lLength;
if (lKey.Length < lKeyEnd)
{
throw new IndexOutOfRangeException("Given Key for hashing is not of expected length");
}
ulong lHash = ((lSeed + K2_64_2) * K0_64_2) + lLength;
if (lLength >= 32)
{
ulong[] lV = { lHash, lHash, lHash, lHash };
do
{
lV[0] += Read_u64(lKey, lKeyIndex) * K0_64_2; lKeyIndex += 8; lV[0] = RotateRight(lV[0],29) + lV[2];
lV[1] += Read_u64(lKey, lKeyIndex) * K1_64_2; lKeyIndex += 8; lV[1] = RotateRight(lV[1],29) + lV[3];
lV[2] += Read_u64(lKey, lKeyIndex) * K2_64_2; lKeyIndex += 8; lV[2] = RotateRight(lV[2],29) + lV[0];
lV[3] += Read_u64(lKey, lKeyIndex) * K3_64_2; lKeyIndex += 8; lV[3] = RotateRight(lV[3],29) + lV[1];
}
while (lKeyIndex <= (lKeyEnd - 32));
lV[2] ^= RotateRight(((lV[0] + lV[3]) * K0_64_2) + lV[1], 30) * K1_64_2;
lV[3] ^= RotateRight(((lV[1] + lV[2]) * K1_64_2) + lV[0], 30) * K0_64_2;
lV[0] ^= RotateRight(((lV[0] + lV[2]) * K0_64_2) + lV[3], 30) * K1_64_2;
lV[1] ^= RotateRight(((lV[1] + lV[3]) * K1_64_2) + lV[2], 30) * K0_64_2;
lHash += lV[0] ^ lV[1];
}
if ((lKeyEnd - lKeyIndex) >= 16)
{
ulong lV0 = lHash + (Read_u64(lKey, lKeyIndex) * K2_64_2); lKeyIndex += 8; lV0 = RotateRight(lV0, 29) * K3_64_2;
ulong lV1 = lHash + (Read_u64(lKey, lKeyIndex) * K2_64_2); lKeyIndex += 8; lV1 = RotateRight(lV1, 29) * K3_64_2;
lV0 ^= RotateRight(lV0 * K0_64_2, 34) + lV1;
lV1 ^= RotateRight(lV1 * K3_64_2, 34) + lV0;
lHash += lV1;
}
if ((lKeyEnd - lKeyIndex) >= 8)
{
lHash += Read_u64(lKey, lKeyIndex) * K3_64_2; lKeyIndex += 8;
lHash ^= RotateRight(lHash, 36) * K1_64_2;
}
if ((lKeyEnd - lKeyIndex) >= 4)
{
lHash += Read_u32(lKey, lKeyIndex) * K3_64_2; lKeyIndex += 4;
lHash ^= RotateRight(lHash, 15) * K1_64_2;
}
if ((lKeyEnd - lKeyIndex) >= 2)
{
lHash += Read_u16(lKey, lKeyIndex) * K3_64_2; lKeyIndex += 2;
lHash ^= RotateRight(lHash, 15) * K1_64_2;
}
if ((lKeyEnd - lKeyIndex) >= 1)
{
lHash += Read_u8(lKey, lKeyIndex) * K3_64_2;
lHash ^= RotateRight(lHash, 23) * K1_64_2;
}
lHash ^= RotateRight(lHash, 28);
lHash *= K0_64_2;
lHash ^= RotateRight(lHash, 29);
lOutput = BitConverter.GetBytes(lHash);
}
//---------------------------------------------------------------------------//
/* rotate right idiom recognized by compiler*/
private static ulong RotateRight(ulong lV, uint lK)
{
int lSignedK = (int)lK;
return (lV >> lSignedK) | (lV << (64 - lSignedK));
}
//---------------------------------------------------------------------------//
// unaligned reads, fast and safe on Nehalem and later microarchitectures
private static ulong Read_u64(byte[] lData, uint lOffset)
{
return BitConverter.ToUInt64(lData, (int)lOffset);
}
//---------------------------------------------------------------------------//
private static ulong Read_u32(byte[] lData, uint lOffset)
{
return BitConverter.ToUInt32(lData, (int)lOffset);
}
//---------------------------------------------------------------------------//
private static ulong Read_u16(byte[] lData, uint lOffset)
{
return BitConverter.ToUInt16(lData, (int)lOffset);
}
//---------------------------------------------------------------------------//
private static ulong Read_u8(byte[] lData, uint lOffset)
{
return lData[lOffset];
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PhotonHandler.cs" company="Exit Games GmbH">
// Part of: Photon Unity Networking
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Diagnostics;
using ExitGames.Client.Photon;
using UnityEngine;
using Debug = UnityEngine.Debug;
using Hashtable = ExitGames.Client.Photon.Hashtable;
using SupportClassPun = ExitGames.Client.Photon.SupportClass;
#if UNITY_5_5_OR_NEWER
using UnityEngine.Profiling;
#endif
/// <summary>
/// Internal Monobehaviour that allows Photon to run an Update loop.
/// </summary>
internal class PhotonHandler : MonoBehaviour
{
public static PhotonHandler SP;
public int updateInterval; // time [ms] between consecutive SendOutgoingCommands calls
public int updateIntervalOnSerialize; // time [ms] between consecutive RunViewUpdate calls (sending syncs, etc)
private int nextSendTickCount = 0;
private int nextSendTickCountOnSerialize = 0;
private static bool sendThreadShouldRun;
private static Stopwatch timerToStopConnectionInBackground;
protected internal static bool AppQuits;
protected internal static Type PingImplementation = null;
protected void Awake()
{
if (SP != null && SP != this && SP.gameObject != null)
{
GameObject.DestroyImmediate(SP.gameObject);
}
SP = this;
DontDestroyOnLoad(this.gameObject);
this.updateInterval = 1000 / PhotonNetwork.sendRate;
this.updateIntervalOnSerialize = 1000 / PhotonNetwork.sendRateOnSerialize;
PhotonHandler.StartFallbackSendAckThread();
}
#if UNITY_5_4_OR_NEWER
protected void Start()
{
UnityEngine.SceneManagement.SceneManager.sceneLoaded += (scene, loadingMode) =>
{
PhotonNetwork.networkingPeer.NewSceneLoaded();
PhotonNetwork.networkingPeer.SetLevelInPropsIfSynced(SceneManagerHelper.ActiveSceneName);
};
}
#else
/// <summary>Called by Unity after a new level was loaded.</summary>
protected void OnLevelWasLoaded(int level)
{
PhotonNetwork.networkingPeer.NewSceneLoaded();
PhotonNetwork.networkingPeer.SetLevelInPropsIfSynced(SceneManagerHelper.ActiveSceneName);
}
#endif
/// <summary>Called by Unity when the application is closed. Disconnects.</summary>
protected void OnApplicationQuit()
{
PhotonHandler.AppQuits = true;
PhotonHandler.StopFallbackSendAckThread();
PhotonNetwork.Disconnect();
}
/// <summary>
/// Called by Unity when the application gets paused (e.g. on Android when in background).
/// </summary>
/// <remarks>
/// Sets a disconnect timer when PhotonNetwork.BackgroundTimeout > 0.1f. See PhotonNetwork.BackgroundTimeout.
///
/// Some versions of Unity will give false values for pause on Android (and possibly on other platforms).
/// </remarks>
/// <param name="pause">If the app pauses.</param>
protected void OnApplicationPause(bool pause)
{
if (PhotonNetwork.BackgroundTimeout > 0.1f)
{
if (timerToStopConnectionInBackground == null)
{
timerToStopConnectionInBackground = new Stopwatch();
}
timerToStopConnectionInBackground.Reset();
if (pause)
{
timerToStopConnectionInBackground.Start();
}
else
{
timerToStopConnectionInBackground.Stop();
}
}
}
/// <summary>Called by Unity when the play mode ends. Used to cleanup.</summary>
protected void OnDestroy()
{
//Debug.Log("OnDestroy on PhotonHandler.");
PhotonHandler.StopFallbackSendAckThread();
//PhotonNetwork.Disconnect();
}
protected void Update()
{
if (PhotonNetwork.networkingPeer == null)
{
Debug.LogError("NetworkPeer broke!");
return;
}
if (PhotonNetwork.connectionStateDetailed == ClientState.PeerCreated || PhotonNetwork.connectionStateDetailed == ClientState.Disconnected || PhotonNetwork.offlineMode)
{
return;
}
// the messageQueue might be paused. in that case a thread will send acknowledgements only. nothing else to do here.
if (!PhotonNetwork.isMessageQueueRunning)
{
return;
}
bool doDispatch = true;
while (PhotonNetwork.isMessageQueueRunning && doDispatch)
{
// DispatchIncomingCommands() returns true of it found any command to dispatch (event, result or state change)
Profiler.BeginSample("DispatchIncomingCommands");
doDispatch = PhotonNetwork.networkingPeer.DispatchIncomingCommands();
Profiler.EndSample();
}
int currentMsSinceStart = (int)(Time.realtimeSinceStartup * 1000); // avoiding Environment.TickCount, which could be negative on long-running platforms
if (PhotonNetwork.isMessageQueueRunning && currentMsSinceStart > this.nextSendTickCountOnSerialize)
{
PhotonNetwork.networkingPeer.RunViewUpdate();
this.nextSendTickCountOnSerialize = currentMsSinceStart + this.updateIntervalOnSerialize;
this.nextSendTickCount = 0; // immediately send when synchronization code was running
}
currentMsSinceStart = (int)(Time.realtimeSinceStartup * 1000);
if (currentMsSinceStart > this.nextSendTickCount)
{
bool doSend = true;
while (PhotonNetwork.isMessageQueueRunning && doSend)
{
// Send all outgoing commands
Profiler.BeginSample("SendOutgoingCommands");
doSend = PhotonNetwork.networkingPeer.SendOutgoingCommands();
Profiler.EndSample();
}
this.nextSendTickCount = currentMsSinceStart + this.updateInterval;
}
}
protected void OnJoinedRoom()
{
PhotonNetwork.networkingPeer.LoadLevelIfSynced();
}
protected void OnCreatedRoom()
{
PhotonNetwork.networkingPeer.SetLevelInPropsIfSynced(SceneManagerHelper.ActiveSceneName);
}
public static void StartFallbackSendAckThread()
{
#if !UNITY_WEBGL
if (sendThreadShouldRun)
{
return;
}
sendThreadShouldRun = true;
SupportClassPun.StartBackgroundCalls(FallbackSendAckThread); // thread will call this every 100ms until method returns false
#endif
}
public static void StopFallbackSendAckThread()
{
#if !UNITY_WEBGL
sendThreadShouldRun = false;
#endif
}
/// <summary>A thread which runs independent from the Update() calls. Keeps connections online while loading or in background. See PhotonNetwork.BackgroundTimeout.</summary>
public static bool FallbackSendAckThread()
{
if (sendThreadShouldRun && !PhotonNetwork.offlineMode && PhotonNetwork.networkingPeer != null)
{
// check if the client should disconnect after some seconds in background
if (timerToStopConnectionInBackground != null && PhotonNetwork.BackgroundTimeout > 0.1f)
{
if (timerToStopConnectionInBackground.ElapsedMilliseconds > PhotonNetwork.BackgroundTimeout * 1000)
{
if (PhotonNetwork.connected)
{
PhotonNetwork.Disconnect();
}
timerToStopConnectionInBackground.Stop();
timerToStopConnectionInBackground.Reset();
return sendThreadShouldRun;
}
}
if (!PhotonNetwork.isMessageQueueRunning || PhotonNetwork.networkingPeer.ConnectionTime - PhotonNetwork.networkingPeer.LastSendOutgoingTime > 200)
{
PhotonNetwork.networkingPeer.SendAcksOnly();
}
}
return sendThreadShouldRun;
}
#region Photon Cloud Ping Evaluation
private const string PlayerPrefsKey = "PUNCloudBestRegion";
internal static CloudRegionCode BestRegionCodeInPreferences
{
get
{
string prefsRegionCode = PlayerPrefs.GetString(PlayerPrefsKey, "");
if (!string.IsNullOrEmpty(prefsRegionCode))
{
CloudRegionCode loadedRegion = Region.Parse(prefsRegionCode);
return loadedRegion;
}
return CloudRegionCode.none;
}
set
{
if (value == CloudRegionCode.none)
{
PlayerPrefs.DeleteKey(PlayerPrefsKey);
}
else
{
PlayerPrefs.SetString(PlayerPrefsKey, value.ToString());
}
}
}
internal protected static void PingAvailableRegionsAndConnectToBest()
{
SP.StartCoroutine(SP.PingAvailableRegionsCoroutine(true));
}
internal IEnumerator PingAvailableRegionsCoroutine(bool connectToBest)
{
while (PhotonNetwork.networkingPeer.AvailableRegions == null)
{
if (PhotonNetwork.connectionStateDetailed != ClientState.ConnectingToNameServer && PhotonNetwork.connectionStateDetailed != ClientState.ConnectedToNameServer)
{
Debug.LogError("Call ConnectToNameServer to ping available regions.");
yield break; // break if we don't connect to the nameserver at all
}
Debug.Log("Waiting for AvailableRegions. State: " + PhotonNetwork.connectionStateDetailed + " Server: " + PhotonNetwork.Server + " PhotonNetwork.networkingPeer.AvailableRegions " + (PhotonNetwork.networkingPeer.AvailableRegions != null));
yield return new WaitForSeconds(0.25f); // wait until pinging finished (offline mode won't ping)
}
if (PhotonNetwork.networkingPeer.AvailableRegions == null || PhotonNetwork.networkingPeer.AvailableRegions.Count == 0)
{
Debug.LogError("No regions available. Are you sure your appid is valid and setup?");
yield break; // break if we don't get regions at all
}
PhotonPingManager pingManager = new PhotonPingManager();
foreach (Region region in PhotonNetwork.networkingPeer.AvailableRegions)
{
SP.StartCoroutine(pingManager.PingSocket(region));
}
while (!pingManager.Done)
{
yield return new WaitForSeconds(0.1f); // wait until pinging finished (offline mode won't ping)
}
Region best = pingManager.BestRegion;
PhotonHandler.BestRegionCodeInPreferences = best.Code;
Debug.Log("Found best region: '" + best.Code + "' ping: " + best.Ping + ". Calling ConnectToRegionMaster() is: " + connectToBest);
if (connectToBest)
{
PhotonNetwork.networkingPeer.ConnectToRegionMaster(best.Code);
}
}
#endregion
}
| |
using Microsoft.IdentityModel;
using SharePointPnP.IdentityModel.Extensions.S2S.Protocols.OAuth2;
using SharePointPnP.IdentityModel.Extensions.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace SharePoint.AccessApp.Scanner.Utilities
{
internal static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registered for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registered for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registered for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate (object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified ClaimsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it. Identity claim type and identity provider name (as registered in SharePoint)
/// should be specified in configuration file e.g.:
/// <appSettings>
/// <add key = "IdentityClaimType" value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" />
/// <add key = "TrustedIdentityTokenIssuerName" value="sso" />
/// </appSettings>
/// To discover trusted identity token issuer name use following cmdlet:
/// Get-SPTrustedIdentityTokenIssuer | select name
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Claims identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithClaimsIdentity(Uri targetApplicationUri, System.Security.Claims.ClaimsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithClaimsIdentity(identity, IdentityClaimType, TrustedIdentityTokenIssuerName) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Hosted app configuration
//
private static string clientId = null;
private static string issuerId = null;
private static string hostedAppHostNameOverride = null;
private static string hostedAppHostName = null;
private static string clientSecret = null;
private static string secondaryClientSecret = null;
private static string realm = null;
private static string serviceNamespace = null;
private static string identityClaimType = null;
private static string trustedIdentityTokenIssuerName = null;
//
// Environment Constants
//
private static string acsHostUrl = "accesscontrol.windows.net";
private static string globalEndPointPrefix = "accounts";
public static string AcsHostUrl
{
get
{
if (String.IsNullOrEmpty(acsHostUrl))
{
return "accesscontrol.windows.net";
}
else
{
return acsHostUrl;
}
}
set
{
acsHostUrl = value;
}
}
public static string GlobalEndPointPrefix
{
get
{
if (globalEndPointPrefix == null)
{
return "accounts";
}
else
{
return globalEndPointPrefix;
}
}
set
{
globalEndPointPrefix = value;
}
}
public static string ClientId
{
get
{
if (String.IsNullOrEmpty(clientId))
{
return string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
}
else
{
return clientId;
}
}
set
{
clientId = value;
}
}
public static string IssuerId
{
get
{
if (String.IsNullOrEmpty(issuerId))
{
return string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
}
else
{
return issuerId;
}
}
set
{
issuerId = value;
}
}
public static string HostedAppHostNameOverride
{
get
{
if (String.IsNullOrEmpty(hostedAppHostNameOverride))
{
return WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
}
else
{
return hostedAppHostNameOverride;
}
}
set
{
hostedAppHostNameOverride = value;
}
}
public static string HostedAppHostName
{
get
{
if (String.IsNullOrEmpty(hostedAppHostName))
{
return WebConfigurationManager.AppSettings.Get("HostedAppHostName");
}
else
{
return hostedAppHostName;
}
}
set
{
hostedAppHostName = value;
}
}
public static string ClientSecret
{
get
{
if (String.IsNullOrEmpty(clientSecret))
{
return string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
}
else
{
return clientSecret;
}
}
set
{
clientSecret = value;
}
}
public static string SecondaryClientSecret
{
get
{
if (String.IsNullOrEmpty(secondaryClientSecret))
{
return WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
}
else
{
return secondaryClientSecret;
}
}
set
{
secondaryClientSecret = value;
}
}
public static string Realm
{
get
{
if (String.IsNullOrEmpty(realm))
{
return WebConfigurationManager.AppSettings.Get("Realm");
}
else
{
return realm;
}
}
set
{
realm = value;
}
}
public static string ServiceNamespace
{
get
{
if (String.IsNullOrEmpty(serviceNamespace))
{
return WebConfigurationManager.AppSettings.Get("Realm");
}
else
{
return serviceNamespace;
}
}
set
{
serviceNamespace = value;
}
}
public static string IdentityClaimType
{
get
{
if (String.IsNullOrEmpty(identityClaimType))
{
return WebConfigurationManager.AppSettings.Get("IdentityClaimType");
}
else
{
return identityClaimType;
}
}
set
{
identityClaimType = value;
}
}
public static string TrustedIdentityTokenIssuerName
{
get
{
if (String.IsNullOrEmpty(trustedIdentityTokenIssuerName))
{
return WebConfigurationManager.AppSettings.Get("TrustedIdentityTokenIssuerName");
}
else
{
return trustedIdentityTokenIssuerName;
}
}
set
{
trustedIdentityTokenIssuerName = value;
}
}
//private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
//private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
//private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
//private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
//private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
//private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
//private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
//private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
if (GlobalEndPointPrefix.Length == 0)
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}/", AcsHostUrl);
}
else
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
}
public static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static JsonWebTokenClaim[] GetClaimsWithClaimsIdentity(System.Security.Claims.ClaimsIdentity identity, string identityClaimType, string trustedProviderName)
{
var identityClaim = identity.Claims.Where(c => string.Equals(c.Type, identityClaimType, StringComparison.InvariantCultureIgnoreCase)).First();
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identityClaim.Value),
new JsonWebTokenClaim("nii", "trusted:" + trustedProviderName)
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.AspNetCore.Components.Test.Helpers;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Microsoft.AspNetCore.Components.Authorization
{
public class CascadingAuthenticationStateTest
{
[Fact]
public void RequiresRegisteredService()
{
// Arrange
var renderer = new TestRenderer();
var component = new AutoRenderFragmentComponent(builder =>
{
builder.OpenComponent<CascadingAuthenticationState>(0);
builder.CloseComponent();
});
// Act/Assert
renderer.AssignRootComponentId(component);
var ex = Assert.Throws<InvalidOperationException>(() => component.TriggerRender());
Assert.Contains($"There is no registered service of type '{typeof(AuthenticationStateProvider).FullName}'.", ex.Message);
}
[Fact]
public void SuppliesSynchronouslyAvailableAuthStateToChildContent()
{
// Arrange: Service
var services = new ServiceCollection();
var authStateProvider = new TestAuthenticationStateProvider()
{
CurrentAuthStateTask = Task.FromResult(CreateAuthenticationState("Bert"))
};
services.AddSingleton<AuthenticationStateProvider>(authStateProvider);
// Arrange: Renderer and component
var renderer = new TestRenderer(services.BuildServiceProvider());
var component = new UseCascadingAuthenticationStateComponent();
// Act
renderer.AssignRootComponentId(component);
component.TriggerRender();
// Assert
var batch = renderer.Batches.Single();
var receiveAuthStateId = batch.GetComponentFrames<ReceiveAuthStateComponent>().Single().ComponentId;
var receiveAuthStateDiff = batch.DiffsByComponentId[receiveAuthStateId].Single();
Assert.Collection(receiveAuthStateDiff.Edits, edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Text(
batch.ReferenceFrames[edit.ReferenceFrameIndex],
"Authenticated: True; Name: Bert; Pending: False; Renders: 1");
});
}
[Fact]
public void SuppliesAsynchronouslyAvailableAuthStateToChildContent()
{
// Arrange: Service
var services = new ServiceCollection();
var authStateTaskCompletionSource = new TaskCompletionSource<AuthenticationState>();
var authStateProvider = new TestAuthenticationStateProvider()
{
CurrentAuthStateTask = authStateTaskCompletionSource.Task
};
services.AddSingleton<AuthenticationStateProvider>(authStateProvider);
// Arrange: Renderer and component
var renderer = new TestRenderer(services.BuildServiceProvider());
var component = new UseCascadingAuthenticationStateComponent();
// Act 1: Initial synchronous render
renderer.AssignRootComponentId(component);
component.TriggerRender();
// Assert 1: Empty state
var batch1 = renderer.Batches.Single();
var receiveAuthStateFrame = batch1.GetComponentFrames<ReceiveAuthStateComponent>().Single();
var receiveAuthStateId = receiveAuthStateFrame.ComponentId;
var receiveAuthStateComponent = (ReceiveAuthStateComponent)receiveAuthStateFrame.Component;
var receiveAuthStateDiff1 = batch1.DiffsByComponentId[receiveAuthStateId].Single();
Assert.Collection(receiveAuthStateDiff1.Edits, edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Text(
batch1.ReferenceFrames[edit.ReferenceFrameIndex],
"Authenticated: False; Name: ; Pending: True; Renders: 1");
});
// Act/Assert 2: Auth state fetch task completes in background
// No new renders yet, because the cascading parameter itself hasn't changed
authStateTaskCompletionSource.SetResult(CreateAuthenticationState("Bert"));
Assert.Single(renderer.Batches);
// Act/Assert 3: Refresh display
receiveAuthStateComponent.TriggerRender();
Assert.Equal(2, renderer.Batches.Count);
var batch2 = renderer.Batches.Last();
var receiveAuthStateDiff2 = batch2.DiffsByComponentId[receiveAuthStateId].Single();
Assert.Collection(receiveAuthStateDiff2.Edits, edit =>
{
Assert.Equal(RenderTreeEditType.UpdateText, edit.Type);
AssertFrame.Text(
batch2.ReferenceFrames[edit.ReferenceFrameIndex],
"Authenticated: True; Name: Bert; Pending: False; Renders: 2");
});
}
[Fact]
public void RespondsToNotificationsFromAuthenticationStateProvider()
{
// Arrange: Service
var services = new ServiceCollection();
var authStateProvider = new TestAuthenticationStateProvider()
{
CurrentAuthStateTask = Task.FromResult(CreateAuthenticationState(null))
};
services.AddSingleton<AuthenticationStateProvider>(authStateProvider);
// Arrange: Renderer and component, initially rendered
var renderer = new TestRenderer(services.BuildServiceProvider());
var component = new UseCascadingAuthenticationStateComponent();
renderer.AssignRootComponentId(component);
component.TriggerRender();
var receiveAuthStateId = renderer.Batches.Single()
.GetComponentFrames<ReceiveAuthStateComponent>().Single().ComponentId;
// Act 2: AuthenticationStateProvider issues notification
authStateProvider.TriggerAuthenticationStateChanged(
Task.FromResult(CreateAuthenticationState("Bert")));
// Assert 2: Re-renders content
Assert.Equal(2, renderer.Batches.Count);
var batch = renderer.Batches.Last();
var receiveAuthStateDiff = batch.DiffsByComponentId[receiveAuthStateId].Single();
Assert.Collection(receiveAuthStateDiff.Edits, edit =>
{
Assert.Equal(RenderTreeEditType.UpdateText, edit.Type);
AssertFrame.Text(
batch.ReferenceFrames[edit.ReferenceFrameIndex],
"Authenticated: True; Name: Bert; Pending: False; Renders: 2");
});
}
class ReceiveAuthStateComponent : AutoRenderComponent
{
int numRenders;
[CascadingParameter] Task<AuthenticationState> AuthStateTask { get; set; }
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
numRenders++;
if (AuthStateTask.IsCompleted)
{
var identity = AuthStateTask.Result.User.Identity;
builder.AddContent(0, $"Authenticated: {identity.IsAuthenticated}; Name: {identity.Name}; Pending: False; Renders: {numRenders}");
}
else
{
builder.AddContent(0, $"Authenticated: False; Name: ; Pending: True; Renders: {numRenders}");
}
}
}
class UseCascadingAuthenticationStateComponent : AutoRenderComponent
{
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.OpenComponent<CascadingAuthenticationState>(0);
builder.AddAttribute(1, "ChildContent", new RenderFragment(childBuilder =>
{
childBuilder.OpenComponent<ReceiveAuthStateComponent>(0);
childBuilder.CloseComponent();
}));
builder.CloseComponent();
}
}
public static AuthenticationState CreateAuthenticationState(string username)
=> new AuthenticationState(new ClaimsPrincipal(username == null
? new ClaimsIdentity()
: (IIdentity)new TestIdentity { Name = username }));
class TestIdentity : IIdentity
{
public string AuthenticationType => "Test";
public bool IsAuthenticated => true;
public string Name { get; set; }
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// Pool-wide updates to the host software
/// First published in XenServer 7.1.
/// </summary>
public partial class Pool_update : XenObject<Pool_update>
{
#region Constructors
public Pool_update()
{
}
public Pool_update(string uuid,
string name_label,
string name_description,
string version,
long installation_size,
string key,
List<update_after_apply_guidance> after_apply_guidance,
XenRef<VDI> vdi,
List<XenRef<Host>> hosts,
Dictionary<string, string> other_config,
bool enforce_homogeneity)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.version = version;
this.installation_size = installation_size;
this.key = key;
this.after_apply_guidance = after_apply_guidance;
this.vdi = vdi;
this.hosts = hosts;
this.other_config = other_config;
this.enforce_homogeneity = enforce_homogeneity;
}
/// <summary>
/// Creates a new Pool_update from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Pool_update(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Pool_update from a Proxy_Pool_update.
/// </summary>
/// <param name="proxy"></param>
public Pool_update(Proxy_Pool_update proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Pool_update.
/// </summary>
public override void UpdateFrom(Pool_update update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
version = update.version;
installation_size = update.installation_size;
key = update.key;
after_apply_guidance = update.after_apply_guidance;
vdi = update.vdi;
hosts = update.hosts;
other_config = update.other_config;
enforce_homogeneity = update.enforce_homogeneity;
}
internal void UpdateFrom(Proxy_Pool_update proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
version = proxy.version == null ? null : proxy.version;
installation_size = proxy.installation_size == null ? 0 : long.Parse(proxy.installation_size);
key = proxy.key == null ? null : proxy.key;
after_apply_guidance = proxy.after_apply_guidance == null ? null : Helper.StringArrayToEnumList<update_after_apply_guidance>(proxy.after_apply_guidance);
vdi = proxy.vdi == null ? null : XenRef<VDI>.Create(proxy.vdi);
hosts = proxy.hosts == null ? null : XenRef<Host>.Create(proxy.hosts);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
enforce_homogeneity = (bool)proxy.enforce_homogeneity;
}
public Proxy_Pool_update ToProxy()
{
Proxy_Pool_update result_ = new Proxy_Pool_update();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.version = version ?? "";
result_.installation_size = installation_size.ToString();
result_.key = key ?? "";
result_.after_apply_guidance = after_apply_guidance == null ? new string[] {} : Helper.ObjectListToStringArray(after_apply_guidance);
result_.vdi = vdi ?? "";
result_.hosts = hosts == null ? new string[] {} : Helper.RefListToStringArray(hosts);
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.enforce_homogeneity = enforce_homogeneity;
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Pool_update
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("version"))
version = Marshalling.ParseString(table, "version");
if (table.ContainsKey("installation_size"))
installation_size = Marshalling.ParseLong(table, "installation_size");
if (table.ContainsKey("key"))
key = Marshalling.ParseString(table, "key");
if (table.ContainsKey("after_apply_guidance"))
after_apply_guidance = Helper.StringArrayToEnumList<update_after_apply_guidance>(Marshalling.ParseStringArray(table, "after_apply_guidance"));
if (table.ContainsKey("vdi"))
vdi = Marshalling.ParseRef<VDI>(table, "vdi");
if (table.ContainsKey("hosts"))
hosts = Marshalling.ParseSetRef<Host>(table, "hosts");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
if (table.ContainsKey("enforce_homogeneity"))
enforce_homogeneity = Marshalling.ParseBool(table, "enforce_homogeneity");
}
public bool DeepEquals(Pool_update other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._version, other._version) &&
Helper.AreEqual2(this._installation_size, other._installation_size) &&
Helper.AreEqual2(this._key, other._key) &&
Helper.AreEqual2(this._after_apply_guidance, other._after_apply_guidance) &&
Helper.AreEqual2(this._vdi, other._vdi) &&
Helper.AreEqual2(this._hosts, other._hosts) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._enforce_homogeneity, other._enforce_homogeneity);
}
internal static List<Pool_update> ProxyArrayToObjectList(Proxy_Pool_update[] input)
{
var result = new List<Pool_update>();
foreach (var item in input)
result.Add(new Pool_update(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Pool_update server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Pool_update.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static Pool_update get_record(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_record(session.opaque_ref, _pool_update);
else
return new Pool_update(session.proxy.pool_update_get_record(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get a reference to the pool_update instance with the specified UUID.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Pool_update> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Pool_update>.Create(session.proxy.pool_update_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the pool_update instances with the given label.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Pool_update>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Pool_update>.Create(session.proxy.pool_update_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_uuid(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_uuid(session.opaque_ref, _pool_update);
else
return session.proxy.pool_update_get_uuid(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_name_label(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_name_label(session.opaque_ref, _pool_update);
else
return session.proxy.pool_update_get_name_label(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_name_description(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_name_description(session.opaque_ref, _pool_update);
else
return session.proxy.pool_update_get_name_description(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the version field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_version(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_version(session.opaque_ref, _pool_update);
else
return session.proxy.pool_update_get_version(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the installation_size field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static long get_installation_size(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_installation_size(session.opaque_ref, _pool_update);
else
return long.Parse(session.proxy.pool_update_get_installation_size(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the key field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_key(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_key(session.opaque_ref, _pool_update);
else
return session.proxy.pool_update_get_key(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the after_apply_guidance field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static List<update_after_apply_guidance> get_after_apply_guidance(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_after_apply_guidance(session.opaque_ref, _pool_update);
else
return Helper.StringArrayToEnumList<update_after_apply_guidance>(session.proxy.pool_update_get_after_apply_guidance(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the vdi field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static XenRef<VDI> get_vdi(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_vdi(session.opaque_ref, _pool_update);
else
return XenRef<VDI>.Create(session.proxy.pool_update_get_vdi(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the hosts field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static List<XenRef<Host>> get_hosts(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_hosts(session.opaque_ref, _pool_update);
else
return XenRef<Host>.Create(session.proxy.pool_update_get_hosts(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given pool_update.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static Dictionary<string, string> get_other_config(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_other_config(session.opaque_ref, _pool_update);
else
return Maps.convert_from_proxy_string_string(session.proxy.pool_update_get_other_config(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the enforce_homogeneity field of the given pool_update.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static bool get_enforce_homogeneity(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_enforce_homogeneity(session.opaque_ref, _pool_update);
else
return (bool)session.proxy.pool_update_get_enforce_homogeneity(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given pool_update.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _pool_update, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_set_other_config(session.opaque_ref, _pool_update, _other_config);
else
session.proxy.pool_update_set_other_config(session.opaque_ref, _pool_update ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given pool_update.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _pool_update, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_add_to_other_config(session.opaque_ref, _pool_update, _key, _value);
else
session.proxy.pool_update_add_to_other_config(session.opaque_ref, _pool_update ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given pool_update. If the key is not in that Map, then do nothing.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _pool_update, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_remove_from_other_config(session.opaque_ref, _pool_update, _key);
else
session.proxy.pool_update_remove_from_other_config(session.opaque_ref, _pool_update ?? "", _key ?? "").parse();
}
/// <summary>
/// Introduce update VDI
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vdi">The VDI which contains a software update.</param>
public static XenRef<Pool_update> introduce(Session session, string _vdi)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_introduce(session.opaque_ref, _vdi);
else
return XenRef<Pool_update>.Create(session.proxy.pool_update_introduce(session.opaque_ref, _vdi ?? "").parse());
}
/// <summary>
/// Introduce update VDI
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vdi">The VDI which contains a software update.</param>
public static XenRef<Task> async_introduce(Session session, string _vdi)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_introduce(session.opaque_ref, _vdi);
else
return XenRef<Task>.Create(session.proxy.async_pool_update_introduce(session.opaque_ref, _vdi ?? "").parse());
}
/// <summary>
/// Execute the precheck stage of the selected update on a host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_host">The host to run the prechecks on.</param>
public static livepatch_status precheck(Session session, string _pool_update, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_precheck(session.opaque_ref, _pool_update, _host);
else
return (livepatch_status)Helper.EnumParseDefault(typeof(livepatch_status), (string)session.proxy.pool_update_precheck(session.opaque_ref, _pool_update ?? "", _host ?? "").parse());
}
/// <summary>
/// Execute the precheck stage of the selected update on a host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_host">The host to run the prechecks on.</param>
public static XenRef<Task> async_precheck(Session session, string _pool_update, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_precheck(session.opaque_ref, _pool_update, _host);
else
return XenRef<Task>.Create(session.proxy.async_pool_update_precheck(session.opaque_ref, _pool_update ?? "", _host ?? "").parse());
}
/// <summary>
/// Apply the selected update to a host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_host">The host to apply the update to.</param>
public static void apply(Session session, string _pool_update, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_apply(session.opaque_ref, _pool_update, _host);
else
session.proxy.pool_update_apply(session.opaque_ref, _pool_update ?? "", _host ?? "").parse();
}
/// <summary>
/// Apply the selected update to a host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_host">The host to apply the update to.</param>
public static XenRef<Task> async_apply(Session session, string _pool_update, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_apply(session.opaque_ref, _pool_update, _host);
else
return XenRef<Task>.Create(session.proxy.async_pool_update_apply(session.opaque_ref, _pool_update ?? "", _host ?? "").parse());
}
/// <summary>
/// Apply the selected update to all hosts in the pool
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static void pool_apply(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_pool_apply(session.opaque_ref, _pool_update);
else
session.proxy.pool_update_pool_apply(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Apply the selected update to all hosts in the pool
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static XenRef<Task> async_pool_apply(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_pool_apply(session.opaque_ref, _pool_update);
else
return XenRef<Task>.Create(session.proxy.async_pool_update_pool_apply(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Removes the update's files from all hosts in the pool, but does not revert the update
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static void pool_clean(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_pool_clean(session.opaque_ref, _pool_update);
else
session.proxy.pool_update_pool_clean(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Removes the update's files from all hosts in the pool, but does not revert the update
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static XenRef<Task> async_pool_clean(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_pool_clean(session.opaque_ref, _pool_update);
else
return XenRef<Task>.Create(session.proxy.async_pool_update_pool_clean(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Removes the database entry. Only works on unapplied update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static void destroy(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_destroy(session.opaque_ref, _pool_update);
else
session.proxy.pool_update_destroy(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Removes the database entry. Only works on unapplied update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static XenRef<Task> async_destroy(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_destroy(session.opaque_ref, _pool_update);
else
return XenRef<Task>.Create(session.proxy.async_pool_update_destroy(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Return a list of all the pool_updates known to the system.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Pool_update>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_all(session.opaque_ref);
else
return XenRef<Pool_update>.Create(session.proxy.pool_update_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the pool_update Records at once, in a single XML RPC call
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Pool_update>, Pool_update> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_all_records(session.opaque_ref);
else
return XenRef<Pool_update>.Create<Proxy_Pool_update>(session.proxy.pool_update_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// Update version number
/// </summary>
public virtual string version
{
get { return _version; }
set
{
if (!Helper.AreEqual(value, _version))
{
_version = value;
Changed = true;
NotifyPropertyChanged("version");
}
}
}
private string _version = "";
/// <summary>
/// Size of the update in bytes
/// </summary>
public virtual long installation_size
{
get { return _installation_size; }
set
{
if (!Helper.AreEqual(value, _installation_size))
{
_installation_size = value;
Changed = true;
NotifyPropertyChanged("installation_size");
}
}
}
private long _installation_size = 0;
/// <summary>
/// GPG key of the update
/// </summary>
public virtual string key
{
get { return _key; }
set
{
if (!Helper.AreEqual(value, _key))
{
_key = value;
Changed = true;
NotifyPropertyChanged("key");
}
}
}
private string _key = "";
/// <summary>
/// What the client should do after this update has been applied.
/// </summary>
public virtual List<update_after_apply_guidance> after_apply_guidance
{
get { return _after_apply_guidance; }
set
{
if (!Helper.AreEqual(value, _after_apply_guidance))
{
_after_apply_guidance = value;
Changed = true;
NotifyPropertyChanged("after_apply_guidance");
}
}
}
private List<update_after_apply_guidance> _after_apply_guidance = new List<update_after_apply_guidance>() {};
/// <summary>
/// VDI the update was uploaded to
/// </summary>
[JsonConverter(typeof(XenRefConverter<VDI>))]
public virtual XenRef<VDI> vdi
{
get { return _vdi; }
set
{
if (!Helper.AreEqual(value, _vdi))
{
_vdi = value;
Changed = true;
NotifyPropertyChanged("vdi");
}
}
}
private XenRef<VDI> _vdi = new XenRef<VDI>(Helper.NullOpaqueRef);
/// <summary>
/// The hosts that have applied this update.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Host>))]
public virtual List<XenRef<Host>> hosts
{
get { return _hosts; }
set
{
if (!Helper.AreEqual(value, _hosts))
{
_hosts = value;
Changed = true;
NotifyPropertyChanged("hosts");
}
}
}
private List<XenRef<Host>> _hosts = new List<XenRef<Host>>() {};
/// <summary>
/// additional configuration
/// First published in XenServer 7.3.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
/// <summary>
/// Flag - if true, all hosts in a pool must apply this update
/// First published in XenServer 7.3.
/// </summary>
public virtual bool enforce_homogeneity
{
get { return _enforce_homogeneity; }
set
{
if (!Helper.AreEqual(value, _enforce_homogeneity))
{
_enforce_homogeneity = value;
Changed = true;
NotifyPropertyChanged("enforce_homogeneity");
}
}
}
private bool _enforce_homogeneity = false;
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Masb.Yai
{
public class ExpressionReflectionVisitor : ExpressionVisitor
{
protected override CatchBlock VisitCatchBlock(CatchBlock node)
{
var newTest = this.VisitType(node.Test);
if (newTest != node.Test)
{
var newVariable = this.VisitAndConvert(node.Variable, "VisitCatchBlock");
var newFilter = this.Visit(node.Filter);
var newBody = this.Visit(node.Body);
var newNode = Expression.MakeCatchBlock(newTest, newVariable, newFilter, newBody);
return newNode;
}
return base.VisitCatchBlock(node);
}
protected override Expression VisitConstant(ConstantExpression node)
{
var asType = node.Value as Type;
if (asType != null)
{
var newType = this.VisitType(asType);
if (asType != newType)
return Expression.Constant(newType);
}
return base.VisitConstant(node);
}
protected override Expression VisitDefault(DefaultExpression node)
{
var newType = this.VisitType(node.Type);
if (newType != node.Type)
return Expression.Default(newType);
return base.VisitDefault(node);
}
protected override Expression VisitDynamic(DynamicExpression node)
{
// todo: is dynamic inside lambda possible?
return base.VisitDynamic(node);
}
protected override ElementInit VisitElementInit(ElementInit node)
{
// todo: a method is used here
return base.VisitElementInit(node);
}
protected override Expression VisitLambda<T>(Expression<T> node)
{
var type = typeof(T);
var newType = this.VisitType(type);
if (newType != type)
{
var newBody = this.Visit(node.Body);
var newArgs = this.VisitAndConvert(node.Parameters, "VisitLambda");
var newNode = Expression.Lambda(newType, newBody, node.Name, node.TailCall, newArgs);
return newNode;
}
return base.VisitLambda(node);
}
protected override Expression VisitMethodCall(MethodCallExpression node)
{
var newMethod = this.VisitMethodInfo(node.Method);
if (newMethod != node.Method)
{
Expression instance = this.Visit(node.Object);
var expressionArray = this.Visit(node.Arguments);
var newNode = Expression.Call(instance, newMethod, expressionArray);
return newNode;
}
return base.VisitMethodCall(node);
}
protected override Expression VisitUnary(UnaryExpression node)
{
if (node.NodeType == ExpressionType.Convert || node.NodeType == ExpressionType.ConvertChecked)
{
var newType = this.VisitType(node.Type);
if (newType != node.Type)
{
var newOperand = this.Visit(node.Operand);
var newNode = node.NodeType == ExpressionType.Convert
? Expression.Convert(newOperand, newType)
: Expression.ConvertChecked(newOperand, newType);
return newNode;
}
}
return base.VisitUnary(node);
}
protected virtual Type VisitType(Type type)
{
Type newType = null;
if (type.ReflectedType != null)
{
var newReflectedType = this.VisitType(type.ReflectedType);
if (newReflectedType != type.ReflectedType)
newType = FindEquivalentType(type, newReflectedType);
}
Type[] newTypeParams = null;
if (type.IsGenericType)
newTypeParams = this.VisitTypeGenericParameters(type);
if (newTypeParams != null)
{
newType = newType ?? type;
newType = newType.IsGenericTypeDefinition
? newType
: newType.GetGenericTypeDefinition();
newType = newType.MakeGenericType(newTypeParams);
}
newType = newType ?? type;
return newType;
}
protected virtual Type[] VisitTypeGenericParameters(Type type)
{
Type[] newTypeParams = null;
var typeParams = type.GetGenericArguments();
for (int itParam = 0; itParam < typeParams.Length; itParam++)
{
var newTypeParam = this.VisitType(typeParams[itParam]);
if (newTypeParams != null)
newTypeParams[itParam] = newTypeParam;
else if (newTypeParam != typeParams[itParam])
newTypeParams = typeParams;
}
return typeParams;
}
protected virtual MethodInfo VisitMethodInfo(MethodInfo method)
{
MethodInfo newMethod = null;
if (method.ReflectedType != null)
{
var newReflectedType = this.VisitType(method.ReflectedType);
if (newReflectedType != method.ReflectedType)
newMethod = FindEquivalentMethod(method, newReflectedType);
}
Type[] newTypeParams = null;
if (method.IsGenericMethod)
newTypeParams = this.VisitMethodGenericParameters(method);
if (newTypeParams != null)
{
newMethod = newMethod ?? method;
newMethod = newMethod.IsGenericMethodDefinition
? newMethod
: newMethod.GetGenericMethodDefinition();
newMethod = newMethod.MakeGenericMethod(newTypeParams);
}
newMethod = newMethod ?? method;
return newMethod;
}
protected virtual Type[] VisitMethodGenericParameters(MethodInfo method)
{
Type[] newTypeParams = null;
var typeParams = method.GetGenericArguments();
for (int itParam = 0; itParam < typeParams.Length; itParam++)
{
var newTypeParam = this.VisitType(typeParams[itParam]);
if (newTypeParams != null)
newTypeParams[itParam] = newTypeParam;
else if (newTypeParam != typeParams[itParam])
newTypeParams = typeParams;
}
return typeParams;
}
protected static Type FindEquivalentType(Type subtype, Type newReflectedType)
{
if (subtype.ReflectedType == null)
throw new Exception("Passed `subtype` must have a `ReflectedType`.");
const BindingFlags allFlags =
BindingFlags.Instance | BindingFlags.Static
| BindingFlags.Public | BindingFlags.NonPublic;
var oldTypes = subtype.ReflectedType.GetNestedTypes(allFlags)
.Where(m => AreTypesGenericallyEqual(m, subtype))
.ToArray();
var newTypes = newReflectedType.GetNestedTypes(allFlags)
.Where(m => AreTypesGenericallyEqual(m, subtype))
.ToArray();
for (int it = 0; it < oldTypes.Length; it++)
if (oldTypes[it] == subtype)
return newTypes[it];
return null;
}
protected static MethodInfo FindEquivalentMethod(MethodInfo method, Type newReflectedType)
{
if (method.ReflectedType == null)
throw new Exception("Passed `method` must have a `ReflectedType`.");
const BindingFlags allFlags =
BindingFlags.Instance | BindingFlags.Static
| BindingFlags.Public | BindingFlags.NonPublic;
var oldMethods = method.ReflectedType.GetMethods(allFlags)
.Where(m => AreMethodsGenericallyEqual(m, method))
.ToArray();
var newMethods = newReflectedType.GetMethods(allFlags)
.Where(m => AreMethodsGenericallyEqual(m, method))
.ToArray();
for (int it = 0; it < oldMethods.Length; it++)
if (oldMethods[it] == method)
return newMethods[it];
return null;
}
protected static bool AreTypesGenericallyEqual(Type a, Type b)
{
#if NET45
return a.MetadataToken == b.MetadataToken;
#else
if (a.Attributes != b.Attributes)
return false;
if (a.Name != b.Name)
return false;
if (a.DeclaringType != null && b.DeclaringType != null)
{
if (a.DeclaringType.IsGenericType != b.DeclaringType.IsGenericType)
return false;
var da = a.DeclaringType;
var db = b.DeclaringType;
if (a.DeclaringType.IsGenericType)
{
da = da.GetGenericTypeDefinition();
db = db.GetGenericTypeDefinition();
}
if (!AreTypesGenericallyEqual(da, db))
return false;
}
else if (a.DeclaringType != b.DeclaringType)
return false;
if (a.IsGenericType != b.IsGenericType)
return false;
if (a.IsGenericType)
{
var ta = a.GetGenericTypeDefinition().GetGenericArguments();
var tb = b.GetGenericTypeDefinition().GetGenericArguments();
if (ta.Length != tb.Length)
return false;
if (!ta.Select(tp => tp.Attributes).SequenceEqual(tb.Select(tp => tp.Attributes)))
return false;
if (!ta.Select(tp => tp.Name).SequenceEqual(tb.Select(tp => tp.Name)))
return false;
}
return true;
#endif
}
protected static bool AreMethodsGenericallyEqual(MethodInfo a, MethodInfo b)
{
#if NET45
return a.MetadataToken == b.MetadataToken;
#else
if (a.Attributes != b.Attributes)
return false;
if (a.Name != b.Name)
return false;
if (a.DeclaringType != null && b.DeclaringType != null)
{
if (a.DeclaringType.IsGenericType != b.DeclaringType.IsGenericType)
return false;
var da = a.DeclaringType;
var db = b.DeclaringType;
if (a.DeclaringType.IsGenericType)
{
da = da.GetGenericTypeDefinition();
db = db.GetGenericTypeDefinition();
}
if (!AreTypesGenericallyEqual(da, db))
return false;
}
else if (a.DeclaringType != b.DeclaringType)
return false;
if (a.IsGenericMethod != b.IsGenericMethod)
return false;
if (a.IsGenericMethod)
{
var ta = a.GetGenericMethodDefinition().GetGenericArguments();
var tb = b.GetGenericMethodDefinition().GetGenericArguments();
if (ta.Length != tb.Length)
return false;
if (!ta.Select(tp => tp.Attributes).SequenceEqual(tb.Select(tp => tp.Attributes)))
return false;
if (!ta.Select(tp => tp.Name).SequenceEqual(tb.Select(tp => tp.Name)))
return false;
}
var pa = a.GetParameters();
var pb = b.GetParameters();
if (pa.Length != pb.Length)
return false;
if (!pa.Select(tp => tp.Attributes).SequenceEqual(pb.Select(tp => tp.Attributes)))
return false;
if (!pa.Select(tp => tp.Name).SequenceEqual(pb.Select(tp => tp.Name)))
return false;
return true;
#endif
}
public virtual object VisitAny(object obj)
{
if (obj is Expression)
return this.Visit(obj as Expression);
if (obj is ReadOnlyCollection<Expression>)
return this.Visit(obj as ReadOnlyCollection<Expression>);
if (obj is Type)
return this.VisitType(obj as Type);
if (obj is MethodInfo)
return this.VisitMethodInfo(obj as MethodInfo);
return obj;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class CustomTypeInfoTypeArgumentMap
{
private static readonly CustomTypeInfoTypeArgumentMap s_empty = new CustomTypeInfoTypeArgumentMap();
private readonly Type _typeDefinition;
private readonly ReadOnlyCollection<byte> _dynamicFlags;
private readonly int[] _dynamicFlagStartIndices;
private readonly ReadOnlyCollection<string> _tupleElementNames;
private readonly int[] _tupleElementNameStartIndices;
private CustomTypeInfoTypeArgumentMap()
{
}
private CustomTypeInfoTypeArgumentMap(
Type typeDefinition,
ReadOnlyCollection<byte> dynamicFlags,
int[] dynamicFlagStartIndices,
ReadOnlyCollection<string> tupleElementNames,
int[] tupleElementNameStartIndices)
{
Debug.Assert(typeDefinition != null);
Debug.Assert((dynamicFlags != null) == (dynamicFlagStartIndices != null));
Debug.Assert((tupleElementNames != null) == (tupleElementNameStartIndices != null));
#if DEBUG
Debug.Assert(typeDefinition.IsGenericTypeDefinition);
int n = typeDefinition.GetGenericArguments().Length;
Debug.Assert(dynamicFlagStartIndices == null || dynamicFlagStartIndices.Length == n + 1);
Debug.Assert(tupleElementNameStartIndices == null || tupleElementNameStartIndices.Length == n + 1);
#endif
_typeDefinition = typeDefinition;
_dynamicFlags = dynamicFlags;
_dynamicFlagStartIndices = dynamicFlagStartIndices;
_tupleElementNames = tupleElementNames;
_tupleElementNameStartIndices = tupleElementNameStartIndices;
}
internal static CustomTypeInfoTypeArgumentMap Create(TypeAndCustomInfo typeAndInfo)
{
var typeInfo = typeAndInfo.Info;
if (typeInfo == null)
{
return s_empty;
}
var type = typeAndInfo.Type;
Debug.Assert(type != null);
if (!type.IsGenericType)
{
return s_empty;
}
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(typeInfo.PayloadTypeId, typeInfo.Payload, out dynamicFlags, out tupleElementNames);
Debug.Assert(dynamicFlags != null || tupleElementNames != null);
var typeDefinition = type.GetGenericTypeDefinition();
Debug.Assert(typeDefinition != null);
var dynamicFlagStartIndices = (dynamicFlags == null) ? null : GetStartIndices(type, t => 1);
var tupleElementNameStartIndices = (tupleElementNames == null) ? null : GetStartIndices(type, TypeHelpers.GetTupleCardinalityIfAny);
return new CustomTypeInfoTypeArgumentMap(
typeDefinition,
dynamicFlags,
dynamicFlagStartIndices,
tupleElementNames,
tupleElementNameStartIndices);
}
internal DkmClrCustomTypeInfo SubstituteCustomTypeInfo(Type type, DkmClrCustomTypeInfo customInfo)
{
if (_typeDefinition == null)
{
return customInfo;
}
ReadOnlyCollection<byte> dynamicFlags = null;
ReadOnlyCollection<string> tupleElementNames = null;
if (customInfo != null)
{
CustomTypeInfo.Decode(
customInfo.PayloadTypeId,
customInfo.Payload,
out dynamicFlags,
out tupleElementNames);
}
var substitutedFlags = SubstituteDynamicFlags(type, dynamicFlags);
var substitutedNames = SubstituteTupleElementNames(type, tupleElementNames);
return CustomTypeInfo.Create(substitutedFlags, substitutedNames);
}
private ReadOnlyCollection<byte> SubstituteDynamicFlags(Type type, ReadOnlyCollection<byte> dynamicFlagsOpt)
{
var builder = ArrayBuilder<bool>.GetInstance();
int f = 0;
foreach (Type curr in new TypeWalker(type))
{
if (curr.IsGenericParameter && curr.DeclaringType.Equals(_typeDefinition))
{
AppendRangeFor(
curr,
_dynamicFlags,
_dynamicFlagStartIndices,
DynamicFlagsCustomTypeInfo.GetFlag,
builder);
}
else
{
builder.Add(DynamicFlagsCustomTypeInfo.GetFlag(dynamicFlagsOpt, f));
}
f++;
}
var result = DynamicFlagsCustomTypeInfo.ToBytes(builder);
builder.Free();
return result;
}
private ReadOnlyCollection<string> SubstituteTupleElementNames(Type type, ReadOnlyCollection<string> tupleElementNamesOpt)
{
var builder = ArrayBuilder<string>.GetInstance();
int i = 0;
foreach (Type curr in new TypeWalker(type))
{
if (curr.IsGenericParameter && curr.DeclaringType.Equals(_typeDefinition))
{
AppendRangeFor(
curr,
_tupleElementNames,
_tupleElementNameStartIndices,
CustomTypeInfo.GetTupleElementNameIfAny,
builder);
}
else
{
int n = curr.GetTupleCardinalityIfAny();
AppendRange(tupleElementNamesOpt, i, i + n, CustomTypeInfo.GetTupleElementNameIfAny, builder);
i += n;
}
}
var result = (builder.Count == 0) ? null : builder.ToImmutable();
builder.Free();
return result;
}
private delegate int GetIndexCount(Type type);
private static int[] GetStartIndices(Type type, GetIndexCount getIndexCount)
{
var typeArgs = type.GetGenericArguments();
Debug.Assert(typeArgs.Length > 0);
int pos = getIndexCount(type); // Consider "type" to have already been consumed.
var startsBuilder = ArrayBuilder<int>.GetInstance();
foreach (var typeArg in typeArgs)
{
startsBuilder.Add(pos);
foreach (Type curr in new TypeWalker(typeArg))
{
pos += getIndexCount(curr);
}
}
Debug.Assert(pos > 1);
startsBuilder.Add(pos);
return startsBuilder.ToArrayAndFree();
}
private delegate U Map<T, U>(ReadOnlyCollection<T> collection, int index);
private static void AppendRangeFor<T, U>(
Type type,
ReadOnlyCollection<T> collection,
int[] startIndices,
Map<T, U> map,
ArrayBuilder<U> builder)
{
Debug.Assert(type.IsGenericParameter);
if (startIndices == null)
{
return;
}
var genericParameterPosition = type.GenericParameterPosition;
AppendRange(
collection,
startIndices[genericParameterPosition],
startIndices[genericParameterPosition + 1],
map,
builder);
}
private static void AppendRange<T, U>(
ReadOnlyCollection<T> collection,
int start,
int end,
Map<T, U> map,
ArrayBuilder<U> builder)
{
for (int i = start; i < end; i++)
{
builder.Add(map(collection, i));
}
}
}
}
| |
using System;
using System.Text;
using NUnit.Framework;
using SimpleContainer.Interface;
using SimpleContainer.Tests.Helpers;
namespace SimpleContainer.Tests
{
public abstract class CloneContainerTest : SimpleContainerTestBase
{
public class Simple : CloneContainerTest
{
private static int counter;
public class Hoster
{
public readonly IContainer container;
public Hoster(IContainer container)
{
this.container = container;
}
}
public class ComponentWrap
{
public readonly Component component;
private readonly int myCounter = counter++;
public ComponentWrap(Component component)
{
this.component = component;
LogBuilder.Append("ComponentWrap" + myCounter + ".ctor ");
}
}
public class Component : IDisposable
{
private readonly int myCounter = counter++;
public Component()
{
LogBuilder.Append("Component" + myCounter + ".ctor ");
}
public void Dispose()
{
LogBuilder.Append("Component" + myCounter + ".Dispose ");
}
}
[Test]
public void Test()
{
using (var container = Container())
{
Assert.That(LogBuilder.ToString(), Is.EqualTo(""));
var hoster = container.Get<Hoster>();
Assert.That(LogBuilder.ToString(), Is.EqualTo(""));
var outerWrap = container.Get<ComponentWrap>();
Assert.That(LogBuilder.ToString(), Is.EqualTo("Component0.ctor ComponentWrap1.ctor "));
LogBuilder.Clear();
ComponentWrap clone1;
using (var clonedContainer = hoster.container.Clone(null))
{
clone1 = clonedContainer.Get<ComponentWrap>();
Assert.That(clone1, Is.Not.SameAs(outerWrap));
Assert.That(LogBuilder.ToString(), Is.EqualTo("Component2.ctor ComponentWrap3.ctor "));
Assert.That(container.Get<ComponentWrap>(), Is.SameAs(outerWrap));
LogBuilder.Clear();
}
Assert.That(LogBuilder.ToString(), Is.EqualTo("Component2.Dispose "));
LogBuilder.Clear();
using (var clonedContainer = hoster.container.Clone(null))
{
Assert.That(clonedContainer.Get<ComponentWrap>(), Is.Not.SameAs(outerWrap));
Assert.That(clonedContainer.Get<ComponentWrap>(), Is.Not.SameAs(clone1));
Assert.That(clonedContainer.Get<ComponentWrap>(), Is.SameAs(clonedContainer.Get<ComponentWrap>()));
Assert.That(LogBuilder.ToString(), Is.EqualTo("Component4.ctor ComponentWrap5.ctor "));
LogBuilder.Clear();
}
Assert.That(LogBuilder.ToString(), Is.EqualTo("Component4.Dispose "));
LogBuilder.Clear();
}
Assert.That(LogBuilder.ToString(), Is.EqualTo("Component0.Dispose "));
}
}
public class OverrideContractConfiguration : CloneContainerTest
{
public class A
{
public readonly B b;
public A([TestContract("x")] B b)
{
this.b = b;
}
}
public class B
{
public readonly int parameter;
public B(int parameter)
{
this.parameter = parameter;
}
}
public class C
{
public readonly int parameter;
public C(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(b => b.Contract("x").BindDependency<B>("parameter", 12));
using (var clonedContainer = container.Clone(b => b.BindDependency<C>("parameter", 13)))
{
Assert.That(clonedContainer.Get<A>().b.parameter, Is.EqualTo(12));
Assert.That(clonedContainer.Get<C>().parameter, Is.EqualTo(13));
}
}
}
public class HostOfClonedContainerShouldBeNotifiedAboutExceptionInDispose : CloneContainerTest
{
public class A : IDisposable
{
public void Dispose()
{
throw new InvalidOperationException("test crash ");
}
}
[Test]
public void Test()
{
var logBuilder = new StringBuilder();
LogError logError = (message, error) => logBuilder.Append(error.InnerException.InnerException.Message);
using (var container = Factory().WithErrorLogger(logError).Build())
{
var exception = Assert.Throws<AggregateException>(delegate
{
using (var containerClone = container.Clone(null))
containerClone.Get<A>();
});
Assert.That(exception.InnerException.InnerException.Message, Is.EqualTo("test crash "));
Assert.That(logBuilder.ToString(), Is.EqualTo(""));
container.Get<A>();
Assert.That(logBuilder.ToString(), Is.EqualTo(""));
}
Assert.That(logBuilder.ToString(), Is.EqualTo("test crash "));
}
}
public class CanOverrideConfiguration : CloneContainerTest
{
public class A
{
public readonly int parameter;
public A(int parameter)
{
this.parameter = parameter;
}
}
public class B
{
public readonly int parameter;
public B(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(b =>
{
b.BindDependency<A>("parameter", 1);
b.BindDependency<B>("parameter", 2);
});
Assert.That(container.Get<A>().parameter, Is.EqualTo(1));
Assert.That(container.Get<B>().parameter, Is.EqualTo(2));
using (var clonedContainer = container.Clone(b => b.BindDependency<A>("parameter", 3)))
{
Assert.That(clonedContainer.Get<A>().parameter, Is.EqualTo(3));
Assert.That(clonedContainer.Get<B>().parameter, Is.EqualTo(2));
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
namespace System.Data.SqlClient
{
abstract internal class SqlInternalConnection : DbConnectionInternal
{
private readonly SqlConnectionString _connectionOptions;
// if connection is not open: null
// if connection is open: currently active database
internal string CurrentDatabase { get; set; }
// if connection is not open yet, CurrentDataSource is null
// if connection is open:
// * for regular connections, it is set to Data Source value from connection string
// * for connections with FailoverPartner, it is set to the FailoverPartner value from connection string if the connection was opened to it.
internal string CurrentDataSource { get; set; }
internal enum TransactionRequest
{
Begin,
Commit,
Rollback,
IfRollback,
Save
};
internal SqlInternalConnection(SqlConnectionString connectionOptions) : base()
{
Debug.Assert(null != connectionOptions, "null connectionOptions?");
_connectionOptions = connectionOptions;
}
internal SqlConnection Connection
{
get
{
return (SqlConnection)Owner;
}
}
internal SqlConnectionString ConnectionOptions
{
get
{
return _connectionOptions;
}
}
abstract internal SqlInternalTransaction CurrentTransaction
{
get;
}
// Get the internal transaction that should be hooked to a new outer transaction
// during a BeginTransaction API call. In some cases (i.e. connection is going to
// be reset), CurrentTransaction should not be hooked up this way.
virtual internal SqlInternalTransaction AvailableInternalTransaction
{
get
{
return CurrentTransaction;
}
}
internal bool HasLocalTransaction
{
get
{
SqlInternalTransaction currentTransaction = CurrentTransaction;
bool result = (null != currentTransaction && currentTransaction.IsLocal);
return result;
}
}
internal bool HasLocalTransactionFromAPI
{
get
{
SqlInternalTransaction currentTransaction = CurrentTransaction;
bool result = (null != currentTransaction && currentTransaction.HasParentTransaction);
return result;
}
}
abstract internal bool IsLockedForBulkCopy
{
get;
}
abstract internal bool IsKatmaiOrNewer
{
get;
}
override public DbTransaction BeginTransaction(IsolationLevel iso)
{
return BeginSqlTransaction(iso, null, false);
}
virtual internal SqlTransaction BeginSqlTransaction(IsolationLevel iso, string transactionName, bool shouldReconnect)
{
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Connection.Statistics);
ValidateConnectionForExecute(null);
if (HasLocalTransactionFromAPI)
throw ADP.ParallelTransactionsNotSupported(Connection);
if (iso == IsolationLevel.Unspecified)
{
iso = IsolationLevel.ReadCommitted; // Default to ReadCommitted if unspecified.
}
SqlTransaction transaction = new SqlTransaction(this, Connection, iso, AvailableInternalTransaction);
transaction.InternalTransaction.RestoreBrokenConnection = shouldReconnect;
ExecuteTransaction(TransactionRequest.Begin, transactionName, iso, transaction.InternalTransaction);
transaction.InternalTransaction.RestoreBrokenConnection = false;
return transaction;
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
override public void ChangeDatabase(string database)
{
if (ADP.IsEmpty(database))
{
throw ADP.EmptyDatabaseName();
}
ValidateConnectionForExecute(null);
ChangeDatabaseInternal(database); // do the real work...
}
abstract protected void ChangeDatabaseInternal(string database);
override protected DbReferenceCollection CreateReferenceCollection()
{
return new SqlReferenceCollection();
}
override protected void Deactivate()
{
try
{
SqlReferenceCollection referenceCollection = (SqlReferenceCollection)ReferenceCollection;
if (null != referenceCollection)
{
referenceCollection.Deactivate();
}
// Invoke subclass-specific deactivation logic
InternalDeactivate();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
// if an exception occurred, the inner connection will be
// marked as unusable and destroyed upon returning to the
// pool
DoomThisConnection();
}
}
abstract internal void DisconnectTransaction(SqlInternalTransaction internalTransaction);
override public void Dispose()
{
base.Dispose();
}
abstract internal void ExecuteTransaction(TransactionRequest transactionRequest, string name, IsolationLevel iso, SqlInternalTransaction internalTransaction);
internal SqlDataReader FindLiveReader(SqlCommand command)
{
SqlDataReader reader = null;
SqlReferenceCollection referenceCollection = (SqlReferenceCollection)ReferenceCollection;
if (null != referenceCollection)
{
reader = referenceCollection.FindLiveReader(command);
}
return reader;
}
internal SqlCommand FindLiveCommand(TdsParserStateObject stateObj)
{
SqlCommand command = null;
SqlReferenceCollection referenceCollection = (SqlReferenceCollection)ReferenceCollection;
if (null != referenceCollection)
{
command = referenceCollection.FindLiveCommand(stateObj);
}
return command;
}
virtual protected void InternalDeactivate()
{
}
// If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter
// The close action also supports being run asynchronously
internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction = null)
{
if (breakConnection)
{
DoomThisConnection();
}
var connection = Connection;
if (null != connection)
{
connection.OnError(exception, breakConnection, wrapCloseInAction);
}
else if (exception.Class >= TdsEnums.MIN_ERROR_CLASS)
{
// It is an error, and should be thrown. Class of TdsEnums.MIN_ERROR_CLASS
// or above is an error, below TdsEnums.MIN_ERROR_CLASS denotes an info message.
throw exception;
}
}
abstract internal void ValidateConnectionForExecute(SqlCommand command);
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
// Tests for features of the Expression class, rather than any derived types,
// including how it acts with custom derived types.
//
// Unfortunately there is slightly different internal behaviour depending on whether
// a derived Expression uses the new constructor, uses the old constructor, or uses
// the new constructor after at least one use of the old constructor has been made,
// due to static state being affected. For this reason some tests have to be done
// in a particular order, with those for the old constructor coming after most of
// the tests, and those affected by this being repeated after that.
[TestCaseOrderer("System.Linq.Expressions.Tests.TestOrderer", "System.Linq.Expressions.Tests")]
public class ExpressionTests
{
private static readonly Expression MarkerExtension = Expression.Constant(0);
private class IncompleteExpressionOverride : Expression
{
public class Visitor : ExpressionVisitor
{
protected override Expression VisitExtension(Expression node)
{
return MarkerExtension;
}
}
public IncompleteExpressionOverride()
: base()
{
}
public Expression VisitChildren()
{
return VisitChildren(new Visitor());
}
}
private class ClaimedReducibleOverride : IncompleteExpressionOverride
{
public override bool CanReduce
{
get { return true; }
}
}
private class ReducesToSame : ClaimedReducibleOverride
{
public override Expression Reduce()
{
return this;
}
}
private class ReducesToNull : ClaimedReducibleOverride
{
public override Expression Reduce()
{
return null;
}
}
private class ReducesToLongTyped : ClaimedReducibleOverride
{
private class ReducedToLongTyped : IncompleteExpressionOverride
{
public override Type Type
{
get { return typeof(long); }
}
}
public override Type Type
{
get { return typeof(int); }
}
public override Expression Reduce()
{
return new ReducedToLongTyped();
}
}
private class Reduces : ClaimedReducibleOverride
{
public override Type Type
{
get { return typeof(int); }
}
public override Expression Reduce()
{
return new Reduces();
}
}
private class ReducesFromStrangeNodeType : Expression
{
public override Type Type => typeof(int);
public override ExpressionType NodeType => (ExpressionType)(-1);
public override bool CanReduce => true;
public override Expression Reduce() => Constant(3);
}
private class ObsoleteIncompleteExpressionOverride : Expression
{
#pragma warning disable 0618 // Testing obsolete behaviour.
public ObsoleteIncompleteExpressionOverride(ExpressionType nodeType, Type type)
: base(nodeType, type)
{
}
#pragma warning restore 0618
}
private class IrreducibleWithTypeAndNodeType : Expression
{
public override Type Type => typeof(void);
public override ExpressionType NodeType => ExpressionType.Extension;
}
private class IrreduceibleWithTypeAndStrangeNodeType : Expression
{
public override Type Type => typeof(void);
public override ExpressionType NodeType => (ExpressionType)(-1);
}
private class ExtensionNoToString : Expression
{
public override ExpressionType NodeType => ExpressionType.Extension;
public override Type Type => typeof(int);
public override bool CanReduce => false;
}
private class ExtensionToString : Expression
{
public override ExpressionType NodeType => ExpressionType.Extension;
public override Type Type => typeof(int);
public override bool CanReduce => false;
public override string ToString() => "bar";
}
public static IEnumerable<object[]> AllNodeTypesPlusSomeInvalid
{
get
{
foreach (ExpressionType et in Enum.GetValues(typeof(ExpressionType)))
yield return new object[] { et };
yield return new object[] { (ExpressionType)(-1) };
yield return new object[] { (ExpressionType)int.MaxValue };
yield return new object[] { (ExpressionType)int.MinValue };
}
}
public static IEnumerable<object[]> SomeTypes
{
get
{
return new[] { typeof(int), typeof(void), typeof(object), typeof(DateTime), typeof(string), typeof(ExpressionTests), typeof(ExpressionType) }
.Select(type => new object[] { type });
}
}
[Fact]
public void NodeTypeMustBeOverridden()
{
var exp = new IncompleteExpressionOverride();
Assert.Throws<InvalidOperationException>(() => exp.NodeType);
}
[Theory, TestOrder(1), MemberData(nameof(AllNodeTypesPlusSomeInvalid))]
public void NodeTypeFromConstructor(ExpressionType nodeType)
{
Assert.Equal(nodeType, new ObsoleteIncompleteExpressionOverride(nodeType, typeof(int)).NodeType);
}
[Fact, TestOrder(2)]
public void NodeTypeMustBeOverriddenAfterObsoleteConstructorUsed()
{
var exp = new IncompleteExpressionOverride();
Assert.Throws<InvalidOperationException>(() => exp.NodeType);
}
[Fact]
public void TypeMustBeOverridden()
{
var exp = new IncompleteExpressionOverride();
Assert.Throws<InvalidOperationException>(() => exp.Type);
}
[Theory, TestOrder(1), MemberData(nameof(SomeTypes))]
public void TypeFromConstructor(Type type)
{
Assert.Equal(type, new ObsoleteIncompleteExpressionOverride(ExpressionType.Constant, type).Type);
}
[Fact, TestOrder(1)]
public void TypeMayBeNonNullOnObsoleteConstructedExpression()
{
// This is probably undesirable, but throwing here would be a breaking change.
// Impact must be considered before prohibiting this.
Assert.Null(new ObsoleteIncompleteExpressionOverride(ExpressionType.Add, null).Type);
}
[Fact, TestOrder(2)]
public void TypeMustBeOverriddenCheckCorrectAfterObsoleteConstructorUsed()
{
var exp = new IncompleteExpressionOverride();
Assert.Throws<InvalidOperationException>(() => exp.Type);
}
[Fact]
public void DefaultCannotReduce()
{
Assert.False(new IncompleteExpressionOverride().CanReduce);
}
[Fact]
public void DefaultReducesToSame()
{
var exp = new IncompleteExpressionOverride();
Assert.Same(exp, exp.Reduce());
}
[Fact]
public void VisitChildrenThrowsAsNotReducible()
{
var exp = new IncompleteExpressionOverride();
Assert.Throws<ArgumentException>(null, () => exp.VisitChildren());
}
[Fact]
public void CanVisitChildrenIfReallyReduces()
{
var exp = new Reduces();
Assert.NotSame(exp, exp.VisitChildren());
}
[Fact]
public void VisitingCallsVisitExtension()
{
Assert.Same(MarkerExtension, new IncompleteExpressionOverride.Visitor().Visit(new IncompleteExpressionOverride()));
}
[Fact]
public void ReduceAndCheckThrowsByDefault()
{
var exp = new IncompleteExpressionOverride();
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public void ReduceExtensionsThrowsByDefault()
{
var exp = new IncompleteExpressionOverride();
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public void IfClaimCanReduceMustReduce()
{
var exp = new ClaimedReducibleOverride();
Assert.Throws<ArgumentException>(null, () => exp.Reduce());
}
[Fact]
public void ReduceAndCheckThrowOnReduceToSame()
{
var exp = new ReducesToSame();
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public void ReduceAndCheckThrowOnReduceToNull()
{
var exp = new ReducesToNull();
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public void ReduceAndCheckThrowOnReducedTypeNotAssignable()
{
var exp = new ReducesToLongTyped();
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
#pragma warning disable 0169, 0414 // Accessed through reflection.
private static int TestField;
private const int TestConstant = 0;
private static readonly int TestInitOnlyField = 0;
#pragma warning restore 0169, 0414
private static int Unreadable
{
set { }
}
private static int Unwritable
{
get { return 0; }
}
private class UnreadableIndexableClass
{
public int this[int index]
{
set { }
}
}
private class UnwritableIndexableClass
{
public int this[int index]
{
get { return 0; }
}
}
[Fact]
public void ConfirmCanRead()
{
var readableExpressions = new Expression[]
{
Expression.Constant(0),
Expression.Add(Expression.Constant(0), Expression.Constant(0)),
Expression.Default(typeof(int)),
Expression.Property(Expression.Constant(new List<int>()), "Count"),
Expression.ArrayIndex(Expression.Constant(Array.Empty<int>()), Expression.Constant(0)),
Expression.Field(null, typeof(ExpressionTests), "TestField"),
Expression.Field(null, typeof(ExpressionTests), "TestConstant"),
Expression.Field(null, typeof(ExpressionTests), "TestInitOnlyField")
};
Expression.Block(typeof(void), readableExpressions);
}
public static IEnumerable<Expression> UnreadableExpressions
{
get
{
yield return Expression.Property(null, typeof(ExpressionTests), "Unreadable");
yield return Expression.Property(Expression.Constant(new UnreadableIndexableClass()), "Item", Expression.Constant(0));
}
}
public static IEnumerable<object[]> UnreadableExpressionData
{
get
{
return UnreadableExpressions.Concat(new Expression[1]).Select(exp => new object[] { exp });
}
}
public static IEnumerable<Expression> WritableExpressions
{
get
{
yield return Expression.Property(null, typeof(ExpressionTests), "Unreadable");
yield return Expression.Property(Expression.Constant(new UnreadableIndexableClass()), "Item", Expression.Constant(0));
yield return Expression.Field(null, typeof(ExpressionTests), "TestField");
yield return Expression.Parameter(typeof(int));
}
}
public static IEnumerable<Expression> UnwritableExpressions
{
get
{
yield return Expression.Property(null, typeof(ExpressionTests), "Unwritable");
yield return Expression.Property(Expression.Constant(new UnwritableIndexableClass()), "Item", Expression.Constant(0));
yield return Expression.Field(null, typeof(ExpressionTests), "TestConstant");
yield return Expression.Field(null, typeof(ExpressionTests), "TestInitOnlyField");
yield return Expression.Call(Expression.Default(typeof(ExpressionTests)), "ConfirmCannotReadSequence", new Type[0]);
yield return null;
}
}
public static IEnumerable<object[]> UnwritableExpressionData
{
get
{
return UnwritableExpressions.Select(exp => new object[] { exp });
}
}
public static IEnumerable<object[]> WritableExpressionData
{
get
{
return WritableExpressions.Select(exp => new object[] { exp });
}
}
[Theory, MemberData(nameof(UnreadableExpressionData))]
public void ConfirmCannotRead(Expression unreadableExpression)
{
if (unreadableExpression == null)
Assert.Throws<ArgumentNullException>("expression", () => Expression.Increment(unreadableExpression));
else
Assert.Throws<ArgumentException>("expression", () => Expression.Increment(unreadableExpression));
}
[Fact]
public void ConfirmCannotReadSequence()
{
Assert.Throws<ArgumentException>("expressions[0]", () => Expression.Block(typeof(void), UnreadableExpressions));
}
[Theory, MemberData(nameof(UnwritableExpressionData))]
public void ConfirmCannotWrite(Expression unwritableExpression)
{
if (unwritableExpression == null)
Assert.Throws<ArgumentNullException>("left", () => Expression.Assign(unwritableExpression, Expression.Constant(0)));
else
Assert.Throws<ArgumentException>("left", () => Expression.Assign(unwritableExpression, Expression.Constant(0)));
}
[Theory, MemberData(nameof(WritableExpressionData))]
public void ConfirmCanWrite(Expression writableExpression)
{
Expression.Assign(writableExpression, Expression.Default(writableExpression.Type));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void CompileIrreduciebleExtension(bool useInterpreter)
{
var exp = Expression.Lambda<Action>(new IrreducibleWithTypeAndNodeType());
Assert.Throws<ArgumentException>(null, () => exp.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void CompileIrreduciebleStrangeNodeTypeExtension(bool useInterpreter)
{
var exp = Expression.Lambda<Action>(new IrreduceibleWithTypeAndStrangeNodeType());
Assert.Throws<ArgumentException>(null, () => exp.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void CompileReducibleStrangeNodeTypeExtension(bool useInterpreter)
{
var exp = Expression.Lambda<Func<int>>(new ReducesFromStrangeNodeType());
Assert.Equal(3, exp.Compile(useInterpreter)());
}
[Fact]
public void ToStringTest()
{
var e1 = new ExtensionNoToString();
Assert.Equal($"[{typeof(ExtensionNoToString).FullName}]", e1.ToString());
var e2 = Expression.Add(Expression.Constant(1), new ExtensionToString());
Assert.Equal($"(1 + bar)", e2.ToString());
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Org.Apache.REEF.Common.Tasks;
using Org.Apache.REEF.Examples.Tasks.HelloTask;
using Org.Apache.REEF.Examples.Tasks.StreamingTasks;
using Org.Apache.REEF.Tang.Annotations;
using Org.Apache.REEF.Tang.Examples;
using Org.Apache.REEF.Tang.Implementations.ClassHierarchy;
using Org.Apache.REEF.Tang.Implementations.Tang;
using Org.Apache.REEF.Tang.Interface;
using Org.Apache.REEF.Tang.Util;
namespace Org.Apache.REEF.Tang.Tests.Injection
{
[DefaultImplementation(typeof(AReferenceClass))]
internal interface IAInterface
{
}
[TestClass]
public class TestInjection
{
static Assembly asm = null;
[ClassInitialize]
public static void ClassSetup(TestContext context)
{
asm = Assembly.Load(FileNames.Examples);
}
[ClassCleanup]
public static void ClassCleanup()
{
}
[TestInitialize()]
public void TestSetup()
{
}
[TestCleanup()]
public void TestCleanup()
{
}
[TestMethod]
public void TestTimer()
{
Type timerType = typeof(Timer);
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples });
cb.BindNamedParameter<Timer.Seconds, int>(GenericType<Timer.Seconds>.Class, "2");
IConfiguration conf = cb.Build();
IInjector injector = tang.NewInjector(conf);
var timer = (Timer)injector.GetInstance(timerType);
Assert.IsNotNull(timer);
timer.sleep();
}
[TestMethod]
public void TestTimerWithClassHierarchy()
{
Type timerType = typeof(Timer);
ClassHierarchyImpl classHierarchyImpl = new ClassHierarchyImpl(FileNames.Examples);
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder((ICsClassHierarchy)classHierarchyImpl);
cb.BindNamedParameter<Timer.Seconds, int>(GenericType<Timer.Seconds>.Class, "2");
IConfiguration conf = cb.Build();
IInjector injector = tang.NewInjector(conf);
var timer = (Timer)injector.GetInstance(timerType);
Assert.IsNotNull(timer);
timer.sleep();
}
[TestMethod]
public void TestDocumentLoadNamedParameter()
{
Type documentedLocalNamedParameterType = typeof(DocumentedLocalNamedParameter);
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples });
cb.BindNamedParameter<DocumentedLocalNamedParameter.Foo, string>(GenericType<DocumentedLocalNamedParameter.Foo>.Class, "Hello");
IConfiguration conf = cb.Build();
IInjector injector = tang.NewInjector(conf);
var doc = (DocumentedLocalNamedParameter)injector.GetInstance(documentedLocalNamedParameterType);
Assert.IsNotNull(doc);
}
[TestMethod]
public void TestDocumentLoadNamedParameterWithDefaultValue()
{
ITang tang = TangFactory.GetTang();
IConfiguration conf = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }).Build();
IInjector injector = tang.NewInjector(conf);
var doc = (DocumentedLocalNamedParameter)injector.GetInstance(typeof(DocumentedLocalNamedParameter));
Assert.IsNotNull(doc);
}
[TestMethod]
public void TestSimpleConstructor()
{
Type simpleConstructorType = typeof(SimpleConstructors);
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples });
IConfiguration conf = cb.Build();
IInjector injector = tang.NewInjector(conf);
var simpleConstructor = (SimpleConstructors)injector.GetInstance(simpleConstructorType);
Assert.IsNotNull(simpleConstructor);
}
[TestMethod]
public void TestActivity()
{
Type activityType = typeof(HelloTask);
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Tasks, FileNames.Common });
IConfiguration conf = cb.Build();
IInjector injector = tang.NewInjector(conf);
var activityRef = (ITask)injector.GetInstance(activityType);
Assert.IsNotNull(activityRef);
}
[TestMethod]
public void TestStreamActivity1()
{
Type activityType = typeof(StreamTask1);
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Tasks, FileNames.Common });
IConfiguration conf = cb.Build();
IInjector injector = tang.NewInjector(conf);
var activityRef = (ITask)injector.GetInstance(activityType);
Assert.IsNotNull(activityRef);
}
[TestMethod]
public void TestStreamActivity2()
{
Type activityType = typeof(StreamTask2);
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Tasks, FileNames.Common });
IConfiguration conf = cb.Build();
IInjector injector = tang.NewInjector(conf);
var activityRef = (ITask)injector.GetInstance(activityType);
Assert.IsNotNull(activityRef);
}
[TestMethod]
public void TestMultipleAssemlies()
{
Type activityInterfaceType1 = typeof(ITask);
Type tweeterType = typeof(Tweeter);
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples, FileNames.Tasks, FileNames.Common });
cb.BindImplementation(GenericType<ITask>.Class, GenericType<HelloTask>.Class);
cb.BindImplementation(GenericType<ITweetFactory>.Class, GenericType<MockTweetFactory>.Class);
cb.BindImplementation(GenericType<ISMS>.Class, GenericType<MockSMS>.Class);
cb.BindNamedParameter<Tweeter.PhoneNumber, long>(GenericType<Tweeter.PhoneNumber>.Class, "8675309");
IConfiguration conf = cb.Build();
IInjector injector = tang.NewInjector(conf);
var activityRef = (ITask)injector.GetInstance(activityInterfaceType1);
var tweeter = (Tweeter)injector.GetInstance(tweeterType);
Assert.IsNotNull(activityRef);
Assert.IsNotNull(tweeter);
tweeter.sendMessage();
}
[TestMethod]
public void TestActivityWithBinding()
{
Type activityInterfaceType = typeof(ITask);
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Tasks, FileNames.Common });
cb.BindImplementation(GenericType<ITask>.Class, GenericType<HelloTask>.Class);
cb.BindNamedParameter<TaskConfigurationOptions.Identifier, string>(GenericType<TaskConfigurationOptions.Identifier>.Class, "Hello Task");
IConfiguration conf = cb.Build();
IInjector injector = tang.NewInjector(conf);
ITask activityRef1 = injector.GetInstance<ITask>();
var activityRef2 = (ITask)injector.GetInstance(activityInterfaceType);
Assert.IsNotNull(activityRef2);
Assert.IsNotNull(activityRef1);
Assert.AreEqual(activityRef1, activityRef2);
}
[TestMethod]
public void TestHelloStreamingActivityWithBinding()
{
Type activityInterfaceType = typeof(ITask);
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Tasks, FileNames.Common });
cb.BindImplementation(GenericType<ITask>.Class, GenericType<HelloTask>.Class);
cb.BindNamedParameter<TaskConfigurationOptions.Identifier, string>(GenericType<TaskConfigurationOptions.Identifier>.Class, "Hello Stereamingk");
cb.BindNamedParameter<StreamTask1.IpAddress, string>(GenericType<StreamTask1.IpAddress>.Class, "127.0.0.0");
IConfiguration conf = cb.Build();
IInjector injector = tang.NewInjector(conf);
var activityRef = (ITask)injector.GetInstance(activityInterfaceType);
Assert.IsNotNull(activityRef);
}
[TestMethod]
public void TestTweetExample()
{
Type tweeterType = typeof(Tweeter);
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples });
IConfiguration conf = cb.BindImplementation(GenericType<ITweetFactory>.Class, GenericType<MockTweetFactory>.Class)
.BindImplementation(GenericType<ISMS>.Class, GenericType<MockSMS>.Class)
.BindNamedParameter<Tweeter.PhoneNumber, long>(GenericType<Tweeter.PhoneNumber>.Class, "8675309")
.Build();
IInjector injector = tang.NewInjector(conf);
var tweeter = (Tweeter)injector.GetInstance(tweeterType);
tweeter.sendMessage();
var sms = (ISMS)injector.GetInstance(typeof(ISMS));
var factory = (ITweetFactory)injector.GetInstance(typeof(ITweetFactory));
Assert.IsNotNull(sms);
Assert.IsNotNull(factory);
}
[TestMethod]
public void TestReferenceType()
{
AReferenceClass o = (AReferenceClass)TangFactory.GetTang().NewInjector().GetInstance(typeof(IAInterface));
}
[TestMethod]
public void TestGeneric()
{
var o = (AGenericClass<int>)TangFactory.GetTang().NewInjector().GetInstance(typeof(AGenericClass<int>));
var o2 = (AClassWithGenericArgument<int>)TangFactory.GetTang().NewInjector().GetInstance(typeof(AClassWithGenericArgument<int>));
Assert.IsNotNull(o);
Assert.IsNotNull(o2);
}
[TestMethod]
public void TestNestedClass()
{
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder();
IConfiguration conf = cb
.BindNamedParameter<ClassParameter.Named1, int>(GenericType<ClassParameter.Named1>.Class, "5")
.BindNamedParameter<ClassParameter.Named2, string>(GenericType<ClassParameter.Named2>.Class, "hello")
.Build();
IInjector injector = tang.NewInjector(conf);
ClassHasNestedClass h = injector.GetInstance<ClassHasNestedClass>();
Assert.IsNotNull(h);
}
[TestMethod]
public void TestExternalObject()
{
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder();
IInjector injector = tang.NewInjector(cb.Build());
//bind an object to the injetor so that Tang will get this instance from cache directly instead of inject it when injecting ClassWithExternalObject
injector.BindVolatileInstance(GenericType<ExternalClass>.Class, new ExternalClass());
ClassWithExternalObject o = injector.GetInstance<ClassWithExternalObject>();
Assert.IsNotNull(o.ExternalObject is ExternalClass);
}
/// <summary>
/// In this test, interface is a generic of T. Implementations have different generic arguments such as int and string.
/// When doing injection, we must specify the interface with a specified argument type
/// </summary>
[TestMethod]
public void TestInjectionWithGenericArguments()
{
var c = TangFactory.GetTang().NewConfigurationBuilder()
.BindImplementation(GenericType<IMyOperator<int>>.Class, GenericType<MyOperatorImpl<int>>.Class)
.BindImplementation(GenericType<IMyOperator<string>>.Class, GenericType<MyOperatorImpl<string>>.Class)
.Build();
var injector = TangFactory.GetTang().NewInjector(c);
//argument type must be specified in injection
var o1 = injector.GetInstance(typeof(IMyOperator<int>));
var o2 = injector.GetInstance(typeof(IMyOperator<string>));
var o3 = injector.GetInstance(typeof(MyOperatorTopology<int>));
Assert.IsTrue(o1 is MyOperatorImpl<int>);
Assert.IsTrue(o2 is MyOperatorImpl<string>);
Assert.IsTrue(o3 is MyOperatorTopology<int>);
}
/// <summary>
/// In this test, interface argument type is set through Configuration. We can get the argument type and then
/// make the interface with the argument type on the fly so that to do the injection
/// </summary>
[TestMethod]
public void TestInjectionWithGenericArgumentType()
{
var c = TangFactory.GetTang().NewConfigurationBuilder()
.BindImplementation(GenericType<IMyOperator<int[]>>.Class, GenericType<MyOperatorImpl<int[]>>.Class)
.BindNamedParameter(typeof(MessageType), typeof(int[]).AssemblyQualifiedName)
.Build();
var injector = TangFactory.GetTang().NewInjector(c);
//get argument type from configuration
var messageTypeAsString = injector.GetNamedInstance<MessageType, string>(GenericType<MessageType>.Class);
Type messageType = Type.GetType(messageTypeAsString);
//creat interface with generic type on the fly
Type genericInterfaceType = typeof(IMyOperator<>);
Type interfaceOfMessageType = genericInterfaceType.MakeGenericType(messageType);
var o = injector.GetInstance(interfaceOfMessageType);
Assert.IsTrue(o is MyOperatorImpl<int[]>);
}
}
class AReferenceClass : IAInterface
{
[Inject]
public AReferenceClass(AReferenced refclass)
{
}
}
class AReferenced
{
[Inject]
public AReferenced()
{
}
}
class AGenericClass<T>
{
[Inject]
public AGenericClass()
{
}
}
class AClassWithGenericArgument<T>
{
[Inject]
public AClassWithGenericArgument(AGenericClass<T> g)
{
}
}
class ClassHasNestedClass
{
[Inject]
public ClassHasNestedClass(ClassParameter h1)
{
}
}
class ClassParameter
{
private int i;
private string s;
[Inject]
public ClassParameter([Parameter(typeof(Named1))] int i, [Parameter(typeof(Named2))] string s)
{
this.i = i;
this.s = s;
}
[NamedParameter]
public class Named1 : Name<int>
{
}
[NamedParameter]
public class Named2 : Name<string>
{
}
}
class ClassWithExternalObject
{
[Inject]
public ClassWithExternalObject(ExternalClass ec)
{
ExternalObject = ec;
}
public ExternalClass ExternalObject { get; set; }
}
class ExternalClass
{
public ExternalClass()
{
}
}
interface IMyOperator<T>
{
string OperatorName { get; }
}
class MyOperatorImpl<T> : IMyOperator<T>
{
[Inject]
public MyOperatorImpl()
{
}
string IMyOperator<T>.OperatorName
{
get { throw new NotImplementedException(); }
}
}
[NamedParameter]
class MessageType : Name<string>
{
}
class MyOperatorTopology<T>
{
[Inject]
public MyOperatorTopology(IMyOperator<T> op)
{
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Resource
{
using System;
using System.Collections.Generic;
using System.Reflection;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Resource;
/// <summary>
/// Resource type descriptor.
/// </summary>
internal class ResourceTypeDescriptor
{
/** Attribute type: InstanceResourceAttribute. */
private static readonly Type TypAttrIgnite = typeof(InstanceResourceAttribute);
/** Attribute type: StoreSessionResourceAttribute. */
private static readonly Type TypAttrStoreSes = typeof(StoreSessionResourceAttribute);
/** Type: IGrid. */
private static readonly Type TypIgnite = typeof(IIgnite);
/** Type: ICacheStoreSession. */
private static readonly Type TypStoreSes = typeof (ICacheStoreSession);
/** Type: ComputeTaskNoResultCacheAttribute. */
private static readonly Type TypComputeTaskNoResCache = typeof(ComputeTaskNoResultCacheAttribute);
/** Cached binding flags. */
private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
/** Ignite injectors. */
private readonly IList<IResourceInjector> _igniteInjectors;
/** Session injectors. */
private readonly IList<IResourceInjector> _storeSesInjectors;
/** Task "no result cache" flag. */
private readonly bool _taskNoResCache;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type">Type.</param>
internal ResourceTypeDescriptor(Type type)
{
Collector gridCollector = new Collector(TypAttrIgnite, TypIgnite);
Collector storeSesCollector = new Collector(TypAttrStoreSes, TypStoreSes);
Type curType = type;
while (curType != null)
{
CreateInjectors(curType, gridCollector, storeSesCollector);
curType = curType.BaseType;
}
_igniteInjectors = gridCollector.Injectors;
_storeSesInjectors = storeSesCollector.Injectors;
_taskNoResCache = ContainsAttribute(type, TypComputeTaskNoResCache, true);
}
/// <summary>
/// Inject resources to the given object.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="ignite">Grid.</param>
public void InjectIgnite(object target, IIgniteInternal ignite)
{
Inject0(target, ignite, _igniteInjectors);
}
/// <summary>
/// Inject store session.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="ses">Store session.</param>
public void InjectStoreSession(object target, ICacheStoreSession ses)
{
Inject0(target, ses, _storeSesInjectors);
}
/// <summary>
/// Perform injection.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="injectee">Injectee.</param>
/// <param name="injectors">Injectors.</param>
private static void Inject0(object target, object injectee, ICollection<IResourceInjector> injectors)
{
if (injectors != null)
{
foreach (IResourceInjector injector in injectors)
injector.Inject(target, injectee);
}
}
/// <summary>
/// Task "no result cache" flag.
/// </summary>
public bool TaskNoResultCache
{
get
{
return _taskNoResCache;
}
}
/// <summary>
/// Create gridInjectors for the given type.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="collectors">Collectors.</param>
private static void CreateInjectors(Type type, params Collector[] collectors)
{
FieldInfo[] fields = type.GetFields(Flags);
foreach (FieldInfo field in fields)
{
foreach (var collector in collectors)
{
if (!ContainsAttribute(field, collector.AttributeType, false))
continue;
if (!field.FieldType.IsAssignableFrom(collector.ResourceType))
throw new IgniteException("Invalid field type for resource attribute [" +
"type=" + type.Name +
", field=" + field.Name +
", fieldType=" + field.FieldType.Name +
", resourceType=" + collector.ResourceType.Name + ']');
collector.Add(new ResourceFieldInjector(field));
}
}
PropertyInfo[] props = type.GetProperties(Flags);
foreach (var prop in props)
{
foreach (var collector in collectors)
{
if (!ContainsAttribute(prop, collector.AttributeType, false))
continue;
if (!prop.CanWrite)
throw new IgniteException("Property with resource attribute is not writable [" +
"type=" + type.Name +
", property=" + prop.Name +
", resourceType=" + collector.ResourceType.Name + ']');
if (!prop.PropertyType.IsAssignableFrom(collector.ResourceType))
throw new IgniteException("Invalid property type for resource attribute [" +
"type=" + type.Name +
", property=" + prop.Name +
", propertyType=" + prop.PropertyType.Name +
", resourceType=" + collector.ResourceType.Name + ']');
collector.Add(new ResourcePropertyInjector(prop));
}
}
MethodInfo[] mthds = type.GetMethods(Flags);
foreach (MethodInfo mthd in mthds)
{
foreach (var collector in collectors)
{
if (!ContainsAttribute(mthd, collector.AttributeType, false))
continue;
ParameterInfo[] parameters = mthd.GetParameters();
if (parameters.Length != 1)
throw new IgniteException("Method with resource attribute must have only one parameter [" +
"type=" + type.Name +
", method=" + mthd.Name +
", resourceType=" + collector.ResourceType.Name + ']');
if (!parameters[0].ParameterType.IsAssignableFrom(collector.ResourceType))
throw new IgniteException("Invalid method parameter type for resource attribute [" +
"type=" + type.Name +
", method=" + mthd.Name +
", methodParameterType=" + parameters[0].ParameterType.Name +
", resourceType=" + collector.ResourceType.Name + ']');
collector.Add(new ResourceMethodInjector(mthd));
}
}
}
/// <summary>
/// Check whether the given member contains the given attribute.
/// </summary>
/// <param name="member">Mmeber.</param>
/// <param name="attrType">Attribute type.</param>
/// <param name="inherit">Inherit flag.</param>
/// <returns>True if contains</returns>
private static bool ContainsAttribute(MemberInfo member, Type attrType, bool inherit)
{
return member.GetCustomAttributes(attrType, inherit).Length > 0;
}
/// <summary>
/// Collector.
/// </summary>
private class Collector
{
/** Attribute type. */
private readonly Type _attrType;
/** Resource type. */
private readonly Type _resType;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="attrType">Atrribute type.</param>
/// <param name="resType">Resource type.</param>
public Collector(Type attrType, Type resType)
{
_attrType = attrType;
_resType = resType;
}
/// <summary>
/// Attribute type.
/// </summary>
public Type AttributeType
{
get { return _attrType; }
}
/// <summary>
/// Resource type.
/// </summary>
public Type ResourceType
{
get { return _resType; }
}
/// <summary>
/// Add injector.
/// </summary>
/// <param name="injector">Injector.</param>
public void Add(IResourceInjector injector)
{
if (Injectors == null)
Injectors = new List<IResourceInjector> { injector };
else
Injectors.Add(injector);
}
/// <summary>
/// Injectors.
/// </summary>
public List<IResourceInjector> Injectors { get; private set; }
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type GroupRequestBuilder.
/// </summary>
public partial class GroupRequestBuilder : DirectoryObjectRequestBuilder, IGroupRequestBuilder
{
/// <summary>
/// Constructs a new GroupRequestBuilder.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public GroupRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
public new IGroupRequest Request()
{
return this.Request(null);
}
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
public new IGroupRequest Request(IEnumerable<Option> options)
{
return new GroupRequest(this.RequestUrl, this.Client, options);
}
/// <summary>
/// Gets the request builder for Members.
/// </summary>
/// <returns>The <see cref="IGroupMembersCollectionWithReferencesRequestBuilder"/>.</returns>
public IGroupMembersCollectionWithReferencesRequestBuilder Members
{
get
{
return new GroupMembersCollectionWithReferencesRequestBuilder(this.AppendSegmentToRequestUrl("members"), this.Client);
}
}
/// <summary>
/// Gets the request builder for MemberOf.
/// </summary>
/// <returns>The <see cref="IGroupMemberOfCollectionWithReferencesRequestBuilder"/>.</returns>
public IGroupMemberOfCollectionWithReferencesRequestBuilder MemberOf
{
get
{
return new GroupMemberOfCollectionWithReferencesRequestBuilder(this.AppendSegmentToRequestUrl("memberOf"), this.Client);
}
}
/// <summary>
/// Gets the request builder for CreatedOnBehalfOf.
/// </summary>
/// <returns>The <see cref="IDirectoryObjectWithReferenceRequestBuilder"/>.</returns>
public IDirectoryObjectWithReferenceRequestBuilder CreatedOnBehalfOf
{
get
{
return new DirectoryObjectWithReferenceRequestBuilder(this.AppendSegmentToRequestUrl("createdOnBehalfOf"), this.Client);
}
}
/// <summary>
/// Gets the request builder for Owners.
/// </summary>
/// <returns>The <see cref="IGroupOwnersCollectionWithReferencesRequestBuilder"/>.</returns>
public IGroupOwnersCollectionWithReferencesRequestBuilder Owners
{
get
{
return new GroupOwnersCollectionWithReferencesRequestBuilder(this.AppendSegmentToRequestUrl("owners"), this.Client);
}
}
/// <summary>
/// Gets the request builder for Threads.
/// </summary>
/// <returns>The <see cref="IGroupThreadsCollectionRequestBuilder"/>.</returns>
public IGroupThreadsCollectionRequestBuilder Threads
{
get
{
return new GroupThreadsCollectionRequestBuilder(this.AppendSegmentToRequestUrl("threads"), this.Client);
}
}
/// <summary>
/// Gets the request builder for Calendar.
/// </summary>
/// <returns>The <see cref="ICalendarRequestBuilder"/>.</returns>
public ICalendarRequestBuilder Calendar
{
get
{
return new CalendarRequestBuilder(this.AppendSegmentToRequestUrl("calendar"), this.Client);
}
}
/// <summary>
/// Gets the request builder for CalendarView.
/// </summary>
/// <returns>The <see cref="IGroupCalendarViewCollectionRequestBuilder"/>.</returns>
public IGroupCalendarViewCollectionRequestBuilder CalendarView
{
get
{
return new GroupCalendarViewCollectionRequestBuilder(this.AppendSegmentToRequestUrl("calendarView"), this.Client);
}
}
/// <summary>
/// Gets the request builder for Events.
/// </summary>
/// <returns>The <see cref="IGroupEventsCollectionRequestBuilder"/>.</returns>
public IGroupEventsCollectionRequestBuilder Events
{
get
{
return new GroupEventsCollectionRequestBuilder(this.AppendSegmentToRequestUrl("events"), this.Client);
}
}
/// <summary>
/// Gets the request builder for Conversations.
/// </summary>
/// <returns>The <see cref="IGroupConversationsCollectionRequestBuilder"/>.</returns>
public IGroupConversationsCollectionRequestBuilder Conversations
{
get
{
return new GroupConversationsCollectionRequestBuilder(this.AppendSegmentToRequestUrl("conversations"), this.Client);
}
}
/// <summary>
/// Gets the request builder for Photo.
/// </summary>
/// <returns>The <see cref="IProfilePhotoRequestBuilder"/>.</returns>
public IProfilePhotoRequestBuilder Photo
{
get
{
return new ProfilePhotoRequestBuilder(this.AppendSegmentToRequestUrl("photo"), this.Client);
}
}
/// <summary>
/// Gets the request builder for AcceptedSenders.
/// </summary>
/// <returns>The <see cref="IGroupAcceptedSendersCollectionRequestBuilder"/>.</returns>
public IGroupAcceptedSendersCollectionRequestBuilder AcceptedSenders
{
get
{
return new GroupAcceptedSendersCollectionRequestBuilder(this.AppendSegmentToRequestUrl("acceptedSenders"), this.Client);
}
}
/// <summary>
/// Gets the request builder for RejectedSenders.
/// </summary>
/// <returns>The <see cref="IGroupRejectedSendersCollectionRequestBuilder"/>.</returns>
public IGroupRejectedSendersCollectionRequestBuilder RejectedSenders
{
get
{
return new GroupRejectedSendersCollectionRequestBuilder(this.AppendSegmentToRequestUrl("rejectedSenders"), this.Client);
}
}
/// <summary>
/// Gets the request builder for Drive.
/// </summary>
/// <returns>The <see cref="IDriveRequestBuilder"/>.</returns>
public IDriveRequestBuilder Drive
{
get
{
return new DriveRequestBuilder(this.AppendSegmentToRequestUrl("drive"), this.Client);
}
}
/// <summary>
/// Gets the request builder for GroupSubscribeByMail.
/// </summary>
/// <returns>The <see cref="IGroupSubscribeByMailRequestBuilder"/>.</returns>
public IGroupSubscribeByMailRequestBuilder SubscribeByMail()
{
return new GroupSubscribeByMailRequestBuilder(
this.AppendSegmentToRequestUrl("microsoft.graph.subscribeByMail"),
this.Client);
}
/// <summary>
/// Gets the request builder for GroupUnsubscribeByMail.
/// </summary>
/// <returns>The <see cref="IGroupUnsubscribeByMailRequestBuilder"/>.</returns>
public IGroupUnsubscribeByMailRequestBuilder UnsubscribeByMail()
{
return new GroupUnsubscribeByMailRequestBuilder(
this.AppendSegmentToRequestUrl("microsoft.graph.unsubscribeByMail"),
this.Client);
}
/// <summary>
/// Gets the request builder for GroupAddFavorite.
/// </summary>
/// <returns>The <see cref="IGroupAddFavoriteRequestBuilder"/>.</returns>
public IGroupAddFavoriteRequestBuilder AddFavorite()
{
return new GroupAddFavoriteRequestBuilder(
this.AppendSegmentToRequestUrl("microsoft.graph.addFavorite"),
this.Client);
}
/// <summary>
/// Gets the request builder for GroupRemoveFavorite.
/// </summary>
/// <returns>The <see cref="IGroupRemoveFavoriteRequestBuilder"/>.</returns>
public IGroupRemoveFavoriteRequestBuilder RemoveFavorite()
{
return new GroupRemoveFavoriteRequestBuilder(
this.AppendSegmentToRequestUrl("microsoft.graph.removeFavorite"),
this.Client);
}
/// <summary>
/// Gets the request builder for GroupResetUnseenCount.
/// </summary>
/// <returns>The <see cref="IGroupResetUnseenCountRequestBuilder"/>.</returns>
public IGroupResetUnseenCountRequestBuilder ResetUnseenCount()
{
return new GroupResetUnseenCountRequestBuilder(
this.AppendSegmentToRequestUrl("microsoft.graph.resetUnseenCount"),
this.Client);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using gView.Framework.IO;
using gView.Framework.system;
using gView.Framework.UI;
using System.Reflection;
using System.IO;
using gView.Framework.Data;
using gView.Framework.Symbology;
using gView.Framework.Carto.Rendering.UI;
namespace gView.Framework.Carto.Rendering
{
[gView.Framework.system.RegisterPlugIn("2F814C8E-A8B7-442a-BB8B-410F2022F89A")]
public class FeatureGroupRenderer : Cloner, IGroupRenderer, IFeatureRenderer, IPropertyPage, ILegendGroup, ISimplify
{
private RendererGroup _renderers;
private bool _useRefScale = true;
public FeatureGroupRenderer()
{
_renderers = new RendererGroup();
}
#region IGroupRenderer
public IRendererGroup Renderers
{
get { return _renderers; }
}
#endregion
#region IFeatureRenderer Member
public void Draw(IDisplay disp, gView.Framework.Data.IFeature feature)
{
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer == null) continue;
renderer.Draw(disp, feature);
}
}
public void FinishDrawing(IDisplay disp, ICancelTracker cancelTracker)
{
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer != null)
renderer.FinishDrawing(disp, cancelTracker);
}
}
public void PrepareQueryFilter(gView.Framework.Data.IFeatureLayer layer, gView.Framework.Data.IQueryFilter filter)
{
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer == null) continue;
renderer.PrepareQueryFilter(layer, filter);
}
}
public bool CanRender(gView.Framework.Data.IFeatureLayer layer, IMap map)
{
return true;
}
public bool HasEffect(IFeatureLayer layer, IMap map)
{
if (_renderers == null) return false;
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer == null) continue;
if (renderer.HasEffect(layer, map)) return true;
}
return false;
}
public bool UseReferenceScale
{
get
{
return _useRefScale;
}
set
{
_useRefScale = value;
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer == null) continue;
renderer.UseReferenceScale = _useRefScale;
}
}
}
public string Name
{
get { return "Renderer Group"; }
}
public string Category
{
get { return "Group"; }
}
#endregion
#region IPersistable Member
public void Load(IPersistStream stream)
{
_useRefScale = (bool)stream.Load("useRefScale", true);
IFeatureRenderer renderer;
while ((renderer = stream.Load("FeatureRenderer", null) as IFeatureRenderer) != null)
{
_renderers.Add(renderer);
}
}
public void Save(IPersistStream stream)
{
stream.Save("useRefScale", _useRefScale);
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer == null) continue;
stream.Save("FeatureRenderer", renderer);
}
}
#endregion
#region IClone2 Member
public object Clone(IDisplay display)
{
FeatureGroupRenderer grouprenderer = new FeatureGroupRenderer();
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer == null) continue;
grouprenderer._renderers.Add(renderer.Clone(display) as IFeatureRenderer);
}
grouprenderer.UseReferenceScale = _useRefScale;
return grouprenderer;
}
public void Release()
{
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer == null) continue;
renderer.Release();
}
_renderers.Clear();
}
#endregion
#region IPropertyPage Member
public object PropertyPage(object initObject)
{
if (!(initObject is IFeatureLayer)) return null;
try
{
string appPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
Assembly uiAssembly = Assembly.LoadFrom(appPath + @"\gView.Carto.Rendering.UI.dll");
IPropertyPanel p = uiAssembly.CreateInstance("gView.Framework.Carto.Rendering.UI.PropertyForm_FeatureGroupRenderer") as IPropertyPanel;
if (p != null)
{
return p.PropertyPanel(this, (IFeatureLayer)initObject);
}
}
catch (Exception ex)
{
}
return null;
}
public object PropertyPageObject()
{
return this;
}
#endregion
#region ILegendGroup Member
public int LegendItemCount
{
get
{
int count = 0;
foreach (IFeatureRenderer renderer in _renderers)
{
if (!(renderer is ILegendGroup)) continue;
count += ((ILegendGroup)renderer).LegendItemCount;
}
return count;
}
}
public ILegendItem LegendItem(int index)
{
int count = 0;
foreach (IFeatureRenderer renderer in _renderers)
{
if (!(renderer is ILegendGroup)) continue;
if (count + ((ILegendGroup)renderer).LegendItemCount > index)
{
return ((ILegendGroup)renderer).LegendItem(index - count);
}
count += ((ILegendGroup)renderer).LegendItemCount;
}
return null;
}
public void SetSymbol(ILegendItem item, ISymbol symbol)
{
foreach (IFeatureRenderer renderer in _renderers)
{
if (!(renderer is ILegendGroup)) continue;
int count = ((ILegendGroup)renderer).LegendItemCount;
for (int i = 0; i < count; i++)
{
if (((ILegendGroup)renderer).LegendItem(i) == item)
{
((ILegendGroup)renderer).SetSymbol(item, symbol);
return;
}
}
}
}
#endregion
private class RendererGroup : List<IFeatureRenderer>, IRendererGroup
{
}
#region IRenderer Member
public List<ISymbol> Symbols
{
get
{
List<ISymbol> symbols = new List<ISymbol>();
if (_renderers != null)
{
foreach (IRenderer renderer in _renderers)
{
if (renderer == null) continue;
symbols.AddRange(renderer.Symbols);
}
}
return symbols;
}
}
public bool Combine(IRenderer renderer)
{
return false;
}
#endregion
#region ISimplify Member
public void Simplify()
{
if (_renderers == null || _renderers.Count == 0)
return;
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer is ISimplify)
((ISimplify)renderer).Simplify();
}
#region SimpleRenderer zusammenfassen
bool allSimpleRenderers = true;
foreach (IRenderer renderer in _renderers)
{
if (!(renderer is SimpleRenderer))
{
allSimpleRenderers = false;
break;
}
}
if (allSimpleRenderers)
{
IFeatureRenderer renderer = _renderers[0];
if (_renderers.Count > 1)
{
ISymbolCollection symCol = PlugInManager.Create(new Guid("062AD1EA-A93C-4c3c-8690-830E65DC6D91")) as ISymbolCollection;
foreach (IRenderer sRenderer in _renderers)
{
if (((SimpleRenderer)renderer).Symbol != null)
symCol.AddSymbol(((SimpleRenderer)renderer).Symbol);
}
((SimpleRenderer)renderer).Symbol = (ISymbol)symCol;
_renderers.Clear();
_renderers.Add(renderer);
}
}
#endregion
#region Combine Renderers
for (int i = 0; i < _renderers.Count; i++)
{
for (int j = i + 1; j < _renderers.Count; j++)
{
if (_renderers[i].Combine(_renderers[j]))
{
_renderers.RemoveAt(j);
j--;
}
}
}
#endregion
}
#endregion
}
}
| |
// 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 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualNetworksOperations operations.
/// </summary>
public partial interface IVirtualNetworksOperations
{
/// <summary>
/// Deletes the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified virtual network by resource group.
/// </summary>
/// <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='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetwork>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a virtual network in the specified resource
/// group.
/// </summary>
/// <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='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetwork>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual networks in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual networks in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Checks whether a private IP address is available for use.
/// </summary>
/// <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='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPAddressAvailabilityResult>> CheckIPAddressAvailabilityWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string ipAddress = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a virtual network in the specified resource
/// group.
/// </summary>
/// <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='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetwork>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual networks in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual networks in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//
// 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 2011, 2012 Xamarin Inc
//
using System;
using System.Collections;
using System.Collections.Generic;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public partial class NSMutableDictionary : IDictionary, IDictionary<NSObject, NSObject> {
// some API, like SecItemCopyMatching, returns a retained NSMutableDictionary
internal NSMutableDictionary (IntPtr handle, bool owns)
: base (handle)
{
if (!owns)
Release ();
}
public static NSMutableDictionary FromObjectsAndKeys (NSObject [] objects, NSObject [] keys)
{
if (objects.Length != keys.Length)
throw new ArgumentException ("objects and keys arrays have different sizes");
var no = NSArray.FromNSObjects (objects);
var nk = NSArray.FromNSObjects (keys);
var r = FromObjectsAndKeysInternal (no, nk);
no.Dispose ();
nk.Dispose ();
return r;
}
public static NSMutableDictionary FromObjectsAndKeys (object [] objects, object [] keys)
{
if (objects.Length != keys.Length)
throw new ArgumentException ("objects and keys arrays have different sizes");
var no = NSArray.FromObjects (objects);
var nk = NSArray.FromObjects (keys);
var r = FromObjectsAndKeysInternal (no, nk);
no.Dispose ();
nk.Dispose ();
return r;
}
public static NSMutableDictionary FromObjectsAndKeys (NSObject [] objects, NSObject [] keys, int count)
{
if (objects.Length != keys.Length)
throw new ArgumentException ("objects and keys arrays have different sizes");
if (count < 1 || objects.Length < count || keys.Length < count)
throw new ArgumentException ("count");
var no = NSArray.FromNSObjects (objects);
var nk = NSArray.FromNSObjects (keys);
var r = FromObjectsAndKeysInternal (no, nk);
no.Dispose ();
nk.Dispose ();
return r;
}
public static NSMutableDictionary FromObjectsAndKeys (object [] objects, object [] keys, int count)
{
if (objects.Length != keys.Length)
throw new ArgumentException ("objects and keys arrays have different sizes");
if (count < 1 || objects.Length < count || keys.Length < count)
throw new ArgumentException ("count");
var no = NSArray.FromObjects (objects);
var nk = NSArray.FromObjects (keys);
var r = FromObjectsAndKeysInternal (no, nk);
no.Dispose ();
nk.Dispose ();
return r;
}
#region ICollection<KeyValuePair<NSObject, NSObject>>
void ICollection<KeyValuePair<NSObject, NSObject>>.Add (KeyValuePair<NSObject, NSObject> item)
{
SetObject (item.Value, item.Key);
}
public void Clear ()
{
RemoveAllObjects ();
}
bool ICollection<KeyValuePair<NSObject, NSObject>>.Contains (KeyValuePair<NSObject, NSObject> keyValuePair)
{
return ContainsKeyValuePair (keyValuePair);
}
void ICollection<KeyValuePair<NSObject, NSObject>>.CopyTo (KeyValuePair<NSObject, NSObject>[] array, int index)
{
if (array == null)
throw new ArgumentNullException ("array");
if (index < 0)
throw new ArgumentOutOfRangeException ("index");
// we want no exception for index==array.Length && Count == 0
if (index > array.Length)
throw new ArgumentException ("index larger than largest valid index of array");
if (array.Length - index < Count)
throw new ArgumentException ("Destination array cannot hold the requested elements!");
var e = GetEnumerator ();
while (e.MoveNext ())
array [index++] = e.Current;
}
bool ICollection<KeyValuePair<NSObject, NSObject>>.Remove (KeyValuePair<NSObject, NSObject> keyValuePair)
{
var count = Count;
RemoveObjectForKey (keyValuePair.Key);
return count != Count;
}
int ICollection<KeyValuePair<NSObject, NSObject>>.Count {
get {return (int) Count;}
}
bool ICollection<KeyValuePair<NSObject, NSObject>>.IsReadOnly {
get {return false;}
}
#endregion
#region IDictionary
void IDictionary.Add (object key, object value)
{
var nsokey = key as NSObject;
var nsovalue = value as NSObject;
if (nsokey == null || nsovalue == null)
throw new ArgumentException ("You can only use NSObjects for keys and values in an NSMutableDictionary");
// Inverted args
SetObject (nsovalue, nsokey);
}
bool IDictionary.Contains (object key)
{
if (key == null)
throw new ArgumentNullException ("key");
NSObject _key = key as NSObject;
if (_key == null)
return false;
return ContainsKey (_key);
}
IDictionaryEnumerator IDictionary.GetEnumerator ()
{
return new ShimEnumerator (this);
}
[Serializable]
class ShimEnumerator : IDictionaryEnumerator, IEnumerator {
IEnumerator<KeyValuePair<NSObject, NSObject>> e;
public ShimEnumerator (NSMutableDictionary host)
{
e = host.GetEnumerator ();
}
public void Dispose ()
{
e.Dispose ();
}
public bool MoveNext ()
{
return e.MoveNext ();
}
public DictionaryEntry Entry {
get { return new DictionaryEntry { Key = e.Current.Key, Value = e.Current.Value }; }
}
public object Key {
get { return e.Current.Key; }
}
public object Value {
get { return e.Current.Value; }
}
public object Current {
get {return Entry;}
}
public void Reset ()
{
e.Reset ();
}
}
void IDictionary.Remove (object key)
{
if (key == null)
throw new ArgumentNullException ("key");
var nskey = key as NSObject;
if (nskey == null)
throw new ArgumentException ("The key must be an NSObject");
RemoveObjectForKey (nskey);
}
bool IDictionary.IsFixedSize {
get {return false;}
}
bool IDictionary.IsReadOnly {
get {return false;}
}
object IDictionary.this [object key] {
get {
NSObject _key = key as NSObject;
if (_key == null)
return null;
return ObjectForKey (_key);
}
set {
var nsokey = key as NSObject;
var nsovalue = value as NSObject;
if (nsokey == null || nsovalue == null)
throw new ArgumentException ("You can only use NSObjects for keys and values in an NSMutableDictionary");
SetObject (nsovalue, nsokey);
}
}
ICollection IDictionary.Keys {
get {return Keys;}
}
ICollection IDictionary.Values {
get {return Values;}
}
#endregion
#region IDictionary<NSObject, NSObject>
public void Add (NSObject key, NSObject value)
{
// Inverted args.
SetObject (value, key);
}
static readonly NSObject marker = new NSObject ();
public bool Remove (NSObject key)
{
if (key == null)
throw new ArgumentNullException ("key");
var last = Count;
RemoveObjectForKey (key);
return last != Count;
}
public bool TryGetValue (NSObject key, out NSObject value)
{
if (key == null)
throw new ArgumentNullException ("key");
var keys = NSArray.FromNSObjects (new [] {key});
var values = ObjectsForKeys (keys, marker);
if (object.ReferenceEquals (marker, values [0])) {
value = null;
return false;
}
value = values [0];
return true;
}
public override NSObject this [NSObject key] {
get {
if (key == null)
throw new ArgumentNullException ("key");
return ObjectForKey (key);
}
set {
if (key == null)
throw new ArgumentNullException ("key");
if (value == null)
throw new ArgumentNullException ("value");
if (IsDirectBinding) {
MonoMac.ObjCRuntime.Messaging.void_objc_msgSend_IntPtr_IntPtr (this.Handle, selSetObjectForKey_, value.Handle, key.Handle);
} else {
MonoMac.ObjCRuntime.Messaging.void_objc_msgSendSuper_IntPtr_IntPtr (this.SuperHandle, selSetObjectForKey_, value.Handle, key.Handle);
}
}
}
public override NSObject this [NSString key] {
get {
if (key == null)
throw new ArgumentNullException ("key");
return ObjectForKey (key);
}
set {
if (key == null)
throw new ArgumentNullException ("key");
if (value == null)
throw new ArgumentNullException ("value");
if (IsDirectBinding) {
MonoMac.ObjCRuntime.Messaging.void_objc_msgSend_IntPtr_IntPtr (this.Handle, selSetObjectForKey_, value.Handle, key.Handle);
} else {
MonoMac.ObjCRuntime.Messaging.void_objc_msgSendSuper_IntPtr_IntPtr (this.SuperHandle, selSetObjectForKey_, value.Handle, key.Handle);
}
}
}
public override NSObject this [string key] {
get {
if (key == null)
throw new ArgumentNullException ("key");
using (var nss = new NSString (key)){
return ObjectForKey (nss);
}
}
set {
if (key == null)
throw new ArgumentNullException ("key");
if (value == null)
throw new ArgumentNullException ("value");
using (var nss = new NSString (key)){
if (IsDirectBinding) {
MonoMac.ObjCRuntime.Messaging.void_objc_msgSend_IntPtr_IntPtr (this.Handle, selSetObjectForKey_, value.Handle, nss.Handle);
} else {
MonoMac.ObjCRuntime.Messaging.void_objc_msgSendSuper_IntPtr_IntPtr (this.SuperHandle, selSetObjectForKey_, value.Handle, nss.Handle);
}
}
}
}
ICollection<NSObject> IDictionary<NSObject, NSObject>.Keys {
get {return Keys;}
}
ICollection<NSObject> IDictionary<NSObject, NSObject>.Values {
get {return Values;}
}
#endregion
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
public IEnumerator<KeyValuePair<NSObject, NSObject>> GetEnumerator ()
{
foreach (var key in Keys) {
yield return new KeyValuePair<NSObject, NSObject> (key, ObjectForKey (key));
}
}
public static NSMutableDictionary LowlevelFromObjectAndKey (IntPtr obj, IntPtr key)
{
return (NSMutableDictionary) Runtime.GetNSObject (MonoMac.ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (class_ptr, selDictionaryWithObjectForKey_, obj, key));
}
public void LowlevelSetObject (IntPtr obj, IntPtr key)
{
MonoMac.ObjCRuntime.Messaging.void_objc_msgSend_IntPtr_IntPtr (this.Handle, selSetObjectForKey_, obj, key);
}
public void LowlevelSetObject (NSObject obj, IntPtr key)
{
if (obj == null)
throw new ArgumentNullException ("obj");
MonoMac.ObjCRuntime.Messaging.void_objc_msgSend_IntPtr_IntPtr (this.Handle, selSetObjectForKey_, obj.Handle, key);
}
}
}
| |
using ClosedXML.Excel;
using NUnit.Framework;
using System;
using System.Linq;
namespace ClosedXML.Tests.Excel
{
[TestFixture]
public class ColumnTests
{
[Test]
public void ColumnUsed()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Cell(2, 1).SetValue("Test");
ws.Cell(3, 1).SetValue("Test");
IXLRangeColumn fromColumn = ws.Column(1).ColumnUsed();
Assert.AreEqual("A2:A3", fromColumn.RangeAddress.ToStringRelative());
IXLRangeColumn fromRange = ws.Range("A1:A5").FirstColumn().ColumnUsed();
Assert.AreEqual("A2:A3", fromRange.RangeAddress.ToStringRelative());
}
[Test]
public void ColumnsUsedIsFast()
{
using var wb = new XLWorkbook();
var ws = wb.AddWorksheet();
ws.FirstCell().SetValue("Hello world!");
var columnsUsed = ws.Row(1).AsRange().ColumnsUsed();
Assert.AreEqual(1, columnsUsed.Count());
}
[Test]
public void CopyColumn()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Test").Style.Font.SetBold();
ws.FirstColumn().CopyTo(ws.Column(2));
Assert.IsTrue(ws.Cell("B1").Style.Font.Bold);
}
[Test]
public void InsertingColumnsBefore1()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Columns("1,3").Style.Fill.SetBackgroundColor(XLColor.Red);
ws.Column(2).Style.Fill.SetBackgroundColor(XLColor.Yellow);
ws.Cell(2, 2).SetValue("X").Style.Fill.SetBackgroundColor(XLColor.Green);
IXLColumn column1 = ws.Column(1);
IXLColumn column2 = ws.Column(2);
IXLColumn column3 = ws.Column(3);
IXLColumn columnIns = ws.Column(1).InsertColumnsBefore(1).First();
Assert.AreEqual(ws.Style.Fill.BackgroundColor, ws.Column(1).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(ws.Style.Fill.BackgroundColor, ws.Column(1).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(ws.Style.Fill.BackgroundColor, ws.Column(1).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(2).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(2).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(2).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(3).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, ws.Column(3).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(3).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", ws.Column(3).Cell(2).GetString());
Assert.AreEqual(ws.Style.Fill.BackgroundColor, columnIns.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(ws.Style.Fill.BackgroundColor, columnIns.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(ws.Style.Fill.BackgroundColor, columnIns.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, column2.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, column2.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, column2.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", column2.Cell(2).GetString());
}
[Test]
public void InsertingColumnsBefore2()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Columns("1,3").Style.Fill.SetBackgroundColor(XLColor.Red);
ws.Column(2).Style.Fill.SetBackgroundColor(XLColor.Yellow);
ws.Cell(2, 2).SetValue("X").Style.Fill.SetBackgroundColor(XLColor.Green);
IXLColumn column1 = ws.Column(1);
IXLColumn column2 = ws.Column(2);
IXLColumn column3 = ws.Column(3);
IXLColumn columnIns = ws.Column(2).InsertColumnsBefore(1).First();
Assert.AreEqual(XLColor.Red, ws.Column(1).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(1).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(1).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(2).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(2).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(2).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(3).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, ws.Column(3).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(3).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", ws.Column(3).Cell(2).GetString());
Assert.AreEqual(XLColor.Red, columnIns.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, columnIns.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, columnIns.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, column2.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, column2.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, column2.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", column2.Cell(2).GetString());
}
[Test]
public void InsertingColumnsBefore3()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Columns("1,3").Style.Fill.SetBackgroundColor(XLColor.Red);
ws.Column(2).Style.Fill.SetBackgroundColor(XLColor.Yellow);
ws.Cell(2, 2).SetValue("X").Style.Fill.SetBackgroundColor(XLColor.Green);
IXLColumn column1 = ws.Column(1);
IXLColumn column2 = ws.Column(2);
IXLColumn column3 = ws.Column(3);
IXLColumn columnIns = ws.Column(3).InsertColumnsBefore(1).First();
Assert.AreEqual(XLColor.Red, ws.Column(1).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(1).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(1).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(2).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, ws.Column(2).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(2).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(3).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, ws.Column(3).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(3).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", ws.Column(2).Cell(2).GetString());
Assert.AreEqual(XLColor.Yellow, columnIns.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, columnIns.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, columnIns.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, column2.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, column2.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, column2.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", column2.Cell(2).GetString());
}
[Test]
public void NoColumnsUsed()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
Int32 count = 0;
foreach (IXLColumn row in ws.ColumnsUsed())
count++;
foreach (IXLRangeColumn row in ws.Range("A1:C3").ColumnsUsed())
count++;
Assert.AreEqual(0, count);
}
[Test]
public void UngroupFromAll()
{
IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1");
ws.Columns(1, 2).Group();
ws.Columns(1, 2).Ungroup(true);
}
[Test]
public void LastColumnUsed()
{
IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1");
ws.Cell("A1").Value = "A1";
ws.Cell("B1").Value = "B1";
ws.Cell("A2").Value = "A2";
var lastCoUsed = ws.LastColumnUsed().ColumnNumber();
Assert.AreEqual(2, lastCoUsed);
}
[Test]
public void NegativeColumnNumberIsInvalid()
{
var ws = new XLWorkbook().AddWorksheet("Sheet1") as XLWorksheet;
var column = new XLColumn(ws, -1);
Assert.IsFalse(column.RangeAddress.IsValid);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//permutations for (((class_s.a+class_s.b)+class_s.c)+class_s.d)
//(((class_s.a+class_s.b)+class_s.c)+class_s.d)
//(class_s.d+((class_s.a+class_s.b)+class_s.c))
//((class_s.a+class_s.b)+class_s.c)
//(class_s.c+(class_s.a+class_s.b))
//(class_s.a+class_s.b)
//(class_s.b+class_s.a)
//(class_s.a+class_s.b)
//(class_s.b+class_s.a)
//(class_s.a+(class_s.b+class_s.c))
//(class_s.b+(class_s.a+class_s.c))
//(class_s.b+class_s.c)
//(class_s.a+class_s.c)
//((class_s.a+class_s.b)+class_s.c)
//(class_s.c+(class_s.a+class_s.b))
//((class_s.a+class_s.b)+(class_s.c+class_s.d))
//(class_s.c+((class_s.a+class_s.b)+class_s.d))
//(class_s.c+class_s.d)
//((class_s.a+class_s.b)+class_s.d)
//(class_s.a+(class_s.b+class_s.d))
//(class_s.b+(class_s.a+class_s.d))
//(class_s.b+class_s.d)
//(class_s.a+class_s.d)
//(((class_s.a+class_s.b)+class_s.c)+class_s.d)
//(class_s.d+((class_s.a+class_s.b)+class_s.c))
namespace CseTest
{
using System;
public class Test_Main
{
static int Main()
{
int ret = 100;
class_s s = new class_s();
class_s.a = return_int(false, -51);
class_s.b = return_int(false, 86);
class_s.c = return_int(false, 89);
class_s.d = return_int(false, 56);
#if LOOP
do {
#endif
#if TRY
try {
#endif
#if LOOP
do {
for (int i = 0; i < 10; i++) {
#endif
int v1 = (((class_s.a + class_s.b) + class_s.c) + class_s.d);
int v2 = (class_s.d + ((class_s.a + class_s.b) + class_s.c));
int v3 = ((class_s.a + class_s.b) + class_s.c);
int v4 = (class_s.c + (class_s.a + class_s.b));
int v5 = (class_s.a + class_s.b);
int v6 = (class_s.b + class_s.a);
int v7 = (class_s.a + class_s.b);
int v8 = (class_s.b + class_s.a);
int v9 = (class_s.a + (class_s.b + class_s.c));
int v10 = (class_s.b + (class_s.a + class_s.c));
int v11 = (class_s.b + class_s.c);
int v12 = (class_s.a + class_s.c);
int v13 = ((class_s.a + class_s.b) + class_s.c);
int v14 = (class_s.c + (class_s.a + class_s.b));
int v15 = ((class_s.a + class_s.b) + (class_s.c + class_s.d));
int v16 = (class_s.c + ((class_s.a + class_s.b) + class_s.d));
int v17 = (class_s.c + class_s.d);
int v18 = ((class_s.a + class_s.b) + class_s.d);
int v19 = (class_s.a + (class_s.b + class_s.d));
int v20 = (class_s.b + (class_s.a + class_s.d));
int v21 = (class_s.b + class_s.d);
int v22 = (class_s.a + class_s.d);
int v23 = (((class_s.a + class_s.b) + class_s.c) + class_s.d);
int v24 = (class_s.d + ((class_s.a + class_s.b) + class_s.c));
if (v1 != 180)
{
Console.WriteLine("test0: for (((class_s.a+class_s.b)+class_s.c)+class_s.d) failed actual value {0} ", v1);
ret = ret + 1;
}
if (v2 != 180)
{
Console.WriteLine("test1: for (class_s.d+((class_s.a+class_s.b)+class_s.c)) failed actual value {0} ", v2);
ret = ret + 1;
}
if (v3 != 124)
{
Console.WriteLine("test2: for ((class_s.a+class_s.b)+class_s.c) failed actual value {0} ", v3);
ret = ret + 1;
}
if (v4 != 124)
{
Console.WriteLine("test3: for (class_s.c+(class_s.a+class_s.b)) failed actual value {0} ", v4);
ret = ret + 1;
}
if (v5 != 35)
{
Console.WriteLine("test4: for (class_s.a+class_s.b) failed actual value {0} ", v5);
ret = ret + 1;
}
if (v6 != 35)
{
Console.WriteLine("test5: for (class_s.b+class_s.a) failed actual value {0} ", v6);
ret = ret + 1;
}
if (v7 != 35)
{
Console.WriteLine("test6: for (class_s.a+class_s.b) failed actual value {0} ", v7);
ret = ret + 1;
}
if (v8 != 35)
{
Console.WriteLine("test7: for (class_s.b+class_s.a) failed actual value {0} ", v8);
ret = ret + 1;
}
if (v9 != 124)
{
Console.WriteLine("test8: for (class_s.a+(class_s.b+class_s.c)) failed actual value {0} ", v9);
ret = ret + 1;
}
if (v10 != 124)
{
Console.WriteLine("test9: for (class_s.b+(class_s.a+class_s.c)) failed actual value {0} ", v10);
ret = ret + 1;
}
if (v11 != 175)
{
Console.WriteLine("test10: for (class_s.b+class_s.c) failed actual value {0} ", v11);
ret = ret + 1;
}
if (v12 != 38)
{
Console.WriteLine("test11: for (class_s.a+class_s.c) failed actual value {0} ", v12);
ret = ret + 1;
}
if (v13 != 124)
{
Console.WriteLine("test12: for ((class_s.a+class_s.b)+class_s.c) failed actual value {0} ", v13);
ret = ret + 1;
}
if (v14 != 124)
{
Console.WriteLine("test13: for (class_s.c+(class_s.a+class_s.b)) failed actual value {0} ", v14);
ret = ret + 1;
}
if (v15 != 180)
{
Console.WriteLine("test14: for ((class_s.a+class_s.b)+(class_s.c+class_s.d)) failed actual value {0} ", v15);
ret = ret + 1;
}
if (v16 != 180)
{
Console.WriteLine("test15: for (class_s.c+((class_s.a+class_s.b)+class_s.d)) failed actual value {0} ", v16);
ret = ret + 1;
}
if (v17 != 145)
{
Console.WriteLine("test16: for (class_s.c+class_s.d) failed actual value {0} ", v17);
ret = ret + 1;
}
if (v18 != 91)
{
Console.WriteLine("test17: for ((class_s.a+class_s.b)+class_s.d) failed actual value {0} ", v18);
ret = ret + 1;
}
if (v19 != 91)
{
Console.WriteLine("test18: for (class_s.a+(class_s.b+class_s.d)) failed actual value {0} ", v19);
ret = ret + 1;
}
if (v20 != 91)
{
Console.WriteLine("test19: for (class_s.b+(class_s.a+class_s.d)) failed actual value {0} ", v20);
ret = ret + 1;
}
if (v21 != 142)
{
Console.WriteLine("test20: for (class_s.b+class_s.d) failed actual value {0} ", v21);
ret = ret + 1;
}
if (v22 != 5)
{
Console.WriteLine("test21: for (class_s.a+class_s.d) failed actual value {0} ", v22);
ret = ret + 1;
}
if (v23 != 180)
{
Console.WriteLine("test22: for (((class_s.a+class_s.b)+class_s.c)+class_s.d) failed actual value {0} ", v23);
ret = ret + 1;
}
if (v24 != 180)
{
Console.WriteLine("test23: for (class_s.d+((class_s.a+class_s.b)+class_s.c)) failed actual value {0} ", v24);
ret = ret + 1;
}
#if LOOP
}
} while (ret == 1000);
#endif
#if TRY
} finally {
}
#endif
#if LOOP
} while (ret== 1000);
#endif
Console.WriteLine(ret);
return ret;
}
private static int return_int(bool verbose, int input)
{
int ans;
try
{
ans = input;
}
finally
{
if (verbose)
{
Console.WriteLine("returning : ans");
}
}
return ans;
}
}
public class class_s
{
public static volatile int a;
public static volatile int b;
public static volatile int c;
public static volatile int d;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareScalarUnorderedGreaterThanBoolean()
{
var test = new BooleanBinaryOpTest__CompareScalarUnorderedGreaterThanBoolean();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__CompareScalarUnorderedGreaterThanBoolean
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__CompareScalarUnorderedGreaterThanBoolean testClass)
{
var result = Sse.CompareScalarUnorderedGreaterThan(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__CompareScalarUnorderedGreaterThanBoolean testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.CompareScalarUnorderedGreaterThan(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__CompareScalarUnorderedGreaterThanBoolean()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public BooleanBinaryOpTest__CompareScalarUnorderedGreaterThanBoolean()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse.CompareScalarUnorderedGreaterThan(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse.CompareScalarUnorderedGreaterThan(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse.CompareScalarUnorderedGreaterThan(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarUnorderedGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarUnorderedGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarUnorderedGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse.CompareScalarUnorderedGreaterThan(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
fixed (Vector128<Single>* pClsVar2 = &_clsVar2)
{
var result = Sse.CompareScalarUnorderedGreaterThan(
Sse.LoadVector128((Single*)(pClsVar1)),
Sse.LoadVector128((Single*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.CompareScalarUnorderedGreaterThan(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareScalarUnorderedGreaterThan(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareScalarUnorderedGreaterThan(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__CompareScalarUnorderedGreaterThanBoolean();
var result = Sse.CompareScalarUnorderedGreaterThan(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__CompareScalarUnorderedGreaterThanBoolean();
fixed (Vector128<Single>* pFld1 = &test._fld1)
fixed (Vector128<Single>* pFld2 = &test._fld2)
{
var result = Sse.CompareScalarUnorderedGreaterThan(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse.CompareScalarUnorderedGreaterThan(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.CompareScalarUnorderedGreaterThan(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse.CompareScalarUnorderedGreaterThan(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse.CompareScalarUnorderedGreaterThan(
Sse.LoadVector128((Single*)(&test._fld1)),
Sse.LoadVector128((Single*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, bool result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Single[] left, Single[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((left[0] > right[0]) != result)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareScalarUnorderedGreaterThan)}<Boolean>(Vector128<Single>, Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using Afnor.Silverlight.Toolkit.ViewServices;
using EspaceClient.BackOffice.Domaine.Criterias;
using EspaceClient.BackOffice.Domaine.Results;
using EspaceClient.BackOffice.Silverlight.Business.Depots;
using EspaceClient.BackOffice.Silverlight.Business.Interfaces;
using EspaceClient.BackOffice.Silverlight.Business.Loader;
using EspaceClient.BackOffice.Silverlight.ViewModels.Common.Modularity;
using EspaceClient.BackOffice.Silverlight.ViewModels.Administration.Traduction.Tabs.Search;
using EspaceClient.BackOffice.Silverlight.ViewModels.Helper.Traduction;
using EspaceClient.BackOffice.Silverlight.ViewModels.Messages;
using EspaceClient.BackOffice.Silverlight.ViewModels.ModelBuilders.Administration.Traduction;
using nRoute.Components;
using nRoute.Components.Composition;
using nRoute.Components.Messaging;
using OGDC.Silverlight.Toolkit.DataGrid.Manager;
using OGDC.Silverlight.Toolkit.Services.Services;
namespace EspaceClient.BackOffice.Silverlight.ViewModels.Administration.Traduction.Tabs
{
public class SearchViewModel : TabBase, IDisposable
{
private readonly IResourceWrapper _resourceWrapper;
private readonly ILoaderReferentiel _referentiel;
private readonly INotificationViewService _notificationService;
private readonly IDepotTraduction _traductionDepot;
private readonly IModelBuilderDetails _builderDetails;
private ObservableCollection<TraductionResult> _searchResult;
private bool _searchOverflow;
private bool _isLoading;
private ICommand _resetCommand;
private ICommand _searchCommand;
private ICommand _doubleClickCommand;
private DataGridColumnManager _manager;
private SearchEntityViewModel _entity;
protected ChannelObserver<UpdateListMessage> ObserverUpdateList { get; private set; }
[ResolveConstructor]
public SearchViewModel(IResourceWrapper resourceWrapper, IMessenging messengingService, IApplicationContext applicationContext, ILoaderReferentiel referentiel, INotificationViewService notificationService, IDepotTraduction traductionDepot, IModelBuilderDetails builderDetails)
: base(applicationContext, messengingService)
{
_resourceWrapper = resourceWrapper;
_referentiel = referentiel;
_notificationService = notificationService;
_traductionDepot = traductionDepot;
_builderDetails = builderDetails;
InitializeCommands();
InitializeMessenging();
InitializeUI();
}
public DataGridColumnManager DataGridManager
{
get
{
return _manager;
}
set
{
if (_manager != value)
{
_manager = value;
NotifyPropertyChanged(() => DataGridManager);
}
}
}
public ObservableCollection<TraductionResult> SearchResult
{
get
{
return _searchResult;
}
set
{
if (_searchResult != value)
{
_searchResult = value;
NotifyPropertyChanged(() => SearchResult);
}
}
}
public bool SearchOverflow
{
get
{
return _searchOverflow;
}
set
{
if (_searchOverflow != value)
{
_searchOverflow = value;
NotifyPropertyChanged(() => SearchOverflow);
}
}
}
public bool IsLoading
{
get
{
return _isLoading;
}
set
{
if (_isLoading != value)
{
_isLoading = value;
NotifyPropertyChanged(() => IsLoading);
}
}
}
public ICommand ResetCommand
{
get
{
return _resetCommand;
}
set
{
if (_resetCommand != value)
{
_resetCommand = value;
NotifyPropertyChanged(() => ResetCommand);
}
}
}
/// <summary>
/// Command de recherche des personnes.
/// </summary>
public ICommand SearchCommand
{
get { return _searchCommand; }
}
public ICommand DoubleClickCommand
{
get
{
return _doubleClickCommand;
}
}
public SearchEntityViewModel Entity
{
get
{
return _entity;
}
set
{
if (_entity != value)
{
_entity = value;
NotifyPropertyChanged(() => Entity);
}
}
}
private void InitializeCommands()
{
_resetCommand = new ActionCommand(OnReset);
_searchCommand = new ActionCommand(OnSearch);
_doubleClickCommand = new ActionCommand<TraductionResult>(OnDoubleClickCommand);
}
private void InitializeMessenging()
{
ObserverUpdateList = _messengingService.CreateObserver<UpdateListMessage>(Msg =>
{
if (Msg.Type != TypeUpdateList.RechercheReferentiels)
return;
});
ObserverUpdateList.Subscribe(ThreadOption.UIThread);
}
private void InitializeUI()
{
SearchResult = new ObservableCollection<TraductionResult>();
SearchOverflow = false;
IsLoading = false;
Entity = new SearchEntityViewModel(_referentiel);
DataGridManager = new DataGridColumnManager();
}
private void DisposeMessenging()
{
ObserverUpdateList.Unsubscribe();
}
private void OnReset()
{
Entity.Criterias.Reset();
}
private void OnSearch()
{
if (IsLoading)
return;
Entity.Criterias.NotifyAllCheckError(Entity.Criterias);
if (Entity.Criterias.HasErrors)
{
var message = _resourceWrapper.ErrorsResourceManager.GetString("ERROR_CHECK");
_notificationService.ShowNotification(message);
return;
}
var limitValue = _referentiel.Referentiel.Parametres.Where(x => x.Code.Equals("SearchTraductionlLimit")).Select(x => x.Valeur).FirstOrDefault();
var limit = Convert.ToInt32(limitValue);
var criterias = AutoMapper.Mapper.Map<SearchTraductionEntityCriteriasViewModel, SearchTraductionCriteriasDto>(Entity.Criterias);
_traductionDepot.Search(
criterias,
r =>
{
foreach (var P in r)
SearchResult.Add(P);
SearchOverflow = SearchResult.Count == limit;
IsLoading = false;
}, error => _messengingService.Publish(new ErrorMessage(error)));
SearchResult.Clear();
IsLoading = true;
}
private void OnDoubleClickCommand(TraductionResult selected)
{
if (selected != null)
{
TraductionHelper.AddTraductionTab(selected, _messengingService, _applicationContext, _traductionDepot, _builderDetails);
}
}
public void Dispose()
{
DisposeMessenging();
}
public override void OnRefreshTab<EntityType>(long id, Action<EntityType> callback)
{
throw new NotImplementedException();
}
protected override void OnRefreshTabCompleted(Action callback)
{
throw new NotImplementedException();
}
}
}
| |
/*
Copyright (c) 2005-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Diagnostics;
using System.Xml;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
using System.Text;
using PHP.Core;
namespace PHP.Core.Emit
{
/// <summary>
/// Implements generator of XML documentation.
/// </summary>
public sealed class XmlDocFileBuilder
{
/// <summary>
/// Full canonical path to the generated file.
/// </summary>
private string/*!*/ path;
private XmlTextWriter/*!*/ writer;
public XmlDocFileBuilder(string/*!*/ path, string /*!*/assemblyName)
{
Debug.Assert(path != null && assemblyName != null);
this.path = path;
writer = new XmlTextWriter(path, Encoding.UTF8);
writer.WriteStartDocument();
writer.Formatting = Formatting.Indented;
writer.Indentation = 1;
writer.IndentChar = '\t';
writer.WriteStartElement("doc");
// assembly info:
writer.WriteStartElement("assembly");
writer.WriteElementString("name", assemblyName);
writer.WriteEndElement();
writer.WriteStartElement("members");
}
private void StartMember(string/*!*/ id)
{
writer.WriteStartElement("member");
writer.WriteAttributeString("name", id);
}
public void WriteFunction(string/*!*/ clrName, string/*!*/ comment)
{
StartMember(String.Concat("M:", clrName));
ProcessPhpDoc(comment);
writer.WriteEndElement();
}
public void WriteType(string/*!*/ clrName, string/*!*/ comment)
{
StartMember(String.Concat("T:", clrName));
ProcessPhpDoc(comment);
writer.WriteEndElement();
}
public void WriteMethod(string/*!*/ clrName, string/*!*/ comment)
{
StartMember(String.Concat("M:", clrName));
ProcessPhpDoc(comment);
writer.WriteEndElement();
}
public void WriteField(string/*!*/ clrName, string/*!*/ comment)
{
StartMember(String.Concat("F:", clrName));
ProcessPhpDoc(comment);
writer.WriteEndElement();
}
public void WriteClassConstant(string/*!*/ clrName, string/*!*/ comment)
{
StartMember(String.Concat("F:", clrName));
ProcessPhpDoc(comment);
writer.WriteEndElement();
}
public void Dispose()
{
writer.WriteEndElement(); // </members>
writer.WriteEndElement(); // </doc>
writer.WriteEndDocument();
writer.Close();
}
#region PHPdoc Parsing
private void ReadEoln(string/*!*/ str, ref int pos)
{
if (str[pos] == '\n') pos++;
else if (str[pos] == '\r' && str[pos + 1] == '\n') pos += 2;
}
private void ReadSpaces(string/*!*/ str, ref int pos)
{
while (Char.IsWhiteSpace(str, pos) && str[pos] != '\n' && str[pos] != '\r') pos++;
}
private string ReadWord(string/*!*/ str, ref int pos)
{
ReadSpaces(str, ref pos);
int begin = pos;
while (pos < str.Length - 2 && !Char.IsWhiteSpace(str, pos)) pos++;
return str.Substring(begin, pos - begin);
}
private string ReadWord(string/*!*/ str, char first, ref int pos)
{
ReadSpaces(str, ref pos);
if (str[pos] != first) return null;
pos++;
int begin = pos;
while (pos < str.Length - 2 && !Char.IsWhiteSpace(str, pos)) pos++;
return str.Substring(begin, pos - begin);
}
private string ReadLineToken(string/*!*/ str, ref int pos, out bool wholeLine)
{
// eats initial whitespace and optional '*':
ReadSpaces(str, ref pos);
if (str[pos] == '*') pos++;
ReadSpaces(str, ref pos);
// '@' at the beginning of the line means tag:
if (str[pos] == '@')
{
wholeLine = false;
return "";
}
// reads non-whitespace to substring [begin,end] and all whitespace up to the end of the line:
int begin = pos;
int end = pos - 1;
while (pos < str.Length - 2 && str[pos] != '\n' && str[pos] != '\r')
{
// found inlined tag:
// TODO:
// if (str[pos]=='{' && str[pos+1]=='@')
// {
// wholeLine = false;
// return str.Substring(begin,end - begin + 1);
// }
if (!Char.IsWhiteSpace(str[pos])) end = pos;
pos++;
}
ReadEoln(str, ref pos);
wholeLine = true;
Debug.Assert(begin < str.Length);
return str.Substring(begin, end - begin + 1);
}
/// <summary>
/// Reads and writes until empty line or tag appear. Processes inlined tags as well.
/// </summary>
private void ProcessText(string/*!*/ str, ref int pos)
{
bool first_text = true;
for (; ; )
{
bool whole_line;
string line = ReadLineToken(str, ref pos, out whole_line);
if (whole_line)
{
if (line == "") break;
if (!first_text) writer.WriteWhitespace(" "); else first_text = false;
writer.WriteRaw(line);
}
else
{
if (str[pos] == '@') break;
ProcessInlineTag(str, ref pos);
}
}
}
private void ProcessTag(string/*!*/ str, ref int pos)
{
Debug.Assert(str[pos] == '@');
int begin = pos;
string tag = ReadWord(str, '@', ref pos);
Debug.Assert(tag != null);
switch (tag)
{
case "param": // @param type $varname description
{
writer.WriteStartElement("param");
string type = ReadWord(str, ref pos); // TODO: check validity
string name = ReadWord(str, '$', ref pos); // TODO: check validity
if (name == null) name = ""; // TODO
writer.WriteAttributeString("name", name);
writer.WriteAttributeString("type", type);
ProcessText(str, ref pos);
writer.WriteEndElement();
break;
}
case "return": // @return type description
{
writer.WriteStartElement("returns");
string type = ReadWord(str, ref pos); // TODO: check validity
ProcessText(str, ref pos);
writer.WriteEndElement();
break;
}
case "access": // @access [public|protected|private]
// TODO check with real access
break;
case "see": // @see element(,element)*
case "link": // @link url
// TODO
break;
case "version": // @version text
case "copyright": // @copyright text
case "author": // @author text
case "since": // @since text
case "deprecated": // @deprecated text
case "deprec": // @deprec text
case "magic": // @magic text
case "todo": // @todo text
case "exception": // @exception text
case "throws": // @throws text
case "var": // @var type
case "package": // @package text
case "subpackage": // @subpackage text
writer.WriteStartElement(tag);
ProcessText(str, ref pos);
writer.WriteEndElement();
break;
default: // unknown tag: (warning?)
writer.WriteStartElement(tag);
ProcessText(str, ref pos);
writer.WriteEndElement();
break;
}
}
private void ProcessInlineTag(string/*!*/ str, ref int pos)
{
Debug.Assert(str[pos] == '{' && str[pos + 1] == '@');
pos++;
switch (ReadWord(str, '@', ref pos))
{
case "link":
break;
case "see":
break;
}
}
private void ProcessPhpDoc(string/*!*/ comment)
{
const string start_mark = "/**";
const string end_mark = "*/";
const int state_init = -1;
const int state_summary = 0;
const int state_remarks = 1;
const int state_tags = 2;
Debug.Assert(comment != null && comment.Length >= start_mark.Length + end_mark.Length);
Debug.Assert(comment.StartsWith(start_mark) && comment.EndsWith(end_mark));
int pos = start_mark.Length;
int state = state_init;
int last_state = state_init;
bool tag_open = false;
do
{
bool whole_line;
string line = ReadLineToken(comment, ref pos, out whole_line);
if (whole_line)
{
switch (state)
{
case state_init:
if (line != "")
{
last_state = state;
state = state_summary;
goto case state_summary;
}
break;
case state_summary:
if (line != "")
{
if (last_state != state_summary)
{
if (tag_open) writer.WriteEndElement();
writer.WriteStartElement("summary");
tag_open = true;
}
else
{
writer.WriteWhitespace(" ");
}
writer.WriteRaw(line);
last_state = state;
state = state_summary;
}
else
{
// switch to remarks:
last_state = state;
state = state_remarks;
}
break;
case state_remarks:
if (line != "")
{
if (last_state != state_remarks)
{
if (tag_open) writer.WriteEndElement();
writer.WriteStartElement("remarks");
tag_open = true;
}
else
{
writer.WriteWhitespace(" ");
}
writer.WriteRaw(line);
last_state = state;
state = state_summary;
}
break;
case state_tags:
last_state = state;
state = state_remarks;
goto case state_remarks;
}
}
else
{
if (comment[pos] == '@')
{
// close current summary/remarks:
if (tag_open)
{
writer.WriteEndElement();
tag_open = false;
}
// switch to tags:
last_state = state;
state = state_tags;
ProcessTag(comment, ref pos);
}
else
{
ProcessInlineTag(comment, ref pos);
}
}
}
while (pos < comment.Length - 2);
// close any open tag:
if (tag_open) writer.WriteEndElement();
}
#endregion
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion License
using System;
using System.Collections.Generic;
using Irony.Ast;
namespace Irony.Parsing
{
public partial class NonTerminal : BnfTerm
{
#region constructors
public NonTerminal(string name) : base(name, null) // By default display name is null
{ }
public NonTerminal(string name, string errorAlias) : base(name, errorAlias)
{ }
public NonTerminal(string name, string errorAlias, Type nodeType) : base(name, errorAlias, nodeType)
{ }
public NonTerminal(string name, string errorAlias, AstNodeCreator nodeCreator) : base(name, errorAlias, nodeCreator)
{ }
public NonTerminal(string name, Type nodeType) : base(name, null, nodeType)
{ }
public NonTerminal(string name, AstNodeCreator nodeCreator) : base(name, null, nodeCreator)
{ }
public NonTerminal(string name, BnfExpression expression)
: this(name)
{
this.Rule = expression;
}
#endregion constructors
#region properties/fields: Rule, ErrorRule
/// <summary>
/// Separate property for specifying error expressions. This allows putting all such expressions in a separate section
/// in grammar for all non-terminals. However you can still put error expressions in the main Rule property, just like
/// in YACC
/// </summary>
public BnfExpression ErrorRule;
/// <summary>
/// A template for representing ParseTreeNode in the parse tree. Can contain '#{i}' fragments referencing
/// child nodes by index
/// </summary>
public string NodeCaptionTemplate;
public BnfExpression Rule;
/// <summary>
/// Productions are used internally by Parser builder
/// </summary>
internal ProductionList Productions = new ProductionList();
private IntList captionParameters;
/// <summary>
/// Converted template with index list
/// </summary>
private string convertedTemplate;
#endregion properties/fields: Rule, ErrorRule
#region Events: Reduced
/// <summary>
/// Note that Reduced event may be called more than once for a List node
/// </summary>
public event EventHandler<ReducedEventArgs> Reduced;
internal void OnReduced(ParsingContext context, Production reducedProduction, ParseTreeNode resultNode)
{
if (this.Reduced != null)
this.Reduced(this, new ReducedEventArgs(context, reducedProduction, resultNode));
}
#endregion Events: Reduced
#region overrides: ToString, Init
public override void Init(GrammarData grammarData)
{
base.Init(grammarData);
if (!string.IsNullOrEmpty(this.NodeCaptionTemplate))
this.ConvertNodeCaptionTemplate();
}
public override string ToString()
{
return this.Name;
}
#endregion overrides: ToString, Init
#region Grammar hints
/// <summary>
/// Adds a hint at the end of all productions
/// </summary>
/// <param name="hint"></param>
/// <remarks>
/// Contributed by Alexey Yakovlev (yallie)
/// </remarks>
public void AddHintToAll(GrammarHint hint)
{
if (this.Rule == null)
throw new Exception("Rule property must be set on non-terminal before calling AddHintToAll.");
foreach (var plusList in this.Rule.Data)
{
plusList.Add(hint);
}
}
#endregion Grammar hints
#region NodeCaptionTemplate utilities
public string GetNodeCaption(ParseTreeNode node)
{
var paramValues = new string[this.captionParameters.Count];
for (int i = 0; i < this.captionParameters.Count; i++)
{
var childIndex = this.captionParameters[i];
if (childIndex < node.ChildNodes.Count)
{
var child = node.ChildNodes[childIndex];
// If child is a token, then child.ToString returns token.ToString which contains Value + Term;
// In this case we prefer to have Value only
paramValues[i] = (child.Token != null ? child.Token.ValueString : child.ToString());
}
}
var result = string.Format(this.convertedTemplate, paramValues);
return result;
}
/// <summary>
/// We replace original tag '#{i}' (where i is the index of the child node to put here)
/// with the tag '{k}', where k is the number of the parameter. So after conversion the template can
/// be used in string.Format() call, with parameters set to child nodes captions
/// </summary>
private void ConvertNodeCaptionTemplate()
{
this.captionParameters = new IntList();
this.convertedTemplate = this.NodeCaptionTemplate;
var index = 0;
while (index < 100)
{
var strParam = "#{" + index + "}";
if (this.convertedTemplate.Contains(strParam))
{
this.convertedTemplate = this.convertedTemplate.Replace(strParam, "{" + this.captionParameters.Count + "}");
this.captionParameters.Add(index);
}
if (!this.convertedTemplate.Contains("#{"))
return;
index++;
}
}
#endregion NodeCaptionTemplate utilities
}
public class NonTerminalList : List<NonTerminal>
{
public override string ToString()
{
return string.Join(" ", this);
}
}
public class NonTerminalSet : HashSet<NonTerminal>
{
public override string ToString()
{
return string.Join(" ", this);
}
}
internal class IntList : List<int> { }
}
| |
/**
* Least Recently Used cache
* Caches the most recently used items up to the given capacity dumping
* the least used items first
*
* Initial Revision: August 6, 2010 David C. Daeschler
* (c) 2010 InWorldz, LLC.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Text;
namespace OpenSim.Framework
{
/// <summary>
/// Implements a least recently used cache. Basically a linked list with hash indexes and a
/// limited size
///
/// TODO: Implement IDictionary
/// </summary>
public class LRUCache<K, T> : IEnumerable<KeyValuePair<K,T>>
{
public delegate void ItemPurgedDelegate(T item);
public event ItemPurgedDelegate OnItemPurged;
private class KVPComparer<CK, CT> : IEqualityComparer<KeyValuePair<CK, CT>>
{
public bool Equals(KeyValuePair<CK, CT> x, KeyValuePair<CK, CT> y)
{
bool eq = EqualityComparer<CK>.Default.Equals(x.Key, y.Key);
return eq;
}
public int GetHashCode(KeyValuePair<CK, CT> obj)
{
return EqualityComparer<CK>.Default.GetHashCode(obj.Key);
}
}
private C5.HashedLinkedList<KeyValuePair<K,T>> _storage;
private int _capacity;
private Dictionary<K, int> _objectSizes;
private int _totalSize;
private bool _useSizing = false;
/// <summary>
/// A system timer and interval values used to age the cache;
/// </summary>
private Dictionary<K, DateTime> _lastAccessedTime = null;
private int _minSize;
private int _maxAge;
private int _expireInterval;
/// <summary>
/// Constructs an LRUCache with the given maximum size, maximum age and expiration interval
/// </summary>
/// <param name="capacity"></param>
/// <param name="useSizing">Whether or not to use explicit object sizes</param>
/// <param name="minSize">Minimum size in bytes in the cache. Below this level and no aging is performed.</param>
/// <param name="maxAge">The maximum age in milliseconds an an entry should live in cache
/// before it's a candidate to be removed.</param>
/// <param name="expireInterval">Time in milliseconds between checks for expired entries.</param>
public LRUCache(int capacity, bool useSizing = false, int minSize = 0, int maxAge = 0)
{
_storage = new C5.HashedLinkedList<KeyValuePair<K, T>>(new KVPComparer<K, T>());
_capacity = capacity;
_totalSize = 0;
if (useSizing)
{
_objectSizes = new Dictionary<K, int>();
_useSizing = true;
}
_maxAge = maxAge;
_minSize = (minSize <= 0 ? 0 : minSize);
_lastAccessedTime = null;
if (_maxAge > 0)
{
_lastAccessedTime = new Dictionary<K, DateTime>();
}
}
#region TimerDrivenAging
/// <summary>
/// Removes items that have not been accessed in maxAge from the list
/// </summary>
public void Maintain()
{
if (_maxAge == 0) return;
var entries = new List<KeyValuePair<K, T>>();
int entriesSize = 0;
foreach (var entry in _storage)
{
DateTime lastAccess;
if (_lastAccessedTime.TryGetValue(entry.Key, out lastAccess) == false)
continue;
var age = DateTime.Now - lastAccess;
// Check to see if this is a candidate. If not we move on because the cache
// is in LRU order and we would have visited entries that are candidates already
if (age.TotalMilliseconds <= (double)_maxAge)
break;
// See if there is a reserve we are maintaining. If so and we are below it
// we'll break out and clean up. This and subsequent entries should be preserved.
int entrySize = (_useSizing ? _objectSizes[entry.Key] : 1);
if ((RequiredReserve > 0) &&
((Size - (entrySize + entriesSize)) < RequiredReserve))
break;
entriesSize += entrySize;
entries.Add(entry);
}
// Clean up the storage we identified
foreach (var entry in entries)
{
_storage.Remove(entry);
this.AccountForRemoval(entry.Key);
if (this.OnItemPurged != null)
{
OnItemPurged(entry.Value);
}
}
}
#endregion
#region ICollection<T>
/// <summary>
/// Try to return the item that matches the hash of the given item
/// </summary>
/// <param name="item"></param>
/// <param name="foundItem"></param>
/// <returns></returns>
public bool TryGetValue(K key, out T foundItem)
{
KeyValuePair<K, T> kvp = new KeyValuePair<K,T>(key, default(T));
if (_storage.Find(ref kvp))
{
foundItem = kvp.Value;
//readd if we found it to update its position
_storage.Remove(kvp);
_storage.Add(kvp);
if (_lastAccessedTime != null)
{
DateTime accessed;
if (_lastAccessedTime.TryGetValue(key, out accessed))
{
accessed = DateTime.Now;
}
}
return true;
}
else
{
foundItem = default(T);
return false;
}
}
/// <summary>
/// Adds an item/moves an item up in the LRU cache and returns whether or not
/// the item with the given key already existed
/// </summary>
/// <param name="key"></param>
/// <param name="item"></param>
/// <returns>If the object already existed</returns>
public bool Add(K key, T item)
{
return this.Add(key, item, 1);
}
/// <summary>
/// Adds an item/moves an item up in the LRU cache and returns whether or not
/// the item with the given key already existed
/// </summary>
/// <param name="key"></param>
/// <param name="item"></param>
/// <param name="size">Size of the item</param>
/// <returns>If the object already existed</returns>
public bool Add(K key, T item, int size)
{
KeyValuePair<K, T> kvp = new KeyValuePair<K, T>(key, item);
//does this list already contain the item?
//if so remove it so it gets moved to the bottom
bool removed = _storage.Remove(kvp);
//are we at capacity?
if ((!removed) && _totalSize >= _capacity)
{
EnsureCapacity(size);
}
//insert the new item
_storage.Add(kvp);
if (_objectSizes != null)
{
if (_objectSizes.ContainsKey(key)) // replaced
{
_totalSize -= _objectSizes[key];
}
_totalSize += size;
_objectSizes[key] = size;
}
if (_lastAccessedTime != null)
{
_lastAccessedTime.Remove(key);
_lastAccessedTime.Add(key, DateTime.Now);
}
return removed;
}
// Called with _storage already locked
private void EnsureCapacity(int requiredSize)
{
while (this.RemainingCapacity < requiredSize && _storage.Count > 0)
{
//remove the top item
KeyValuePair<K, T> pair = _storage.RemoveFirst();
this.AccountForRemoval(pair.Key);
if (this.OnItemPurged != null)
{
OnItemPurged(pair.Value);
}
}
}
public void Clear()
{
_storage.Clear();
_totalSize = 0;
if (_objectSizes != null) _objectSizes.Clear();
if (_lastAccessedTime != null) _lastAccessedTime.Clear();
}
public bool Contains(K key)
{
KeyValuePair<K, T> kvp = new KeyValuePair<K, T>(key, default(T));
return _storage.Contains(kvp);
}
public int Count
{
get
{
return _storage.Count;
}
}
public int Size
{
get { return _totalSize; }
}
public int RemainingCapacity
{
get { return _capacity - _totalSize; }
}
public int RequiredReserve
{
get { return _minSize; }
}
public bool IsReadOnly
{
get
{
return _storage.IsReadOnly;
}
}
public bool Remove(K key)
{
KeyValuePair<K, T> kvp = new KeyValuePair<K, T>(key, default(T));
if (_storage.Remove(kvp))
{
AccountForRemoval(key);
return true;
}
else
{
return false;
}
}
// Called with _storage already locked
private void AccountForRemoval(K key)
{
if (_objectSizes != null)
{
_totalSize -= _objectSizes[key];
_objectSizes.Remove(key);
}
else
{
_totalSize--;
}
if (_lastAccessedTime != null)
{
_lastAccessedTime.Remove(key);
}
}
#endregion
public IEnumerator<KeyValuePair<K, T>> GetEnumerator()
{
return _storage.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _storage.GetEnumerator();
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////
// Open 3D Model Viewer (open3mod) (v2.0)
// [SceneRendererClassicGl.cs]
// (c) 2012-2015, Open3Mod Contributors
//
// Licensed under the terms and conditions of the 3-clause BSD license. See
// the LICENSE file in the root folder of the repository for the details.
//
// HIS 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.
///////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Assimp;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
namespace open3mod
{
/// <summary>
/// Render a Scene using old-school OpenGl, that is, display lists,
/// matrix stacks and glVertexN-family calls.
/// </summary>
public sealed class SceneRendererClassicGl : SceneRendererShared, ISceneRenderer
{
private int _displayList;
private int _displayListAlpha;
private RenderFlags _lastFlags;
internal SceneRendererClassicGl(Scene owner, Vector3 initposeMin, Vector3 initposeMax)
: base(owner, initposeMin, initposeMax)
{
}
public void Dispose()
{
if (_displayList != 0)
{
GL.DeleteLists(_displayList, 1);
_displayList = 0;
}
if (_displayListAlpha != 0)
{
GL.DeleteLists(_displayListAlpha, 1);
_displayListAlpha = 0;
}
GC.SuppressFinalize(this);
}
#if DEBUG
~SceneRendererClassicGl()
{
// OpenTk is unsafe from here, explicit Dispose() is required.
Debug.Assert(false);
}
#endif
/// <summary>
/// <see cref="ISceneRenderer.Update"/>
/// </summary>
public void Update(double delta)
{
Skinner.Update();
}
/// <summary>
/// <see cref="ISceneRenderer.Render"/>
/// </summary>
public void Render(ICameraController cam, Dictionary<Node, List<Mesh>> visibleMeshesByNode,
bool visibleSetChanged,
bool texturesChanged,
RenderFlags flags,
Renderer renderer)
{
GL.Disable(EnableCap.Texture2D);
GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
GL.Enable(EnableCap.DepthTest);
// set fixed-function lighting parameters
GL.ShadeModel(ShadingModel.Smooth);
GL.LightModel(LightModelParameter.LightModelAmbient, new[] { 0.3f, 0.3f, 0.3f, 1 });
GL.Enable(EnableCap.Lighting);
GL.Enable(EnableCap.Light0);
if (flags.HasFlag(RenderFlags.Wireframe))
{
GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);
}
var tmp = InitposeMax.X - InitposeMin.X;
tmp = Math.Max(InitposeMax.Y - InitposeMin.Y, tmp);
tmp = Math.Max(InitposeMax.Z - InitposeMin.Z, tmp);
var scale = 2.0f / tmp;
// TODO: migrate general scale and this snippet to camcontroller code
if (cam != null)
{
cam.SetPivot(Owner.Pivot * (float)scale);
}
var view = cam == null ? Matrix4.LookAt(0, 10, 5, 0, 0, 0, 0, 1, 0) : cam.GetView();
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadMatrix(ref view);
// light direction
var dir = new Vector3(1, 1, 0);
var mat = renderer.LightRotation;
Vector3.TransformNormal(ref dir, ref mat, out dir);
GL.Light(LightName.Light0, LightParameter.Position, new float[] { dir.X, dir.Y, dir.Z, 0 });
// light color
var col = new Vector3(1, 1, 1);
col *= (0.25f + 1.5f * GraphicsSettings.Default.OutputBrightness / 100.0f) * 1.5f;
GL.Light(LightName.Light0, LightParameter.Diffuse, new float[] { col.X, col.Y, col.Z, 1 });
GL.Light(LightName.Light0, LightParameter.Specular, new float[] { col.X, col.Y, col.Z, 1 });
if (flags.HasFlag(RenderFlags.Shaded))
{
OverlayLightSource.DrawLightSource(dir);
}
GL.Scale(scale, scale, scale);
// If textures changed, we may need to upload some of them to VRAM.
// it is important this happens here and not accidentially while
// compiling a displist.
if (texturesChanged)
{
UploadTextures();
}
GL.PushMatrix();
// Build and cache Gl displaylists and update only when the scene changes.
// when the scene is being animated, this is bad because it changes every
// frame anyway. In this case we don't use a displist.
var animated = Owner.SceneAnimator.IsAnimationActive;
if (_displayList == 0 || visibleSetChanged || texturesChanged || flags != _lastFlags || animated)
{
_lastFlags = flags;
// handle opaque geometry
if (!animated)
{
if (_displayList == 0)
{
_displayList = GL.GenLists(1);
}
GL.NewList(_displayList, ListMode.Compile);
}
var needAlpha = RecursiveRender(Owner.Raw.RootNode, visibleMeshesByNode, flags, animated);
if (flags.HasFlag(RenderFlags.ShowSkeleton))
{
RecursiveRenderNoScale(Owner.Raw.RootNode, visibleMeshesByNode, flags, 1.0f / scale, animated);
}
if (flags.HasFlag(RenderFlags.ShowNormals))
{
RecursiveRenderNormals(Owner.Raw.RootNode, visibleMeshesByNode, flags, 1.0f / scale, animated, Matrix4.Identity);
}
if (!animated)
{
GL.EndList();
}
if (needAlpha)
{
// handle semi-transparent geometry
if (!animated)
{
if (_displayListAlpha == 0)
{
_displayListAlpha = GL.GenLists(1);
}
GL.NewList(_displayListAlpha, ListMode.Compile);
}
RecursiveRenderWithAlpha(Owner.Raw.RootNode, visibleMeshesByNode, flags, animated);
if (!animated)
{
GL.EndList();
}
}
else if (_displayListAlpha != 0)
{
GL.DeleteLists(_displayListAlpha, 1);
_displayListAlpha = 0;
}
}
if (!animated)
{
GL.CallList(_displayList);
if (_displayListAlpha != 0)
{
GL.CallList(_displayListAlpha);
}
}
GL.PopMatrix();
// always switch back to FILL
GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);
GL.Disable(EnableCap.DepthTest);
#if TEST
GL.Enable(EnableCap.ColorMaterial);
// TEST CODE to visualize mid point (pivot) and origin
GL.LoadMatrix(ref view);
GL.Begin(BeginMode.Lines);
GL.Vertex3((InitposeMin + InitposeMax) * 0.5f * (float)scale);
GL.Color3(0.0f, 1.0f, 0.0f);
GL.Vertex3(0,0,0);
GL.Color3(0.0f, 1.0f, 0.0f);
GL.Vertex3((InitposeMin + InitposeMax) * 0.5f * (float)scale);
GL.Color3(0.0f, 1.0f, 0.0f);
GL.Vertex3(10, 10, 10);
GL.Color3(0.0f, 1.0f, 0.0f);
GL.End();
#endif
GL.Disable(EnableCap.Texture2D);
GL.Disable(EnableCap.Lighting);
}
/// <summary>
/// Recursive rendering function
/// </summary>
/// <param name="node">Current node</param>
/// <param name="visibleMeshesByNode"> </param>
/// <param name="flags">Rendering flags</param>
/// <param name="animated">Play animation?</param>
/// <returns>whether there is any need to do a second render pass with alpha blending enabled</returns>
private bool RecursiveRender(Node node,
Dictionary<Node, List<Mesh>> visibleMeshesByNode,
RenderFlags flags, bool animated)
{
var needAlpha = false;
Matrix4 m;
if (animated)
{
Owner.SceneAnimator.GetLocalTransform(node, out m);
}
else
{
m = AssimpToOpenTk.FromMatrix(node.Transform);
}
// TODO for some reason, all OpenTk matrices need a ^T - we should clarify our conventions somewhere
m.Transpose();
GL.PushMatrix();
GL.MultMatrix(ref m);
if (node.HasMeshes)
{
needAlpha = DrawOpaqueMeshes(node, visibleMeshesByNode, flags, animated);
}
for (var i = 0; i < node.ChildCount; i++)
{
needAlpha = RecursiveRender(node.Children[i], visibleMeshesByNode, flags, animated) || needAlpha;
}
GL.PopMatrix();
return needAlpha;
}
/// <summary>
/// Recursive rendering function for semi-transparent (i.e. alpha-blended) meshes.
///
/// Alpha blending is not globally on, meshes need to do that on their own.
///
/// This render function is called _after_ solid geometry has been drawn, so the
/// relative order between transparent and opaque geometry is maintained. There
/// is no further ordering within the alpha rendering pass.
/// </summary>
/// <param name="node">Current node</param>
/// <param name="visibleNodes">Set of visible meshes</param>
/// <param name="flags">Rendering flags</param>
/// <param name="animated">Play animation?</param>
private void RecursiveRenderWithAlpha(Node node, Dictionary<Node, List<Mesh>> visibleNodes,
RenderFlags flags,
bool animated)
{
Matrix4 m;
if (animated)
{
Owner.SceneAnimator.GetLocalTransform(node, out m);
}
else
{
m = AssimpToOpenTk.FromMatrix(node.Transform);
}
// TODO for some reason, all OpenTk matrices need a ^T - clarify our conventions somewhere
m.Transpose();
GL.PushMatrix();
GL.MultMatrix(ref m);
// the following permutations could be compacted into one big loop with lots of
// condition magic, but at the cost of readability and also performance.
// we therefore keep it redundant and stupid.
if (node.HasMeshes)
{
DrawAlphaMeshes(node, visibleNodes, flags, animated);
}
for (var i = 0; i < node.ChildCount; i++)
{
RecursiveRenderWithAlpha(node.Children[i], visibleNodes, flags, animated);
}
GL.PopMatrix();
}
/// <summary>
/// Draw a mesh using either its given material or a transparent "ghost" material.
/// </summary>
/// <param name="node">Current node</param>
/// <param name="animated">Specifies whether animations should be played</param>
/// <param name="showGhost">Indicates whether to substitute the mesh' material with a
/// "ghost" surrogate material that allows looking through the geometry.</param>
/// <param name="index">Mesh index in the scene</param>
/// <param name="mesh">Mesh instance</param>
/// <param name="flags"> </param>
/// <returns></returns>
protected override bool InternDrawMesh(Node node, bool animated, bool showGhost, int index, Mesh mesh, RenderFlags flags)
{
if (showGhost)
{
Owner.MaterialMapper.ApplyGhostMaterial(mesh, Owner.Raw.Materials[mesh.MaterialIndex],
flags.HasFlag(RenderFlags.Shaded));
}
else
{
Owner.MaterialMapper.ApplyMaterial(mesh, Owner.Raw.Materials[mesh.MaterialIndex],
flags.HasFlag(RenderFlags.Textured),
flags.HasFlag(RenderFlags.Shaded));
}
if (GraphicsSettings.Default.BackFaceCulling)
{
GL.FrontFace(FrontFaceDirection.Ccw);
GL.CullFace(CullFaceMode.Back);
GL.Enable(EnableCap.CullFace);
}
else
{
GL.Disable(EnableCap.CullFace);
}
var hasColors = mesh.HasVertexColors(0);
var hasTexCoords = mesh.HasTextureCoords(0);
var skinning = mesh.HasBones && animated;
foreach (var face in mesh.Faces)
{
BeginMode faceMode;
switch (face.IndexCount)
{
case 1:
faceMode = BeginMode.Points;
break;
case 2:
faceMode = BeginMode.Lines;
break;
case 3:
faceMode = BeginMode.Triangles;
break;
default:
faceMode = BeginMode.Polygon;
break;
}
GL.Begin(faceMode);
for (var i = 0; i < face.IndexCount; i++)
{
var indice = face.Indices[i];
if (hasColors)
{
var vertColor = AssimpToOpenTk.FromColor(mesh.VertexColorChannels[0][indice]);
GL.Color4(vertColor);
}
if (mesh.HasNormals)
{
Vector3 normal;
if (skinning)
{
Skinner.GetTransformedVertexNormal(node, mesh, (uint)indice, out normal);
}
else
{
normal = AssimpToOpenTk.FromVector(mesh.Normals[indice]);
}
GL.Normal3(normal);
}
if (hasTexCoords)
{
var uvw = AssimpToOpenTk.FromVector(mesh.TextureCoordinateChannels[0][indice]);
GL.TexCoord2(uvw.X, 1 - uvw.Y);
}
Vector3 pos;
if (skinning)
{
Skinner.GetTransformedVertexPosition(node, mesh, (uint)indice, out pos);
}
else
{
pos = AssimpToOpenTk.FromVector(mesh.Vertices[indice]);
}
GL.Vertex3(pos);
}
GL.End();
}
GL.Disable(EnableCap.CullFace);
return skinning;
}
/// <summary>
/// Recursive render function for drawing opaque geometry with no scaling
/// in the transformation chain. This is used for overlays, such as drawing
/// the skeleton.
/// </summary>
/// <param name="node"></param>
/// <param name="visibleMeshesByNode"></param>
/// <param name="flags"></param>
/// <param name="invGlobalScale"></param>
/// <param name="animated"></param>
private void RecursiveRenderNoScale(Node node, Dictionary<Node, List<Mesh>> visibleMeshesByNode, RenderFlags flags,
float invGlobalScale,
bool animated)
{
// TODO unify our use of OpenTK and Assimp matrices
Matrix4x4 m;
Matrix4 mConv;
if (animated)
{
Owner.SceneAnimator.GetLocalTransform(node, out mConv);
OpenTkToAssimp.FromMatrix(ref mConv, out m);
}
else
{
m = node.Transform;
}
// get rid of the scaling part of the matrix
// TODO this can be done faster and Decompose() doesn't handle
// non positively semi-definite matrices correctly anyway.
Vector3D scaling;
Assimp.Quaternion rotation;
Vector3D translation;
m.Decompose(out scaling, out rotation, out translation);
rotation.Normalize();
m = new Matrix4x4(rotation.GetMatrix()) * Matrix4x4.FromTranslation(translation);
mConv = AssimpToOpenTk.FromMatrix(ref m);
mConv.Transpose();
if (flags.HasFlag(RenderFlags.ShowSkeleton))
{
var highlight = false;
if (visibleMeshesByNode != null)
{
List<Mesh> meshList;
if (visibleMeshesByNode.TryGetValue(node, out meshList) && meshList == null)
{
// If the user hovers over a node in the tab view, all of its descendants
// are added to the visible set as well. This is not the intended
// behavior for skeleton joints, though! Here we only want to show the
// joint corresponding to the node being hovered over.
// Therefore, only highlight nodes whose parents either don't exist
// or are not in the visible set.
if (node.Parent == null || !visibleMeshesByNode.TryGetValue(node.Parent, out meshList) || meshList != null)
{
highlight = true;
}
}
}
OverlaySkeleton.DrawSkeletonBone(node, invGlobalScale,highlight);
}
GL.PushMatrix();
GL.MultMatrix(ref mConv);
for (int i = 0; i < node.ChildCount; i++)
{
RecursiveRenderNoScale(node.Children[i], visibleMeshesByNode, flags, invGlobalScale, animated);
}
GL.PopMatrix();
}
/// <summary>
/// Recursive render function for drawing normals with a constant size.
/// </summary>
/// <param name="node"></param>
/// <param name="visibleMeshesByNode"></param>
/// <param name="flags"></param>
/// <param name="invGlobalScale"></param>
/// <param name="animated"></param>
/// <param name="transform"></param>
private void RecursiveRenderNormals(Node node, Dictionary<Node, List<Mesh>> visibleMeshesByNode, RenderFlags flags,
float invGlobalScale,
bool animated,
Matrix4 transform)
{
// TODO unify our use of OpenTK and Assimp matrices
Matrix4 mConv;
if (animated)
{
Owner.SceneAnimator.GetLocalTransform(node, out mConv);
}
else
{
Matrix4x4 m = node.Transform;
mConv = AssimpToOpenTk.FromMatrix(ref m);
}
mConv.Transpose();
// The normal's position and direction are transformed differently, so we manually track the transform.
transform = mConv * transform;
if (flags.HasFlag(RenderFlags.ShowNormals))
{
List<Mesh> meshList = null;
if (node.HasMeshes &&
(visibleMeshesByNode == null || visibleMeshesByNode.TryGetValue(node, out meshList)))
{
foreach (var index in node.MeshIndices)
{
var mesh = Owner.Raw.Meshes[index];
if (meshList != null && !meshList.Contains(mesh))
{
continue;
}
OverlayNormals.DrawNormals(node, index, mesh, mesh.HasBones && animated ? Skinner : null, invGlobalScale, transform);
}
}
}
for (int i = 0; i < node.ChildCount; i++)
{
RecursiveRenderNormals(node.Children[i], visibleMeshesByNode, flags, invGlobalScale, animated, transform);
}
}
}
}
/* vi: set shiftwidth=4 tabstop=4: */
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class AbstractKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AtRoot_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClass_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalStatement_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalVariableDeclaration_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInEmptyStatement()
{
VerifyAbsence(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCompilationUnit()
{
VerifyKeyword(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterExtern()
{
VerifyKeyword(
@"extern alias Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterUsing()
{
VerifyKeyword(
@"using Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNamespace()
{
VerifyKeyword(
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterTypeDeclaration()
{
VerifyKeyword(
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateDeclaration()
{
VerifyKeyword(
@"delegate void Foo();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodInClass()
{
VerifyKeyword(
@"class C {
void Foo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterFieldInClass()
{
VerifyKeyword(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPropertyInClass()
{
VerifyKeyword(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotBeforeUsing()
{
VerifyAbsence(SourceCodeKind.Regular,
@"$$
using Foo;");
}
[WpfFact(Skip = "528041"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotBeforeUsing_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"$$
using Foo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAssemblyAttribute()
{
VerifyKeyword(
@"[assembly: foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterRootAttribute()
{
VerifyKeyword(
@"[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAttribute()
{
VerifyKeyword(
@"class C {
[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideStruct()
{
VerifyKeyword(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInsideInterface()
{
VerifyAbsence(@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideClass()
{
VerifyKeyword(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPartial()
{
VerifyAbsence(@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterAbstract()
{
VerifyAbsence(@"abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterInternal()
{
VerifyKeyword(
@"internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPublic()
{
VerifyKeyword(
@"public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterStaticInternal()
{
VerifyAbsence(@"static internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterInternalStatic()
{
VerifyAbsence(@"internal static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterInvalidInternal()
{
VerifyAbsence(@"virtual internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterClass()
{
VerifyAbsence(@"class $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPrivate()
{
VerifyKeyword(
@"private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterSealed()
{
VerifyAbsence(@"sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterStatic()
{
VerifyAbsence(@"static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedStatic()
{
VerifyAbsence(@"class C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedInternal()
{
VerifyKeyword(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterDelegate()
{
VerifyAbsence(@"delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedAbstract()
{
VerifyAbsence(@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedVirtual()
{
VerifyAbsence(@"class C {
virtual $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedSealed()
{
VerifyAbsence(@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInProperty()
{
VerifyAbsence(
@"class C {
int Foo { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPropertyAfterAccessor()
{
VerifyAbsence(
@"class C {
int Foo { get; $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPropertyAfterAccessibility()
{
VerifyAbsence(
@"class C {
int Foo { get; protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPropertyAfterInternal()
{
VerifyAbsence(
@"class C {
int Foo { get; internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterOverride()
{
VerifyKeyword(
@"class C {
override $$");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows.Input;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.VisualTree;
#nullable enable
namespace Avalonia.Controls
{
/// <summary>
/// A menu item control.
/// </summary>
[PseudoClasses(":separator", ":icon", ":open", ":pressed", ":selected")]
public class MenuItem : HeaderedSelectingItemsControl, IMenuItem, ISelectable
{
/// <summary>
/// Defines the <see cref="Command"/> property.
/// </summary>
public static readonly DirectProperty<MenuItem, ICommand?> CommandProperty =
Button.CommandProperty.AddOwner<MenuItem>(
menuItem => menuItem.Command,
(menuItem, command) => menuItem.Command = command,
enableDataValidation: true);
/// <summary>
/// Defines the <see cref="HotKey"/> property.
/// </summary>
public static readonly StyledProperty<KeyGesture> HotKeyProperty =
HotKeyManager.HotKeyProperty.AddOwner<MenuItem>();
/// <summary>
/// Defines the <see cref="CommandParameter"/> property.
/// </summary>
public static readonly StyledProperty<object> CommandParameterProperty =
Button.CommandParameterProperty.AddOwner<MenuItem>();
/// <summary>
/// Defines the <see cref="Icon"/> property.
/// </summary>
public static readonly StyledProperty<object> IconProperty =
AvaloniaProperty.Register<MenuItem, object>(nameof(Icon));
/// <summary>
/// Defines the <see cref="InputGesture"/> property.
/// </summary>
public static readonly StyledProperty<KeyGesture> InputGestureProperty =
AvaloniaProperty.Register<MenuItem, KeyGesture>(nameof(InputGesture));
/// <summary>
/// Defines the <see cref="IsSelected"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsSelectedProperty =
ListBoxItem.IsSelectedProperty.AddOwner<MenuItem>();
/// <summary>
/// Defines the <see cref="IsSubMenuOpen"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsSubMenuOpenProperty =
AvaloniaProperty.Register<MenuItem, bool>(nameof(IsSubMenuOpen));
/// <summary>
/// Defines the <see cref="Click"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> ClickEvent =
RoutedEvent.Register<MenuItem, RoutedEventArgs>(nameof(Click), RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="PointerEnterItem"/> event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerEnterItemEvent =
RoutedEvent.Register<InputElement, PointerEventArgs>(nameof(PointerEnterItem), RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="PointerLeaveItem"/> event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerLeaveItemEvent =
RoutedEvent.Register<InputElement, PointerEventArgs>(nameof(PointerLeaveItem), RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="SubmenuOpened"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> SubmenuOpenedEvent =
RoutedEvent.Register<MenuItem, RoutedEventArgs>(nameof(SubmenuOpened), RoutingStrategies.Bubble);
/// <summary>
/// The default value for the <see cref="ItemsControl.ItemsPanel"/> property.
/// </summary>
private static readonly ITemplate<IPanel> DefaultPanel =
new FuncTemplate<IPanel>(() => new StackPanel());
private ICommand? _command;
private bool _commandCanExecute = true;
private Popup? _popup;
/// <summary>
/// Initializes static members of the <see cref="MenuItem"/> class.
/// </summary>
static MenuItem()
{
SelectableMixin.Attach<MenuItem>(IsSelectedProperty);
PressedMixin.Attach<MenuItem>();
CommandProperty.Changed.Subscribe(CommandChanged);
FocusableProperty.OverrideDefaultValue<MenuItem>(true);
HeaderProperty.Changed.AddClassHandler<MenuItem>((x, e) => x.HeaderChanged(e));
IconProperty.Changed.AddClassHandler<MenuItem>((x, e) => x.IconChanged(e));
IsSelectedProperty.Changed.AddClassHandler<MenuItem>((x, e) => x.IsSelectedChanged(e));
ItemsPanelProperty.OverrideDefaultValue<MenuItem>(DefaultPanel);
ClickEvent.AddClassHandler<MenuItem>((x, e) => x.OnClick(e));
SubmenuOpenedEvent.AddClassHandler<MenuItem>((x, e) => x.OnSubmenuOpened(e));
IsSubMenuOpenProperty.Changed.AddClassHandler<MenuItem>((x, e) => x.SubMenuOpenChanged(e));
}
public MenuItem()
{
// HACK: This nasty but it's all WPF's fault. Grid uses an inherited attached
// property to store SharedSizeGroup state, except property inheritance is done
// down the logical tree. In this case, the control which is setting
// Grid.IsSharedSizeScope="True" is not in the logical tree. Instead of fixing
// the way Grid stores shared size state, the developers of WPF just created a
// binding of the internal state of the visual parent to the menu item. We don't
// have much choice but to do the same for now unless we want to refactor Grid,
// which I honestly am not brave enough to do right now. Here's the same hack in
// the WPF codebase:
//
// https://github.com/dotnet/wpf/blob/89537909bdf36bc918e88b37751add46a8980bb0/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/MenuItem.cs#L2126-L2141
//
// In addition to the hack from WPF, we also make sure to return null when we have
// no parent. If we don't do this, inheritance falls back to the logical tree,
// causing the shared size scope in the parent MenuItem to be used, breaking
// menu layout.
var parentSharedSizeScope = this.GetObservable(VisualParentProperty)
.SelectMany(x =>
{
var parent = x as Control;
return parent?.GetObservable(DefinitionBase.PrivateSharedSizeScopeProperty) ??
Observable.Return<DefinitionBase.SharedSizeScope?>(null);
});
this.Bind(DefinitionBase.PrivateSharedSizeScopeProperty, parentSharedSizeScope);
}
/// <summary>
/// Occurs when a <see cref="MenuItem"/> without a submenu is clicked.
/// </summary>
public event EventHandler<RoutedEventArgs> Click
{
add { AddHandler(ClickEvent, value); }
remove { RemoveHandler(ClickEvent, value); }
}
/// <summary>
/// Occurs when the pointer enters a menu item.
/// </summary>
/// <remarks>
/// A bubbling version of the <see cref="InputElement.PointerEnter"/> event for menu items.
/// </remarks>
public event EventHandler<PointerEventArgs> PointerEnterItem
{
add { AddHandler(PointerEnterItemEvent, value); }
remove { RemoveHandler(PointerEnterItemEvent, value); }
}
/// <summary>
/// Raised when the pointer leaves a menu item.
/// </summary>
/// <remarks>
/// A bubbling version of the <see cref="InputElement.PointerLeave"/> event for menu items.
/// </remarks>
public event EventHandler<PointerEventArgs> PointerLeaveItem
{
add { AddHandler(PointerLeaveItemEvent, value); }
remove { RemoveHandler(PointerLeaveItemEvent, value); }
}
/// <summary>
/// Occurs when a <see cref="MenuItem"/>'s submenu is opened.
/// </summary>
public event EventHandler<RoutedEventArgs> SubmenuOpened
{
add { AddHandler(SubmenuOpenedEvent, value); }
remove { RemoveHandler(SubmenuOpenedEvent, value); }
}
/// <summary>
/// Gets or sets the command associated with the menu item.
/// </summary>
public ICommand? Command
{
get { return _command; }
set { SetAndRaise(CommandProperty, ref _command, value); }
}
/// <summary>
/// Gets or sets an <see cref="KeyGesture"/> associated with this control
/// </summary>
public KeyGesture HotKey
{
get { return GetValue(HotKeyProperty); }
set { SetValue(HotKeyProperty, value); }
}
/// <summary>
/// Gets or sets the parameter to pass to the <see cref="Command"/> property of a
/// <see cref="MenuItem"/>.
/// </summary>
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
/// <summary>
/// Gets or sets the icon that appears in a <see cref="MenuItem"/>.
/// </summary>
public object Icon
{
get { return GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
/// <summary>
/// Gets or sets the input gesture that will be displayed in the menu item.
/// </summary>
/// <remarks>
/// Setting this property does not cause the input gesture to be handled by the menu item,
/// it simply displays the gesture text in the menu.
/// </remarks>
public KeyGesture InputGesture
{
get { return GetValue(InputGestureProperty); }
set { SetValue(InputGestureProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the <see cref="MenuItem"/> is currently selected.
/// </summary>
public bool IsSelected
{
get { return GetValue(IsSelectedProperty); }
set { SetValue(IsSelectedProperty, value); }
}
/// <summary>
/// Gets or sets a value that indicates whether the submenu of the <see cref="MenuItem"/> is
/// open.
/// </summary>
public bool IsSubMenuOpen
{
get { return GetValue(IsSubMenuOpenProperty); }
set { SetValue(IsSubMenuOpenProperty, value); }
}
/// <summary>
/// Gets or sets a value that indicates whether the <see cref="MenuItem"/> has a submenu.
/// </summary>
public bool HasSubMenu => !Classes.Contains(":empty");
/// <summary>
/// Gets a value that indicates whether the <see cref="MenuItem"/> is a top-level main menu item.
/// </summary>
public bool IsTopLevel => Parent is Menu;
/// <inheritdoc/>
bool IMenuItem.IsPointerOverSubMenu => _popup?.IsPointerOverPopup ?? false;
/// <inheritdoc/>
IMenuElement? IMenuItem.Parent => Parent as IMenuElement;
protected override bool IsEnabledCore => base.IsEnabledCore && _commandCanExecute;
/// <inheritdoc/>
bool IMenuElement.MoveSelection(NavigationDirection direction, bool wrap) => MoveSelection(direction, wrap);
/// <inheritdoc/>
IMenuItem? IMenuElement.SelectedItem
{
get
{
var index = SelectedIndex;
return (index != -1) ?
(IMenuItem)ItemContainerGenerator.ContainerFromIndex(index) :
null;
}
set
{
SelectedIndex = ItemContainerGenerator.IndexFromContainer(value);
}
}
/// <inheritdoc/>
IEnumerable<IMenuItem> IMenuElement.SubItems
{
get
{
return ItemContainerGenerator.Containers
.Select(x => x.ContainerControl)
.OfType<IMenuItem>();
}
}
/// <summary>
/// Opens the submenu.
/// </summary>
/// <remarks>
/// This has the same effect as setting <see cref="IsSubMenuOpen"/> to true.
/// </remarks>
public void Open() => IsSubMenuOpen = true;
/// <summary>
/// Closes the submenu.
/// </summary>
/// <remarks>
/// This has the same effect as setting <see cref="IsSubMenuOpen"/> to false.
/// </remarks>
public void Close() => IsSubMenuOpen = false;
/// <inheritdoc/>
void IMenuItem.RaiseClick() => RaiseEvent(new RoutedEventArgs(ClickEvent));
/// <inheritdoc/>
protected override IItemContainerGenerator CreateItemContainerGenerator()
{
return new MenuItemContainerGenerator(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (Command != null)
{
Command.CanExecuteChanged += CanExecuteChanged;
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (Command != null)
{
Command.CanExecuteChanged -= CanExecuteChanged;
}
}
/// <summary>
/// Called when the <see cref="MenuItem"/> is clicked.
/// </summary>
/// <param name="e">The click event args.</param>
protected virtual void OnClick(RoutedEventArgs e)
{
if (!e.Handled && Command?.CanExecute(CommandParameter) == true)
{
Command.Execute(CommandParameter);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
e.Handled = UpdateSelectionFromEventSource(e.Source, true);
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
// Don't handle here: let event bubble up to menu.
}
/// <inheritdoc/>
protected override void OnPointerEnter(PointerEventArgs e)
{
base.OnPointerEnter(e);
var point = e.GetCurrentPoint(null);
RaiseEvent(new PointerEventArgs(PointerEnterItemEvent, this, e.Pointer, this.VisualRoot, point.Position,
e.Timestamp, point.Properties, e.KeyModifiers));
}
/// <inheritdoc/>
protected override void OnPointerLeave(PointerEventArgs e)
{
base.OnPointerLeave(e);
var point = e.GetCurrentPoint(null);
RaiseEvent(new PointerEventArgs(PointerLeaveItemEvent, this, e.Pointer, this.VisualRoot, point.Position,
e.Timestamp, point.Properties, e.KeyModifiers));
}
/// <summary>
/// Called when a submenu is opened on this MenuItem or a child MenuItem.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnSubmenuOpened(RoutedEventArgs e)
{
var menuItem = e.Source as MenuItem;
if (menuItem != null && menuItem.Parent == this)
{
foreach (var child in ((IMenuItem)this).SubItems)
{
if (child != menuItem && child.IsSubMenuOpen)
{
child.IsSubMenuOpen = false;
}
}
}
}
/// <inheritdoc/>
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
if (_popup != null)
{
_popup.Opened -= PopupOpened;
_popup.Closed -= PopupClosed;
_popup.DependencyResolver = null;
}
_popup = e.NameScope.Find<Popup>("PART_Popup");
if (_popup != null)
{
_popup.DependencyResolver = DependencyResolver.Instance;
_popup.Opened += PopupOpened;
_popup.Closed += PopupClosed;
}
}
protected override void UpdateDataValidation<T>(AvaloniaProperty<T> property, BindingValue<T> value)
{
base.UpdateDataValidation(property, value);
if (property == CommandProperty)
{
if (value.Type == BindingValueType.BindingError)
{
if (_commandCanExecute)
{
_commandCanExecute = false;
UpdateIsEffectivelyEnabled();
}
}
}
}
/// <summary>
/// Closes all submenus of the menu item.
/// </summary>
private void CloseSubmenus()
{
foreach (var child in ((IMenuItem)this).SubItems)
{
child.IsSubMenuOpen = false;
}
}
/// <summary>
/// Called when the <see cref="Command"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void CommandChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is MenuItem menuItem)
{
if (((ILogical)menuItem).IsAttachedToLogicalTree)
{
if (e.OldValue is ICommand oldCommand)
{
oldCommand.CanExecuteChanged -= menuItem.CanExecuteChanged;
}
if (e.NewValue is ICommand newCommand)
{
newCommand.CanExecuteChanged += menuItem.CanExecuteChanged;
}
}
menuItem.CanExecuteChanged(menuItem, EventArgs.Empty);
}
}
/// <summary>
/// Called when the <see cref="ICommand.CanExecuteChanged"/> event fires.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void CanExecuteChanged(object sender, EventArgs e)
{
var canExecute = Command == null || Command.CanExecute(CommandParameter);
if (canExecute != _commandCanExecute)
{
_commandCanExecute = canExecute;
UpdateIsEffectivelyEnabled();
}
}
/// <summary>
/// Called when the <see cref="HeaderedSelectingItemsControl.Header"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void HeaderChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.NewValue is string newValue && newValue == "-")
{
PseudoClasses.Add(":separator");
Focusable = false;
}
else if (e.OldValue is string oldValue && oldValue == "-")
{
PseudoClasses.Remove(":separator");
Focusable = true;
}
}
/// <summary>
/// Called when the <see cref="Icon"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void IconChanged(AvaloniaPropertyChangedEventArgs e)
{
var oldValue = e.OldValue as ILogical;
var newValue = e.NewValue as ILogical;
if (oldValue != null)
{
LogicalChildren.Remove(oldValue);
PseudoClasses.Remove(":icon");
}
if (newValue != null)
{
LogicalChildren.Add(newValue);
PseudoClasses.Add(":icon");
}
}
/// <summary>
/// Called when the <see cref="IsSelected"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void IsSelectedChanged(AvaloniaPropertyChangedEventArgs e)
{
if ((bool)e.NewValue!)
{
Focus();
}
}
/// <summary>
/// Called when the <see cref="IsSubMenuOpen"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void SubMenuOpenChanged(AvaloniaPropertyChangedEventArgs e)
{
var value = (bool)e.NewValue!;
if (value)
{
RaiseEvent(new RoutedEventArgs(SubmenuOpenedEvent));
IsSelected = true;
PseudoClasses.Add(":open");
}
else
{
CloseSubmenus();
SelectedIndex = -1;
PseudoClasses.Remove(":open");
}
}
/// <summary>
/// Called when the submenu's <see cref="Popup"/> is opened.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void PopupOpened(object sender, EventArgs e)
{
var selected = SelectedIndex;
if (selected != -1)
{
var container = ItemContainerGenerator.ContainerFromIndex(selected);
container?.Focus();
}
}
/// <summary>
/// Called when the submenu's <see cref="Popup"/> is closed.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void PopupClosed(object sender, EventArgs e)
{
SelectedItem = null;
}
/// <summary>
/// A dependency resolver which returns a <see cref="MenuItemAccessKeyHandler"/>.
/// </summary>
private class DependencyResolver : IAvaloniaDependencyResolver
{
/// <summary>
/// Gets the default instance of <see cref="DependencyResolver"/>.
/// </summary>
public static readonly DependencyResolver Instance = new DependencyResolver();
/// <summary>
/// Gets a service of the specified type.
/// </summary>
/// <param name="serviceType">The service type.</param>
/// <returns>A service of the requested type.</returns>
public object GetService(Type serviceType)
{
if (serviceType == typeof(IAccessKeyHandler))
{
return new MenuItemAccessKeyHandler();
}
else
{
return AvaloniaLocator.Current.GetService(serviceType);
}
}
}
}
}
| |
// 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 gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.ApigeeConnect.V1
{
/// <summary>Settings for <see cref="TetherClient"/> instances.</summary>
public sealed partial class TetherSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="TetherSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="TetherSettings"/>.</returns>
public static TetherSettings GetDefault() => new TetherSettings();
/// <summary>Constructs a new <see cref="TetherSettings"/> object with default settings.</summary>
public TetherSettings()
{
}
private TetherSettings(TetherSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
EgressSettings = existing.EgressSettings;
EgressStreamingSettings = existing.EgressStreamingSettings;
OnCopy(existing);
}
partial void OnCopy(TetherSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>TetherClient.Egress</c> and
/// <c>TetherClient.EgressAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings EgressSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>
/// <see cref="gaxgrpc::BidirectionalStreamingSettings"/> for calls to <c>TetherClient.Egress</c> and
/// <c>TetherClient.EgressAsync</c>.
/// </summary>
/// <remarks>The default local send queue size is 100.</remarks>
public gaxgrpc::BidirectionalStreamingSettings EgressStreamingSettings { get; set; } = new gaxgrpc::BidirectionalStreamingSettings(100);
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="TetherSettings"/> object.</returns>
public TetherSettings Clone() => new TetherSettings(this);
}
/// <summary>
/// Builder class for <see cref="TetherClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class TetherClientBuilder : gaxgrpc::ClientBuilderBase<TetherClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public TetherSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public TetherClientBuilder()
{
UseJwtAccessWithScopes = TetherClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref TetherClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<TetherClient> task);
/// <summary>Builds the resulting client.</summary>
public override TetherClient Build()
{
TetherClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<TetherClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<TetherClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private TetherClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return TetherClient.Create(callInvoker, Settings);
}
private async stt::Task<TetherClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return TetherClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => TetherClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => TetherClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => TetherClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>Tether client wrapper, for convenient use.</summary>
/// <remarks>
/// Tether provides a way for the control plane to send HTTP API requests to
/// services in data planes that runs in a remote datacenter without
/// requiring customers to open firewalls on their runtime plane.
/// </remarks>
public abstract partial class TetherClient
{
/// <summary>
/// The default endpoint for the Tether service, which is a host of "apigeeconnect.googleapis.com" and a port of
/// 443.
/// </summary>
public static string DefaultEndpoint { get; } = "apigeeconnect.googleapis.com:443";
/// <summary>The default Tether scopes.</summary>
/// <remarks>
/// The default Tether scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="TetherClient"/> using the default credentials, endpoint and settings. To
/// specify custom credentials or other settings, use <see cref="TetherClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="TetherClient"/>.</returns>
public static stt::Task<TetherClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new TetherClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="TetherClient"/> using the default credentials, endpoint and settings. To
/// specify custom credentials or other settings, use <see cref="TetherClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="TetherClient"/>.</returns>
public static TetherClient Create() => new TetherClientBuilder().Build();
/// <summary>
/// Creates a <see cref="TetherClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="TetherSettings"/>.</param>
/// <returns>The created <see cref="TetherClient"/>.</returns>
internal static TetherClient Create(grpccore::CallInvoker callInvoker, TetherSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
Tether.TetherClient grpcClient = new Tether.TetherClient(callInvoker);
return new TetherClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC Tether client</summary>
public virtual Tether.TetherClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Bidirectional streaming methods for
/// <see cref="Egress(gaxgrpc::CallSettings,gaxgrpc::BidirectionalStreamingSettings)"/>.
/// </summary>
public abstract partial class EgressStream : gaxgrpc::BidirectionalStreamingBase<EgressResponse, EgressRequest>
{
}
/// <summary>
/// Egress streams egress requests and responses. Logically, this is not
/// actually a streaming request, but uses streaming as a mechanism to flip
/// the client-server relationship of gRPC so that the server can act as a
/// client.
/// The listener, the RPC server, accepts connections from the dialer,
/// the RPC client.
/// The listener streams http requests and the dialer streams http responses.
/// </summary>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <param name="streamingSettings">If not null, applies streaming overrides to this RPC call.</param>
/// <returns>The client-server stream.</returns>
public virtual EgressStream Egress(gaxgrpc::CallSettings callSettings = null, gaxgrpc::BidirectionalStreamingSettings streamingSettings = null) =>
throw new sys::NotImplementedException();
}
/// <summary>Tether client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Tether provides a way for the control plane to send HTTP API requests to
/// services in data planes that runs in a remote datacenter without
/// requiring customers to open firewalls on their runtime plane.
/// </remarks>
public sealed partial class TetherClientImpl : TetherClient
{
private readonly gaxgrpc::ApiBidirectionalStreamingCall<EgressResponse, EgressRequest> _callEgress;
/// <summary>
/// Constructs a client wrapper for the Tether service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="TetherSettings"/> used within this client.</param>
public TetherClientImpl(Tether.TetherClient grpcClient, TetherSettings settings)
{
GrpcClient = grpcClient;
TetherSettings effectiveSettings = settings ?? TetherSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callEgress = clientHelper.BuildApiCall<EgressResponse, EgressRequest>(grpcClient.Egress, effectiveSettings.EgressSettings, effectiveSettings.EgressStreamingSettings);
Modify_ApiCall(ref _callEgress);
Modify_EgressApiCall(ref _callEgress);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiBidirectionalStreamingCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_EgressApiCall(ref gaxgrpc::ApiBidirectionalStreamingCall<EgressResponse, EgressRequest> call);
partial void OnConstruction(Tether.TetherClient grpcClient, TetherSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC Tether client</summary>
public override Tether.TetherClient GrpcClient { get; }
partial void Modify_EgressResponseCallSettings(ref gaxgrpc::CallSettings settings);
partial void Modify_EgressResponseRequest(ref EgressResponse request);
internal sealed partial class EgressStreamImpl : EgressStream
{
/// <summary>Construct the bidirectional streaming method for <c>Egress</c>.</summary>
/// <param name="service">The service containing this streaming method.</param>
/// <param name="call">The underlying gRPC duplex streaming call.</param>
/// <param name="writeBuffer">
/// The <see cref="gaxgrpc::BufferedClientStreamWriter{EgressResponse}"/> instance associated with this
/// streaming call.
/// </param>
public EgressStreamImpl(TetherClientImpl service, grpccore::AsyncDuplexStreamingCall<EgressResponse, EgressRequest> call, gaxgrpc::BufferedClientStreamWriter<EgressResponse> writeBuffer)
{
_service = service;
GrpcCall = call;
_writeBuffer = writeBuffer;
}
private TetherClientImpl _service;
private gaxgrpc::BufferedClientStreamWriter<EgressResponse> _writeBuffer;
public override grpccore::AsyncDuplexStreamingCall<EgressResponse, EgressRequest> GrpcCall { get; }
private EgressResponse ModifyRequest(EgressResponse request)
{
_service.Modify_EgressResponseRequest(ref request);
return request;
}
public override stt::Task TryWriteAsync(EgressResponse message) =>
_writeBuffer.TryWriteAsync(ModifyRequest(message));
public override stt::Task WriteAsync(EgressResponse message) => _writeBuffer.WriteAsync(ModifyRequest(message));
public override stt::Task TryWriteAsync(EgressResponse message, grpccore::WriteOptions options) =>
_writeBuffer.TryWriteAsync(ModifyRequest(message), options);
public override stt::Task WriteAsync(EgressResponse message, grpccore::WriteOptions options) =>
_writeBuffer.WriteAsync(ModifyRequest(message), options);
public override stt::Task TryWriteCompleteAsync() => _writeBuffer.TryWriteCompleteAsync();
public override stt::Task WriteCompleteAsync() => _writeBuffer.WriteCompleteAsync();
}
/// <summary>
/// Egress streams egress requests and responses. Logically, this is not
/// actually a streaming request, but uses streaming as a mechanism to flip
/// the client-server relationship of gRPC so that the server can act as a
/// client.
/// The listener, the RPC server, accepts connections from the dialer,
/// the RPC client.
/// The listener streams http requests and the dialer streams http responses.
/// </summary>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <param name="streamingSettings">If not null, applies streaming overrides to this RPC call.</param>
/// <returns>The client-server stream.</returns>
public override TetherClient.EgressStream Egress(gaxgrpc::CallSettings callSettings = null, gaxgrpc::BidirectionalStreamingSettings streamingSettings = null)
{
Modify_EgressResponseCallSettings(ref callSettings);
gaxgrpc::BidirectionalStreamingSettings effectiveStreamingSettings = streamingSettings ?? _callEgress.StreamingSettings;
grpccore::AsyncDuplexStreamingCall<EgressResponse, EgressRequest> call = _callEgress.Call(callSettings);
gaxgrpc::BufferedClientStreamWriter<EgressResponse> writeBuffer = new gaxgrpc::BufferedClientStreamWriter<EgressResponse>(call.RequestStream, effectiveStreamingSettings.BufferedClientWriterCapacity);
return new EgressStreamImpl(this, call, writeBuffer);
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ModeGridScript : MonoBehaviour {
// Positions
private Vector3 tapboxPosition_0 = new Vector3(-120f, 120f, LAYER_TAPBOX);
private Vector3 tapboxPosition_1 = new Vector3( -40f, 120f, LAYER_TAPBOX);
private Vector3 tapboxPosition_2 = new Vector3( 40f, 120f, LAYER_TAPBOX);
private Vector3 tapboxPosition_3 = new Vector3( 120f, 120f, LAYER_TAPBOX);
private Vector3 tapboxPosition_4 = new Vector3(-120f, 40f, LAYER_TAPBOX);
private Vector3 tapboxPosition_5 = new Vector3( -40f, 40f, LAYER_TAPBOX);
private Vector3 tapboxPosition_6 = new Vector3( 40f, 40f, LAYER_TAPBOX);
private Vector3 tapboxPosition_7 = new Vector3( 120f, 40f, LAYER_TAPBOX);
private Vector3 tapboxPosition_8 = new Vector3(-120f, -40f, LAYER_TAPBOX);
private Vector3 tapboxPosition_9 = new Vector3( -40f, -40f, LAYER_TAPBOX);
private Vector3 tapboxPosition_10 = new Vector3( 40f, -40f, LAYER_TAPBOX);
private Vector3 tapboxPosition_11 = new Vector3( 120f, -40f, LAYER_TAPBOX);
private Vector3 tapboxPosition_12 = new Vector3(-120f, -120f, LAYER_TAPBOX);
private Vector3 tapboxPosition_13 = new Vector3( -40f, -120f, LAYER_TAPBOX);
private Vector3 tapboxPosition_14 = new Vector3( 40f, -120f, LAYER_TAPBOX);
private Vector3 tapboxPosition_15 = new Vector3( 120f, -120f, LAYER_TAPBOX);
private Vector3 notesPositionOffset = new Vector3( 0, 0, -1f);
private Vector2 gridScale = new Vector2(1.4f, 1.4f);
// Layer constants
private const int LAYER_BG = 10;
private const int LAYER_TAPBOX = 5;
private const int LAYER_NOTES = 4;
private const int LAYER_INTERFACE = 0;
// Common Resources
private CommonScript common;
// Tapboxes
public GameObject tapboxPrefab;
private Dictionary<int, TapboxScript> touchMap;
private List<TapboxScript> tapboxes;
// Notes
public GameObject notesPrefab;
private NotesIterator notesIterator;
private LinkedList<NotesScript> notes; // TODO - Assume sorted
// Awake is called prior to Start()
void Awake() {
this.gameObject.tag = Tags.MAIN;
}
// Use this for initialization
void Start() {
SetupCommon();
SetupInput();
SetupTapboxes();
SetupNotes();
}
// Setup common and game state
void SetupCommon() {
common = (CommonScript)GameObject.Find("Common").GetComponent<CommonScript>();
}
// Setup touchmap
void SetupInput() {
touchMap = new Dictionary<int, TapboxScript>();
}
// Setup tapboxes and touch input
void SetupTapboxes() {
tapboxes = new List<TapboxScript>();
tapboxes.Add(InitTapbox(0, tapboxPosition_0));
tapboxes.Add(InitTapbox(1, tapboxPosition_1));
tapboxes.Add(InitTapbox(2, tapboxPosition_2));
tapboxes.Add(InitTapbox(3, tapboxPosition_3));
tapboxes.Add(InitTapbox(4, tapboxPosition_4));
tapboxes.Add(InitTapbox(5, tapboxPosition_5));
tapboxes.Add(InitTapbox(6, tapboxPosition_6));
tapboxes.Add(InitTapbox(7, tapboxPosition_7));
tapboxes.Add(InitTapbox(8, tapboxPosition_8));
tapboxes.Add(InitTapbox(9, tapboxPosition_9));
tapboxes.Add(InitTapbox(10, tapboxPosition_10));
tapboxes.Add(InitTapbox(11, tapboxPosition_11));
tapboxes.Add(InitTapbox(12, tapboxPosition_12));
tapboxes.Add(InitTapbox(13, tapboxPosition_13));
tapboxes.Add(InitTapbox(14, tapboxPosition_14));
tapboxes.Add(InitTapbox(15, tapboxPosition_15));
}
// Setup notes data
void SetupNotes() {
notesIterator = new NotesIterator(NotesData.SMOOOOCH_DATA); // TODO - hardcoded
notes = new LinkedList<NotesScript>();
}
// Initialize a tapbox
TapboxScript InitTapbox(int column, Vector3 position) {
GameObject tapboxObject = (GameObject)Instantiate(tapboxPrefab);
TapboxScript tapbox = tapboxObject.GetComponent<TapboxScript>();
tapbox.Setup(column);
tapboxObject.transform.position = position;
exSprite sprite = tapboxObject.GetComponent<exSprite>();
sprite.scale = gridScale;
return tapbox;
}
// Update is called once per frame
void Update () {
UpdateInput();
UpdateNotesList();
UpdateNotes();
}
// Check for keyboard, touch, and mouse input
void UpdateInput() {
// ESC / Android BACK button
if (Input.GetKey(KeyCode.Escape)) {
common.OnBackButton();
}
// Touch input
foreach (Touch touch in Input.touches) {
if (touch.phase == TouchPhase.Began) {
OnTapDown(touch.fingerId, touch.position);
} else if (touch.phase == TouchPhase.Ended) {
OnTapUp(touch.fingerId);
}
}
// Mouse click
if (Input.GetMouseButtonDown(0)) {
OnTapDown(0, Input.mousePosition);
} else if (Input.GetMouseButtonUp(0)) {
OnTapUp(0);
}
}
// Tap down event
void OnTapDown(int id, Vector2 position) {
if (!touchMap.ContainsKey(id)) { // Protect against double counts
if (common.gameOver) {
common.OnTapDown(id, position);
} else {
// Collision check via raycast
Ray ray = Camera.main.ScreenPointToRay(position);
RaycastHit hit;
// If hit
if (Physics.Raycast (ray, out hit)) {
// Check tag
GameObject hitObject = hit.collider.gameObject;
if (hitObject.tag.Equals(Tags.TAPBOX)) {
TapboxScript tapbox = hitObject.GetComponent<TapboxScript>();
// Animation
tapbox.PlayDownAnim();
// Add to dictionary
touchMap.Add(
id,
tapbox
);
// Check for notes
OnTapboxTap(tapbox);
}
}
}
}
}
// Tap up event
void OnTapUp(int id) {
if (touchMap.ContainsKey(id)) { // Protect against double counts
// Check dictionary
TapboxScript tapbox;
if (touchMap.TryGetValue(id, out tapbox)) {
// Animation
tapbox.PlayUpAnim();
// Remove from dictionary
touchMap.Remove(id);
// TODO - add lift note action
}
}
}
// Check for notes hit
void OnTapboxTap(TapboxScript tapbox) {
int column = tapbox.column;
foreach (NotesScript note in notes) {
if (note.column == column) {
if (note.state == NotesScript.NotesState.ACTIVE) {
common.OnNoteHit(note);
break;
}
}
}
}
// Remove completed notes, add new ones
private int rowCount = 0;
void UpdateNotesList() {
// Game over check
if (common.gameOver) return;
// Remove completed notes, assumes sequential removal
while(notes.Count > 0 && notes.First.Value.state == NotesScript.NotesState.REMOVE) {
Destroy(notes.First.Value.gameObject);
notes.RemoveFirst();
}
// Add new notes
while (notesIterator.hasNext()) {
// If in the look-ahead range
if (notesIterator.nextTime() - common.musicTime < CommonScript.TIME_LOOKAHEAD) {
GameObject notesObject = (GameObject)Instantiate(notesPrefab);
NotesScript note = notesObject.GetComponent<NotesScript>();
notesIterator.next(note);
// For grid
note.column += rowCount * 4;
rowCount++;
if (rowCount > 3) rowCount = 0;
Vector3 position;
switch(note.column) {
case 0: position = tapboxPosition_0; break;
case 1: position = tapboxPosition_1; break;
case 2: position = tapboxPosition_2; break;
case 3: position = tapboxPosition_3; break;
case 4: position = tapboxPosition_4; break;
case 5: position = tapboxPosition_5; break;
case 6: position = tapboxPosition_6; break;
case 7: position = tapboxPosition_7; break;
case 8: position = tapboxPosition_8; break;
case 9: position = tapboxPosition_9; break;
case 10: position = tapboxPosition_10; break;
case 11: position = tapboxPosition_11; break;
case 12: position = tapboxPosition_12; break;
case 13: position = tapboxPosition_13; break;
case 14: position = tapboxPosition_14; break;
case 15: position = tapboxPosition_15; break;
default: position = new Vector3(0, 0, 0); break; // Error
}
position += notesPositionOffset;
note.gameObject.transform.position = position;
// Add
notes.AddLast(new LinkedListNode<NotesScript>(note));
} else {
break;
}
}
// Check game done
if (notes.Count == 0 && !notesIterator.hasNext()) {
foreach (TapboxScript tapbox in tapboxes) {
tapbox.gameObject.active = false;
}
common.OnGameOver();
}
}
// Update notes states
void UpdateNotes() {
// Game over check
if (common.gameOver) return;
// Iterate through each active node
foreach (NotesScript note in notes) {
float timeDiff = common.GetTimeDiff(note);
common.CheckAutoPlay(note, timeDiff);
common.UpdateNoteState(note, timeDiff);
// Update size
exSprite sprite = note.gameObject.GetComponent<exSprite>();
if (timeDiff > 0) { // Before tapbox
float multiplier = 1 - timeDiff / CommonScript.TIME_ONSCREEN;
if (multiplier <= 0f) {
// Don't draw
note.gameObject.active = false;
} else {
sprite.scale = gridScale * multiplier;
// Draw
note.gameObject.active = true;
}
} else {
sprite.scale = gridScale;
note.gameObject.active = true;
}
}
}
}
| |
/*
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.ComponentModel;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace Adxstudio.Xrm.Web.UI.WebControls
{
/// <summary>
/// Provide a visual indicator of the current step within a predefined number of steps on a multi-step process. Progress trackers are designed to help users through a multi-step process and it is vital that such trackers be well designed in order to keep users informed about what section they are currently on, what section they have completed, and what tasks remain.
/// </summary>
[Description("Provide a visual indicator of the current step within a predefined number of steps on a multi-step process.")]
[ToolboxData(@"<{0}:ProgresIndicator runat=""server""></{0}:ProgressIndicator>")]
[DefaultProperty("")]
public class ProgressIndicator : CompositeDataBoundControl
{
/// <summary>
/// Property Name of the step index of the data item in the datasource.
/// </summary>
[Description("Property Name of the step index of the data item in the datasource.")]
[DefaultValue("Index")]
public string IndexDataPropertyName
{
get
{
var text = (string)ViewState["IndexDataPropertyName"];
return string.IsNullOrWhiteSpace(text) ? "Index" : text;
}
set
{
ViewState["IndexDataPropertyName"] = value;
}
}
/// <summary>
/// Property Name of the step index of the data item in the datasource.
/// </summary>
[Description("Property Name of the step title of the data item in the datasource.")]
[DefaultValue("Title")]
public string TitleDataPropertyName
{
get
{
var text = (string)ViewState["TitleDataPropertyName"];
return string.IsNullOrWhiteSpace(text) ? "Title" : text;
}
set
{
ViewState["TitleDataPropertyName"] = value;
}
}
/// <summary>
/// Property Name of the data item in the datasource of the step indicating the step is the current active step.
/// </summary>
[Description("Property Name of the data item in the datasource of the step indicating the step is the current active step.")]
[DefaultValue("IsActive")]
public string ActiveDataPropertyName
{
get
{
var text = (string)ViewState["ActiveDataPropertyName"];
return string.IsNullOrWhiteSpace(text) ? "IsActive" : text;
}
set
{
ViewState["ActiveDataPropertyName"] = value;
}
}
/// <summary>
/// Property Name of the data item in the datasource of the step indicating the step is completed.
/// </summary>
[Description("Property Name of the data item in the datasource of the step indicating the step is completed.")]
[DefaultValue("IsCompleted")]
public string CompletedDataPropertyName
{
get
{
var text = (string)ViewState["CompletedDataPropertyName"];
return string.IsNullOrWhiteSpace(text) ? "IsCompleted" : text;
}
set
{
ViewState["CompletedDataPropertyName"] = value;
}
}
/// <summary>
/// Position of the control. One of the following values; top, bottom, left, right.
/// </summary>
[Description("Position of the control. One of the following values; top, bottom, left, right.")]
[DefaultValue("")]
public string Position
{
get
{
var text = (string)ViewState["Position"];
return string.IsNullOrWhiteSpace(text) ? string.Empty : text;
}
set
{
ViewState["Position"] = value;
}
}
/// <summary>
/// Indicates if the number/index of the step should be prepended to the step's title.
/// </summary>
[Description("Indicates if the number/index of the step should be prepended to the step's title.")]
[DefaultValue(true)]
public bool PrependStepIndexToTitle
{
get { return (bool)(ViewState["PrependStepIndexToTitle"] ?? true); }
set { ViewState["PrependStepIndexToTitle"] = value; }
}
/// <summary>
/// Indicates if the number/index of the start step is zero.
/// </summary>
[Description("Indicates if the number/index of the start step is zero.")]
[DefaultValue(true)]
public bool ZeroBasedIndex
{
get { return (bool)(ViewState["ZeroBasedIndex"] ?? true); }
set { ViewState["ZeroBasedIndex"] = value; }
}
/// <summary>
/// Type of the control. One of the following values; title, numeric, progressbar.
/// </summary>
[Description("Type of the control. One of the following values; title, numeric, progressbar.")]
[DefaultValue("title")]
public string Type
{
get
{
var text = (string)ViewState["Type"];
return string.IsNullOrWhiteSpace(text) ? "title" : text;
}
set
{
ViewState["Type"] = value;
}
}
/// <summary>
/// Prefix used for the title of the 'numeric' type of progress control.
/// </summary>
[Description("Prefix used for the title of the 'numeric' type of progress control.")]
[DefaultValue("Step")]
public string NumericPrefix
{
get
{
var text = (string)ViewState["NumericPrefix"];
return string.IsNullOrWhiteSpace(text) ? "Step" : text;
}
set
{
ViewState["NumericPrefix"] = value;
}
}
/// <summary>
/// Indicates if the last step should be included in computing the percent of progress.
/// </summary>
[Description("Indicates if the last step should be included in computing the percent of progress.")]
[DefaultValue(false)]
public bool CountLastStepInProgress
{
get { return (bool)(ViewState["CountLastStepInProgress"] ?? true); }
set { ViewState["CountLastStepInProgress"] = value; }
}
protected override HtmlTextWriterTag TagKey
{
get { return HtmlTextWriterTag.Div; }
}
protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
{
Controls.Clear();
int count;
switch (Type.ToLowerInvariant())
{
case "numeric":
count = RenderTypeNumeric(dataSource);
break;
case "progressbar":
count = RenderTypeProgressBar(dataSource);
break;
default:
count = RenderTypeTitle(dataSource);
break;
}
return count;
}
protected void AddStep(object dataItem, Control container)
{
if (dataItem == null)
{
return;
}
var title = DataBinder.GetPropertyValue(dataItem, TitleDataPropertyName, null);
var indexValue = DataBinder.GetPropertyValue(dataItem, IndexDataPropertyName);
var activeValue = DataBinder.GetPropertyValue(dataItem, ActiveDataPropertyName);
var completedValue = DataBinder.GetPropertyValue(dataItem, CompletedDataPropertyName);
var index = Convert.ToInt32(indexValue);
var active = Convert.ToBoolean(activeValue);
var completed = Convert.ToBoolean(completedValue);
var step = new ProgressStep(index, title, active, completed);
var item = new HtmlGenericControl("li");
item.AddClass("list-group-item");
item.InnerHtml = PrependStepIndexToTitle ? string.Format("<span class='number'>{0}</span>{1}", ZeroBasedIndex ? (step.Index + 1) : step.Index, step.Title) : step.Title;
if (step.IsActive)
{
item.AddClass("active");
}
else if (step.IsCompleted)
{
item.AddClass("text-muted list-group-item-success");
item.InnerHtml += "<span class='glyphicon glyphicon-ok'></span>";
}
else
{
item.AddClass("incomplete");
}
container.Controls.Add(item);
}
protected int RenderTypeTitle(IEnumerable dataSource)
{
var count = 0;
var className = "progress list-group";
var controlContainer = new HtmlGenericControl("ol");
var e = dataSource.GetEnumerator();
if (string.IsNullOrWhiteSpace(Position))
{
controlContainer.Attributes["class"] = className;
}
else
{
switch (Position.ToLowerInvariant())
{
case "top":
className += " top";
break;
case "bottom":
className += " bottom";
break;
case "left":
className += " left";
CssClass += " col-sm-3 col-md-2";
break;
case "right":
className += " right";
CssClass += " col-sm-3 col-sm-push-9 col-md-2 col-md-push-10";
break;
}
controlContainer.Attributes["class"] = className;
}
while (e.MoveNext())
{
AddStep(e.Current, controlContainer);
count++;
}
Controls.Add(controlContainer);
return count;
}
protected int RenderTypeNumeric(IEnumerable dataSource)
{
var count = 0;
var progressIndex = 0;
var className = "progress-numeric";
var e = dataSource.GetEnumerator();
if (string.IsNullOrWhiteSpace(Position))
{
CssClass = string.Join(" ", CssClass, className);
}
else
{
switch (Position.ToLowerInvariant())
{
case "top":
className += " top";
break;
case "bottom":
className += " bottom";
break;
case "left":
className += " left";
CssClass += " col-sm-3 col-md-2";
break;
case "right":
className += " right";
CssClass += " col-sm-3 col-sm-push-9 col-md-2 col-md-push-10";
break;
}
CssClass = string.Join(" ", CssClass, className);
}
while (e.MoveNext())
{
if (e.Current == null)
{
continue;
}
var indexValue = DataBinder.GetPropertyValue(e.Current, IndexDataPropertyName);
var activeValue = DataBinder.GetPropertyValue(e.Current, ActiveDataPropertyName);
var index = Convert.ToInt32(indexValue);
var active = Convert.ToBoolean(activeValue);
if (active)
{
progressIndex = ZeroBasedIndex ? index + 1 : index;
}
count++;
}
var literal = new LiteralControl { Text = string.Format("{0} <span class='number'>{1}</span> of <span class='number total'>{2}</span>", NumericPrefix, progressIndex, count) };
Controls.Add(literal);
return count;
}
protected int RenderTypeProgressBar(IEnumerable dataSource)
{
var count = 0;
var progressIndex = 0;
var className = "progress";
var controlContainer = new HtmlGenericControl("div");
var e = dataSource.GetEnumerator();
if (string.IsNullOrWhiteSpace(Position))
{
CssClass = string.Join(" ", CssClass, className);
}
else
{
switch (Position.ToLowerInvariant())
{
case "top":
className += " top";
break;
case "bottom":
className += " bottom";
break;
case "left":
className += " left";
CssClass += " col-sm-3 col-md-2";
break;
case "right":
className += " right";
CssClass += " col-sm-3 col-sm-push-9 col-md-2 col-md-push-10";
break;
}
CssClass = string.Join(" ", CssClass, className);
}
while (e.MoveNext())
{
if (e.Current == null)
{
continue;
}
var indexValue = DataBinder.GetPropertyValue(e.Current, IndexDataPropertyName);
var activeValue = DataBinder.GetPropertyValue(e.Current, ActiveDataPropertyName);
var index = Convert.ToInt32(indexValue);
var active = Convert.ToBoolean(activeValue);
if (active)
{
if (ZeroBasedIndex)
{
index++;
}
progressIndex = index > 0 ? index - 1 : 0;
}
count++;
}
controlContainer.Attributes["class"] = "bar progress-bar";
double percent = 0;
if (count > 0)
{
if (!CountLastStepInProgress)
{
percent = (double)(progressIndex * 100) / (count - 1);
}
else
{
percent = (double)(progressIndex * 100) / count;
}
}
var progress = Math.Floor(percent);
controlContainer.Attributes["style"] = string.Format("width: {0}%;", progress);
controlContainer.Attributes["role"] = "progressbar";
controlContainer.Attributes["aria-valuemin"] = "0";
controlContainer.Attributes["aria-valuemax"] = "100";
controlContainer.Attributes["aria-valuenow"] = progress.ToString(CultureInfo.InvariantCulture);
if (progress.CompareTo(0) == 0)
{
controlContainer.Attributes["class"] = controlContainer.Attributes["class"] + " zero";
}
controlContainer.InnerHtml = string.Format("{0}%", progress);
Controls.Add(controlContainer);
return count;
}
}
/// <summary>
/// Step of a progress indicator.
/// </summary>
public class ProgressStep
{
/// <summary>
/// Initialization of the ProgressStep class.
/// </summary>
public ProgressStep()
{
}
/// <summary>
/// Initialization of the ProgressStep class.
/// </summary>
/// <param name="index">Step index/number</param>
/// <param name="title">Title of the step</param>
/// <param name="isActive">True if the step is the current active</param>
/// <param name="isCompleted">True if the step has been completed</param>
public ProgressStep(int index, string title, bool isActive, bool isCompleted)
{
Index = index;
Title = title;
IsActive = isActive;
IsCompleted = isCompleted;
}
/// <summary>
/// Number of the step.
/// </summary>
public int Index { get; set; }
/// <summary>
/// Label for the step.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Indicates this is the current step.
/// </summary>
public bool IsActive { get; set; }
/// <summary>
/// Indicates step has been completed.
/// </summary>
public bool IsCompleted { get; set; }
}
}
| |
// 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 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Cdn
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// OperationsOperations operations.
/// </summary>
internal partial class OperationsOperations : IServiceOperations<CdnManagementClient>, IOperationsOperations
{
/// <summary>
/// Initializes a new instance of the OperationsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal OperationsOperations(CdnManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the CdnManagementClient
/// </summary>
public CdnManagementClient Client { get; private set; }
/// <summary>
/// Lists all of the available CDN REST API operations.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<Operation>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Cdn/operations").ToString();
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<Operation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<Operation>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.ScenarioTest.Mocks;
using Microsoft.Azure.Graph.RBAC;
using Microsoft.Azure.Management.Authorization;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Test;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
using Microsoft.WindowsAzure.Management.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.ServiceManagemenet.Common.Models;
using Xunit.Abstractions;
using RestTestFramework = Microsoft.Rest.ClientRuntime.Azure.TestFramework;
namespace Microsoft.Azure.Commands.ScenarioTest.SqlTests
{
using Common.Authentication.Abstractions;
using ResourceManager.Common;
using System.IO;
public class SqlTestsBase : RMTestBase
{
protected SqlEvnSetupHelper helper;
private const string TenantIdKey = "TenantId";
private const string DomainKey = "Domain";
public string UserDomain { get; private set; }
protected SqlTestsBase(ITestOutputHelper output)
{
helper = new SqlEvnSetupHelper();
XunitTracingInterceptor tracer = new XunitTracingInterceptor(output);
XunitTracingInterceptor.AddToContext(tracer);
helper.TracingInterceptor = tracer;
}
protected virtual void SetupManagementClients(RestTestFramework.MockContext context)
{
var sqlClient = GetSqlClient(context);
var sqlLegacyClient = GetLegacySqlClient();
var resourcesClient = GetResourcesClient();
helper.SetupSomeOfManagementClients(sqlClient, sqlLegacyClient, resourcesClient);
}
protected void RunPowerShellTest(params string[] scripts)
{
TestExecutionHelpers.SetUpSessionAndProfile();
var callingClassType = TestUtilities.GetCallingClass(2);
var mockName = TestUtilities.GetCurrentMethodName(2);
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("Microsoft.Resources", null);
d.Add("Microsoft.Features", null);
d.Add("Microsoft.Authorization", null);
var providersToIgnore = new Dictionary<string, string>();
providersToIgnore.Add("Microsoft.Azure.Graph.RBAC.GraphRbacManagementClient", "1.42-previewInternal");
providersToIgnore.Add("Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01");
HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(true, d, providersToIgnore);
HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords");
// Enable undo functionality as well as mock recording
using (RestTestFramework.MockContext context = RestTestFramework.MockContext.Start(callingClassType, mockName))
{
SetupManagementClients(context);
helper.SetupEnvironment();
helper.SetupModules(AzureModule.AzureResourceManager,
"ScenarioTests\\Common.ps1",
"ScenarioTests\\" + this.GetType().Name + ".ps1",
helper.RMProfileModule,
helper.RMResourceModule,
helper.RMStorageDataPlaneModule,
helper.GetRMModulePath(@"AzureRM.Insights.psd1"),
helper.GetRMModulePath(@"AzureRM.Sql.psd1"),
"AzureRM.Storage.ps1",
"AzureRM.Resources.ps1");
helper.RunPowerShellTest(scripts);
}
}
protected Management.Sql.SqlManagementClient GetSqlClient(RestTestFramework.MockContext context)
{
Management.Sql.SqlManagementClient client =
context.GetServiceClient<Management.Sql.SqlManagementClient>(
RestTestFramework.TestEnvironmentFactory.GetTestEnvironment());
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
client.LongRunningOperationRetryTimeout = 0;
}
return client;
}
protected Management.Sql.LegacySdk.SqlManagementClient GetLegacySqlClient()
{
Management.Sql.LegacySdk.SqlManagementClient client =
TestBase.GetServiceClient<Management.Sql.LegacySdk.SqlManagementClient>(
new CSMTestEnvironmentFactory());
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
client.LongRunningOperationInitialTimeout = 0;
client.LongRunningOperationRetryTimeout = 0;
}
return client;
}
protected StorageManagementClient GetStorageClient()
{
StorageManagementClient client = TestBase.GetServiceClient<StorageManagementClient>(new RDFETestEnvironmentFactory());
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
client.LongRunningOperationInitialTimeout = 0;
client.LongRunningOperationRetryTimeout = 0;
}
return client;
}
protected ResourceManagementClient GetResourcesClient()
{
ResourceManagementClient client = TestBase.GetServiceClient<ResourceManagementClient>(new CSMTestEnvironmentFactory());
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
client.LongRunningOperationInitialTimeout = 0;
client.LongRunningOperationRetryTimeout = 0;
}
return client;
}
protected AuthorizationManagementClient GetAuthorizationManagementClient()
{
AuthorizationManagementClient client = TestBase.GetServiceClient<AuthorizationManagementClient>(new CSMTestEnvironmentFactory());
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
client.LongRunningOperationInitialTimeout = 0;
client.LongRunningOperationRetryTimeout = 0;
}
return client;
}
protected GraphRbacManagementClient GetGraphClient(RestTestFramework.MockContext context)
{
var environment = RestTestFramework.TestEnvironmentFactory.GetTestEnvironment();
string tenantId = null;
if (HttpMockServer.Mode == HttpRecorderMode.Record)
{
tenantId = environment.Tenant;
UserDomain = environment.UserName.Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries).Last();
HttpMockServer.Variables[TenantIdKey] = tenantId;
HttpMockServer.Variables[DomainKey] = UserDomain;
}
else if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
if (HttpMockServer.Variables.ContainsKey(TenantIdKey))
{
tenantId = HttpMockServer.Variables[TenantIdKey];
AzureRmProfileProvider.Instance.Profile.DefaultContext.Tenant.Id = tenantId;
}
if (HttpMockServer.Variables.ContainsKey(DomainKey))
{
UserDomain = HttpMockServer.Variables[DomainKey];
AzureRmProfileProvider.Instance.Profile.DefaultContext.Tenant.Directory = UserDomain;
}
}
var client = context.GetGraphServiceClient<GraphRbacManagementClient>(environment);
client.TenantID = tenantId;
return client;
}
protected Management.Storage.StorageManagementClient GetStorageV2Client()
{
var client =
TestBase.GetServiceClient<Management.Storage.StorageManagementClient>(new CSMTestEnvironmentFactory());
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
client.LongRunningOperationInitialTimeout = 0;
client.LongRunningOperationRetryTimeout = 0;
}
return client;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.